Bird
Raised Fist0
Interview Prepbit-manipulationmediumAmazonGoogleFacebook

Subsets Using Bitmask

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize / Setup

Start with an empty subset represented by bitmask 0 (all bits cleared). The input array [1,2,3] is sorted (already sorted).

💡 Starting with an empty subset is the base case for building all subsets recursively.
Line:nums.sort() res = [] backtrack(0, [])
💡 The empty subset corresponds to bitmask 000 (binary), meaning no elements included.
📊
Subsets Using Bitmask - Watch the Algorithm Execute, Step by Step
Watching each step reveals how the bitmask corresponds to subset inclusion, making the abstract recursion concrete and easy to follow.
Step 1/19
·Active fill★Answer cell
Initialize empty subset
A
0
0
0
0
0
0
0
0
=0
B
────────────────
=
0
0
0
0
0
0
0
0
=0
💡 Bitmask 000 means no elements included yet.
Add subset to results
A
0
0
0
0
0
0
0
0
=0
B
────────────────
=
0
0
0
0
0
0
0
0
=0
💡 Empty subset corresponds to bitmask 000.
Include element 1
A
0
1
=1
B
────
=
0
1
=1
💡 Bit 0 set means element 1 included.
Add subset to results
A
0
1
=1
B
────
=
0
1
=1
💡 Subset [1] added.
Include element 2
A
0
1
1
=3
B
──────
=
0
1
1
=3
💡 Bits 1 and 0 set mean elements 1 and 2 included.
Add subset to results
A
0
1
1
=3
B
──────
=
0
1
1
=3
💡 Subset [1,2] added.
Include element 3
A
0
1
1
1
=7
B
────────
=
0
1
1
1
=7
💡 Bits 2,1,0 set mean all elements included.
Add subset to results
A
0
1
1
1
=7
B
────────
=
0
1
1
1
=7
💡 Full subset added.
Backtrack remove element 3
A
0
1
1
=3
B
💡 Bit 2 cleared, subset back to [1,2].
Include element 3 alone
A
0
1
0
0
=4
B
────────
=
0
1
0
0
=4
💡 Bit 2 set, bits 1 and 0 cleared.
Add subset to results
A
0
1
0
0
=4
B
────────
=
0
1
0
0
=4
💡 Subset [3] added.
Include elements 1 and 3
A
0
1
0
1
=5
B
────────
=
0
1
0
1
=5
💡 Bits 2 and 0 set, bit 1 cleared.
Add subset to results
A
0
1
0
1
=5
B
────────
=
0
1
0
1
=5
💡 Subset [1,3] added.
Include elements 2 and 3
A
0
1
1
0
=6
B
────────
=
0
1
1
0
=6
💡 Bits 2 and 1 set, bit 0 cleared.
Add subset to results
A
0
1
1
0
=6
B
────────
=
0
1
1
0
=6
💡 Subset [2,3] added.
Backtrack clear all
A
0
0
0
0
0
0
0
0
=0
B
💡 Bitmask reset to empty subset.
Include element 2 alone
A
0
1
0
=2
B
──────
=
0
1
0
=2
💡 Bit 1 set means element 2 included.
Add subset to results
A
0
1
0
=2
B
──────
=
0
1
0
=2
💡 Subset [2] added.
Complete recursion
A
0
0
0
0
0
0
0
0
=0
B
💡 All subsets generated.

Key Takeaways

✓ Each subset corresponds exactly to a bitmask where each bit indicates inclusion of an element.

This insight is hard to see from code alone because the bitmask representation is implicit in recursion.

✓ The recursion explores subsets by including or excluding elements, which corresponds to setting or clearing bits in the bitmask.

Visualizing bit changes clarifies how recursion builds subsets step-by-step.

✓ Backtracking removes elements by clearing bits, allowing exploration of all subset combinations without repetition.

Seeing bits cleared during backtracking concretely shows how the algorithm reverses decisions.

Practice

(1/5)
1. Given the following Python code to generate Gray code sequence, what is the output of grayCode(2)?
easy
A. [1, 0, 3, 2]
B. [0, 1, 2, 3]
C. [0, 1, 3, 2]
D. [0, 2, 3, 1]

