Bird
Raised Fist0
Interview Prepbit-manipulationmediumAmazonFacebookGoogle

Single Number II (Three Copies)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize ones and twos to zero

We start with both 'ones' and 'twos' set to 0, meaning no bits have been seen yet.

💡 Initialization is crucial to correctly accumulate bit counts as we process numbers.
Line:ones = 0 twos = 0
💡 Starting from zero ensures the bitwise counters correctly reflect the input bits as we iterate.
📊
Single Number II (Three Copies) - Watch the Algorithm Execute, Step by Step
Watching each bitwise update helps you understand how the algorithm cleverly counts bits modulo three without extra memory.
Step 1/21
·Active fill★Answer cell
Initialize ones and twos
A
0
0
0
0
0
0
0
0
=0
B
0
0
0
0
0
0
0
0
=0
twos |= ones & num
A
0
0
0
0
0
0
0
0
=0
B
0
0
0
0
0
0
0
0
=0
💡 No bits set in twos because ones is zero
ones ^= num
A
0
1
0
=2
B
0
0
0
0
0
0
0
0
=0
💡 Ones now has bit 1 set (value 2)
common_mask = ~(ones & twos)
A
0
1
0
=2
B
0
0
0
0
0
0
0
0
=0
💡 common_mask is all 1s except bits where ones & twos overlap
ones &= common_mask
A
0
1
0
=2
B
0
0
0
0
0
0
0
0
=0
💡 Ones unchanged, still bit 1 set
twos &= common_mask
A
0
1
0
=2
B
0
0
0
0
0
0
0
0
=0
💡 Twos unchanged, zero
twos |= ones & num
A
0
1
0
=2
B
0
1
0
=2
💡 Twos bit 1 set, tracking bits seen twice
ones ^= num
A
0
0
0
0
0
0
0
0
=0
B
0
1
0
=2
💡 Ones cleared bit 1, now zero
common_mask = ~(ones & twos)
A
0
0
0
0
0
0
0
0
=0
B
0
1
0
=2
💡 common_mask all 1s, no bits cleared
ones &= common_mask
A
0
0
0
0
0
0
0
0
=0
B
0
1
0
=2
💡 Ones zero
twos &= common_mask
A
0
0
0
0
0
0
0
0
=0
B
0
1
0
=2
💡 Twos bit 1 set
twos |= ones & num
A
0
0
0
0
0
0
0
0
=0
B
0
1
0
=2
💡 Twos unchanged
ones ^= num
A
0
1
1
=3
B
0
1
0
=2
💡 Ones bits 0 and 1 set
common_mask = ~(ones & twos)
A
0
1
1
=3
B
0
1
0
=2
💡 common_mask clears bit 1
ones &= common_mask
A
0
1
=1
B
0
1
0
=2
💡 Ones bit 0 set only
twos &= common_mask
A
0
1
=1
B
0
0
0
0
0
0
0
0
=0
💡 Twos cleared
twos |= ones & num
A
0
1
=1
B
0
0
0
0
0
0
0
0
=0
💡 Twos unchanged
ones ^= num
A
0
1
1
=3
B
0
0
0
0
0
0
0
0
=0
💡 Ones bits 0 and 1 set
common_mask = ~(ones & twos)
A
0
1
1
=3
B
0
0
0
0
0
0
0
0
=0
💡 common_mask all 1s
ones &= common_mask; twos &= common_mask
A
0
1
1
=3
B
0
0
0
0
0
0
0
0
=0
💡 Ones holds unique number bits
return ones
A
0
1
1
=3
B
0
0
0
0
0
0
0
0
=0
──────
=
0
1
1
=3
💡 Unique number 3 isolated in ones

Key Takeaways

✓ The algorithm uses two bitmasks (ones and twos) to count bits modulo three without extra memory.

This insight is hard to see from code alone because the bitwise logic is subtle and non-intuitive.

✓ Bits that appear three times are cleared simultaneously from ones and twos using a common mask.

Visualizing the mask operation clarifies how the algorithm resets bits after triple occurrences.

✓ The final unique number is isolated in ones after processing all input numbers.

Seeing the bits in ones evolve step-by-step reveals how the unique number emerges.

Practice

(1/5)
1. Given the following code and input, what is the final returned list?
easy
A. [2, 5]
B. [5, 4]
C. [4, 5]
D. [2, 4]

