Bit Manipulation Technique

Medium Importance

Use direct bitwise operations (AND, OR, XOR, shifts) for ultra-fast, space-efficient computation.

BitwiseMathMaskingXOR
Time: O(1) / O(32)
•
Space: O(1)

When to Use Bit Manipulation:

Key problem characteristics and signals indicating that this technique is the optimal choice.

Finding unique single elements using XOR properties.

Bitmask dynamic programming and subset state representations.

Counting set bits (Hamming weight) and checking power-of-two.

Prerequisite Rule: Sliding window strictly applies to contiguous sequences (subarrays or substrings). For non-contiguous subsequences or when negative values invalidate monotonicity, prefix sum or dynamic programming approaches are standard.

Example Problem — Sum of Pair Equal to Target

The benchmark interview problem demonstrating the transition from quadratic brute force to linear optimality.

Problem Statement

Given a sorted array of integers arr[] and an integer target, determine whether there exists any pair of elements (arr[i], arr[j]) such that their sum equals the target.

Sample Input

arr = [1, 2, 4, 6, 8, 11], target = 10

Expected Output

True (Pair: 2 + 8 = 10 at indices [1, 4])

Explanation: Elements 2 (index 1) and 8 (index 4) sum up to 10, which exactly matches target.

Constraints: 2 <= arr.length <= 10^5, Array is sorted in ascending order.

Naive Method — O(n²) Time and O(1) Space

The baseline brute force approach recalculating candidates through nested loops.

Time: O(n²)Space: O(1)

The brute force approach generates all possible pairs of elements from the array using two nested loops and checks if the sum of any pair equals the target.

PythonBrute-Force Baseline · O(n²)
1// Code snippet is being prepared.

Why Naive Fails in Production & Interviews

For an array with n = 10⁵ elements, checking all pairs requires ~5 × 10⁹ operations, causing Time Limit Exceeded (TLE). It is blind to the sorted order of the sequence.

Bit Manipulation — O(n) Time and O(1) Space

The optimal strategy leveraging bit manipulation mechanics to achieve optimal time complexity.

Time: O(n)Space: O(1)

By maintaining moving pointers/boundaries, we can solve range queries and subarray problems in optimal O(n) time.

1

Initialize Pointers: Set initial boundary coordinates according to pattern constraints.

2

Evaluate Invariant: At each iteration, evaluate current state against problem constraints.

3

Advance Pointers: Advance or shrink boundary in O(1) to transition to next valid state.

Interactive Trace

Step-by-step trace showing invariant evaluation.

Bit Manipulation Algorithm Code

Complete runnable solution in Python, C++, Java, and JavaScript.

PythonStudyFlow Solution · Runnable Example
1// Code snippet is being prepared.

How does this work?

Invariant Proof & Why It Is Guaranteed to Never Miss a Valid Pair

The power of Two Pointers comes from sorted monotonicity: each comparison permanently discards an entire candidate element in O(1) time without risking false negatives.

1

1. Sorted Monotonicity Invariant

The array satisfies arr[0] <= arr[1] <= ... <= arr[n-1]. Consequently, fixing any index i and increasing j strictly increases arr[i] + arr[j]. Conversely, decreasing j strictly decreases the sum.

2

2. Why is discarding arr[right] safe when sum > target?

If arr[left] + arr[right] > target, then since arr[left] is the smallest active element, pairing arr[right] with any other element >= arr[left] will also exceed target. Thus arr[right] cannot participate in ANY valid pair. Decrementing right is 100% safe.

3

3. Why is discarding arr[left] safe when sum < target?

If arr[left] + arr[right] < target, then since arr[right] is the largest active element, pairing arr[left] with any other element <= arr[right] will be even smaller. Thus arr[left] cannot reach target with any remaining candidate. Incrementing left is 100% safe.

4

4. The Boundary Guarantee

Whichever pointer reaches its true coordinate first will halt while every subsequent comparison directs the other pointer straight toward it. Pointers never skip past the true solution.

Core Pattern Variations & Blueprints

Explore the 3 structural variations that power all bit manipulation interview problems. Click each variation to expand its blueprint, interactive dry run, and implementation.

Curated Practice Ladder

Master this pattern progressively through verified interview questions.

“Master the invariants,
and the solution
writes itself.”

Botanical foliage