Bird
Raised Fist0
Interview Prepbit-manipulationhardGoogleAmazon

Generate All Permutations Using Bitmask DP

Choose your preparation mode4 modes available
</>
IDE
def generate_permutations(n: int) -> list:public List<List<Integer>> generatePermutations(int n)vector<vector<int>> generatePermutations(int n)function generatePermutations(n)
def generate_permutations(n):
    # Write your solution here
    pass
class Solution {
    public List<List<Integer>> generatePermutations(int n) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
using namespace std;

vector<vector<int>> generatePermutations(int n) {
    // Write your solution here
    return {};
}
function generatePermutations(n) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: [[0,1,2],[0,2,1],[1,2,0],[2,0,1],[2,1,0]]Missing permutation [1,0,2] due to greedy approach picking next element in ascending order only.✅ At each recursion step, iterate over all unused elements instead of picking the smallest only.
Wrong: [[0,0,1],[0,1,1],[1,0,0]]Elements reused multiple times due to missing or incorrect bitmask checks.✅ Use bitmask to mark elements as visited and skip those already included.
Wrong: [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1]]Off-by-one error in bitmask indexing causing last permutation missing.✅ Use (1 << i) consistently for element i's bit and check bounds carefully.
Wrong: Non-empty output for n=0Missing base case for n=0 returning empty list.✅ Add base case: if n == 0 return [].
Wrong: Timeout or crash on n=10Inefficient recursion without memoization or pruning.✅ Implement memoization with bitmask keys to avoid recomputation.
✓
Test Cases
t1_01basic
Input3
Expected[[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]

All permutations of [0,1,2] are generated using bitmask to track which elements are used.

t1_02basic
Input2
Expected[[0,1],[1,0]]

All permutations of [0,1] generated correctly with bitmask tracking visited elements.

t2_01edge
Input0
Expected[]

No elements means no permutations; output is empty list.

t2_02edge
Input1
Expected[[0]]

Single element has exactly one permutation: [0].

t2_03edge
Input2
Expected[[0,1],[1,0]]

Exact boundary test for n=2 to verify correct permutation generation.

t2_04edge
Input10
Expectednull

n=10 is the upper boundary; output size is 10! which is large but valid for performance test.

t3_01corner
Input3
Expected[[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]

Test to catch greedy approach that picks elements in ascending order only, missing permutations.

t3_02corner
Input4
Expected[[0,1,2,3],[0,1,3,2],[0,2,1,3],[0,2,3,1],[0,3,1,2],[0,3,2,1],[1,0,2,3],[1,0,3,2],[1,2,0,3],[1,2,3,0],[1,3,0,2],[1,3,2,0],[2,0,1,3],[2,0,3,1],[2,1,0,3],[2,1,3,0],[2,3,0,1],[2,3,1,0],[3,0,1,2],[3,0,2,1],[3,1,0,2],[3,1,2,0],[3,2,0,1],[3,2,1,0]]

Test to catch confusion between 0/1 knapsack and permutation generation: reusing elements multiple times.

t3_03corner
Input3
Expected[[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]

Test to catch off-by-one errors in bitmask indexing causing missing or duplicated permutations.

t4_01performance
Input{"_description":"n=10 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

n=10 requires generating 10! permutations; O(n * n!) complexity must complete within 2 seconds.

Practice

(1/5)
1. 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
2. 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
3. The following code attempts to find the single number in an array using XOR. Identify the line containing the subtle bug that causes incorrect results.
medium
A. Line 2: Initializing result to nums[0] instead of 0
B. Line 4: Returning result without sorting
C. Line 3: Looping over nums including the first element again
D. Line 1: Function definition

Solution

  1. Step 1: Analyze initialization of result

    Result initialized to nums[0], then XORed again with nums[0] in loop, cancelling it out incorrectly.
  2. Step 2: Understand correct initialization

    Result should start at 0 so XOR accumulates all elements exactly once.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Initializing to zero avoids double XOR of first element [OK]
Hint: XOR accumulator must start at zero [OK]
Common Mistakes:
  • Initializing with first element causes double XOR
  • Loop includes first element again
  • Misplaced return statement
4. Suppose the input array can contain duplicate numbers and the missing number is still from 0 to n. Which modification to the XOR approach correctly finds the missing number?
hard
A. XOR approach fails; instead use a frequency count array to find the missing number
B. Use XOR as usual; duplicates cancel out so the missing number is found correctly
C. Sort the array and scan for the first missing number ignoring duplicates
D. Use sum approach but subtract duplicates only once to avoid errors

Solution

  1. Step 1: Understand XOR behavior with duplicates

    Duplicates XORed twice cancel out, but duplicates in input break the assumption of unique elements, causing incorrect missing number.
  2. Step 2: Identify correct approach for duplicates

    Frequency counting tracks occurrences accurately, allowing detection of missing number despite duplicates.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    XOR fails with duplicates; frequency count handles duplicates correctly [OK]
Hint: XOR assumes unique elements; duplicates break cancellation [OK]
Common Mistakes:
  • Assuming XOR works with duplicates
  • Trying to fix sum approach without frequency
  • Ignoring duplicates impact on XOR
5. Suppose you want to generate a Gray code sequence where each number can be repeated multiple times (i.e., reuse allowed). Which modification to the optimal bitwise formula approach correctly handles this variant?
hard
A. Use brute force backtracking to generate sequences with repeated numbers allowed.
B. Modify the formula to i ^ (i >> 1) but allow duplicates by not enforcing uniqueness in the output list.
C. Use the same XOR formula but generate only n numbers instead of 2^n.
D. No modification needed; the original formula already allows repeated numbers.

Solution

  1. Step 1: Understand the reuse constraint

    Allowing repeated numbers breaks the Gray code uniqueness property, so the original formula which generates unique numbers won't work.
  2. Step 2: Identify suitable approach

    Brute force backtracking can explore sequences with repeated numbers and enforce the one-bit difference condition without uniqueness constraints.
  3. Step 3: Why other options fail

    Original formula always generates unique numbers; simply allowing duplicates in output breaks Gray code definition; generating fewer numbers misses full coverage.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Backtracking is flexible enough to handle reuse constraints [OK]
Hint: Original formula assumes unique numbers; reuse needs backtracking [OK]
Common Mistakes:
  • Assuming original formula can be tweaked trivially for reuse
  • Thinking fewer numbers still form valid Gray code
  • Ignoring uniqueness property of Gray code
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