Solution

  1. Step 1: Compute values for i in range(4)

    For i=0: 0 ^ (0>>1)=0; i=1: 1 ^ (0)=1; i=2: 2 ^ (1)=2^1=3; i=3: 3 ^ (1)=3^1=2
  2. Step 2: Collect results in list

    The sequence is [0, 1, 3, 2], which matches the Gray code property.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Manual XOR calculation confirms the sequence [0,1,3,2] [OK]
Hint: XOR with right-shifted index generates Gray code directly [OK]
Common Mistakes:
  • Confusing the order of XOR and shift
  • Off-by-one errors in range leading to missing or extra elements
  • Misinterpreting the output as binary numbers instead of integers
2. Consider the following code snippet that finds the single number in an array using XOR. What is the value of result after processing the third element in the input [2, 3, 2]?
easy
A. 3
B. 1
C. 0
D. 2

Solution

  1. Step 1: Trace result after first element (2)

    result = 0 · 2 = 2
  2. Step 2: Trace result after second element (3)

    result = 2 · 3 = 1
  3. Step 3: Trace result after third element (2)

    result = 1 · 2 = 3
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Final XOR result is 3, the unique element [OK]
Hint: XOR accumulates unique element progressively [OK]
Common Mistakes:
  • Off-by-one in loop iteration
  • Confusing XOR with addition
  • Misreading variable updates
3. You are given a sequence of integers representing bytes. You need to verify if this sequence forms a valid encoding where each character can be 1 to 4 bytes long, and continuation bytes must start with bits '10'. Which approach best guarantees an efficient and correct validation?
easy
A. Use a greedy approach that always assumes the longest possible character at each step.
B. Use a brute force approach checking each byte with nested conditions for all possible byte patterns.
C. Use dynamic programming to store valid prefixes and build up to the full sequence.
D. Use a single pass with a counter tracking how many continuation bytes are expected next.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires validating UTF-8 encoding where each character can be 1 to 4 bytes, and continuation bytes must start with '10'.
  2. Step 2: Identify the approach that efficiently tracks continuation bytes

    The single pass with a continuation byte counter efficiently tracks how many continuation bytes are expected, ensuring correctness and O(n) time.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Single pass with counter matches UTF-8 rules and is optimal [OK]
Hint: Track continuation bytes with a counter for linear validation [OK]
Common Mistakes:
  • Assuming greedy longest match always works
  • Using DP unnecessarily complicates the problem
4. What is the time complexity of generating an n-bit Gray code sequence using the optimal bitwise formula [i ^ (i >> 1) for i in range(1 << n)]?
medium
A. O(n)
B. O((2^n)!)
C. O(n * 2^n)
D. O(2^n)

Solution

  1. Step 1: Analyze the loop iteration count

    The list comprehension iterates over all integers from 0 to 2^n - 1, so 2^n iterations.
  2. Step 2: Analyze work per iteration

    Each iteration performs constant time bitwise operations (XOR and right shift), so O(1) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Total time is proportional to 2^n, not multiplied by n or factorial [OK]
Hint: Loop runs 2^n times with O(1) work each [OK]
Common Mistakes:
  • Confusing n with 2^n and claiming O(n)
  • Assuming bitwise operations cost O(n)
  • Mistaking factorial complexity from brute force backtracking
5. Identify the bug in the following code snippet for Single Number II using the bitwise FSM approach:
medium
A. Line with 'twos |= ones & num'
B. Line with 'ones ^= num'
C. Line with 'common_mask = ~(ones | twos)'
D. Line with 'ones &= common_mask'

Solution

  1. Step 1: Compare common_mask calculation with correct formula

    The correct mask is the negation of the AND of ones and twos, i.e., ~(ones & twos), not ~(ones | twos).
  2. Step 2: Understand impact of wrong mask

    Using OR instead of AND causes bits to be cleared incorrectly, failing to reset bits appearing thrice properly.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct mask uses AND, not OR, to clear bits appearing three times [OK]
Hint: Mask must clear bits appearing in both ones and twos simultaneously [OK]
Common Mistakes:
  • Using OR instead of AND in mask
  • Misordering bit updates
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