Solution

  1. Step 1: Compute xor of all elements

    xor = 2 ^ 4 ^ 2 ^ 5 = (2 ^ 2) ^ 4 ^ 5 = 0 ^ 4 ^ 5 = 1 (binary 0001)
  2. Step 2: Find rightmost set bit and partition

    set_bit = xor & (-xor) = 1 & (-1) = 1. Partition nums by bit 1: group1 (bit set): 5, group2 (bit not set): 2,4,2. XOR group1 = 5, XOR group2 = 4.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches unique elements [OK]
Hint: Rightmost set bit partitions unique numbers correctly [OK]
Common Mistakes:
  • Mixing order of output
  • Incorrect xor calculation
  • Miscomputing set bit
2. You are given an array where every element appears exactly twice except for one element that appears only once. Which approach guarantees finding the unique element in linear time and constant space?
easy
A. Using a dynamic programming approach to track element counts
B. Sorting the array and then scanning to find the unique element
C. Using a brute force nested loop to count occurrences of each element
D. Using XOR operation to cancel out duplicates and find the single element

Solution

  1. Step 1: Understand problem constraints

    Every element except one appears twice, so duplicates cancel out under XOR.
  2. Step 2: Identify approach that leverages XOR properties

    XOR of a number with itself is zero, and XOR with zero is the number itself, so XORing all elements leaves the unique one.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    XOR approach runs in O(n) time and O(1) space [OK]
Hint: XOR cancels duplicates perfectly [OK]
Common Mistakes:
  • Sorting is O(n log n), not optimal
  • Brute force is O(n²), inefficient
  • DP is unrelated to this problem
3. The following code attempts to count set bits for all numbers from 0 to n using Brian Kernighan's trick. Identify the line containing the subtle bug that causes incorrect results.
def countBits(n):
    res = []
    for i in range(1, n + 1):
        count = 0
        x = i
        while x:
            x &= x - 1
            count += 1
        res.append(count)
    return res
medium
A. Line 3: for i in range(1, n + 1):
B. Line 2: res = []
C. Line 5: while x:
D. Line 7: res.append(count)

Solution

  1. Step 1: Check loop range correctness

    The loop starts from 1, missing 0, so the count for 0 is never computed or appended.
  2. Step 2: Consequence of missing 0

    Result array length is n instead of n+1, causing mismatch and incorrect output for input including 0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Including 0 is required to match problem specification [OK]
Hint: Loop must start at 0 to include zero count [OK]
Common Mistakes:
  • Starting loop at 1 instead of 0
  • Appending before counting
  • Incorrect while condition
4. Identify the bug in the following code that attempts to count the number of 1 bits in a signed 32-bit integer:
def hammingWeight(n: int) -> int:
    count = 0
    while n != 0:
        count += n & 1
        n >>= 1
    return count
medium
A. The loop condition 'while n != 0' causes infinite loop for negative numbers due to sign extension.
B. The bitwise AND operation 'n & 1' is incorrect; it should be logical AND 'n && 1'.
C. The right shift operator 'n >>= 1' should be replaced with left shift to count bits correctly.
D. The initial count variable should be initialized to 1 instead of 0.

Solution

  1. Step 1: Understand signed right shift behavior

    In Python, right shifting a negative number propagates the sign bit, so n never becomes zero.
  2. Step 2: Analyze loop condition

    Because n != 0 remains true for negative numbers, the loop never terminates, causing infinite loop.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Signed right shift on negative numbers causes infinite loop [OK]
Hint: Signed right shift on negatives causes infinite loop [OK]
Common Mistakes:
  • Confusing bitwise AND with logical AND
  • Wrong shift direction
  • Incorrect count initialization
5. Suppose the input array can contain duplicate numbers and missing numbers may appear multiple times (i.e., numbers can be reused). Which modification to the XOR partitioning approach correctly finds the two missing numbers?
hard
A. Use frequency counting with a hash map instead of XOR to handle duplicates.
B. Use the same XOR partitioning approach since duplicates cancel out in XOR.
C. Modify XOR approach to XOR each number multiple times equal to its frequency.
D. Sort the array and scan for missing numbers instead of XOR.

Solution

  1. Step 1: Understand impact of duplicates

    Duplicates break XOR approach because XOR assumes each number appears exactly once.
  2. Step 2: Choose correct approach

    Frequency counting with a hash map correctly tracks counts and identifies missing numbers even with duplicates.
  3. Step 3: Why other options fail

    Same XOR approach fails due to duplicates; modifying XOR by frequency is not feasible; sorting is O(n log n) and less efficient.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Frequency counting handles duplicates correctly [OK]
Hint: XOR fails with duplicates; frequency map handles counts [OK]
Common Mistakes:
  • Assuming XOR works with duplicates
  • Trying to XOR multiple times per frequency
  • Ignoring complexity of sorting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard