DSA
    intermediate

    Bit Manipulation

    Software Engineer path · lesson 47 of 99
    time O(1)
    space O(1)
    Operation
    a=120706050413120100
    b=100706050413021100
    result76543210
    Bits being combinedResult bit1 in the result1 still in x

    12 & 10: combine the bits column by column, from the right.

    Code (running line highlighted)
    1. 1for each bit i: r[i] = a[i] AND b[i] # 1 only if both are 1
    Bit operations
    0 / 8

    Tap any element in the diagram to inspect its state at this step.

    1 / 10

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Which operator?

    Sort

    Sort each trick by the bitwise operator that replaces the ?.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    AND (&)

    Drop items here

    OR (|)

    Drop items here

    XOR (^)

    Drop items here
    6 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Which property of XOR allows finding a unique number in pairs?

    Write the code

    Runs your solution

    Single Number

    Find the element that appears only once in an array where every other element appears twice.

    Example Cases

    Input:[2,2,1]
    Output:1
    Input:[4,1,2,1,2]
    Output:4
    Input:[1]
    Output:1
    javascript
    function singleNumber(nums) {
      // Your code here
    }

    The short version

    Think of light switches. Each bit is just a switch (ON/OFF). Bit manipulation allows you to flip specific switches or check patterns incredibly fast, far faster than doing math.

    In more depth

    Bitwise Power

    Bit manipulation involves working directly with the binary representations of data.

    Essential Tricks:

    XOR (^):
    x ^ x = 0
    x ^ 0 = x
    Use for finding unique elements or swapping without temp variable.
    AND (&):
    x & 1 checks if x is odd/even.
    x & (x-1) clears the lowest set bit (helps count set bits).
    Shift (<< >>): Multiply or divide by 2.

    When to reach for this

    • Low-level optimization
    • Representing sets using bitmaps
    • Finding unique numbers
    • Counting set bits (Hamming Weight)

    Interview Questions

    Amazon
    Google
    Apple
    Microsoft
    Facebook
    Amazon
    Facebook
    Bloomberg
    Google
    Microsoft
    Apple

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required