Bird
Raised Fist0
Interview Prepbit-manipulationeasyAmazonMicrosoftGoogleBloomberg

Find the Missing Number

Choose your preparation mode4 modes available
▶
Steps
setup

Initial Array State

We start with the unsorted input array [3, 0, 1]. The algorithm will first sort this array to prepare for index comparison.

💡 Sorting ensures the numbers are in order so that each index should match the number if none are missing.
Line:nums.sort()
💡 Sorting is a prerequisite to detect the missing number by comparing indices to values.
📊
Find the Missing Number - Watch the Algorithm Execute, Step by Step
Watching each comparison and decision helps you understand how sorting and linear scan reveal the missing number efficiently.
Step 1/10
·Active fill★Answer cell
Sorting array
A
0
1
1
=3
B
Sorted array
A
0
0
0
0
0
0
0
0
=0
B
Compare index 0 and num 0
A
0
0
0
0
0
0
0
0
=0
B
💡 Index 0 matches element 0
Compare index 1 and num 1
A
0
1
=1
B
💡 Index 1 matches element 1
Compare index 2 and num 3
A
0
1
1
1
=3
B
💡 Mismatch found: index 2 != element 3
Return missing number
A
0
1
0
0
=2
B
────────
=
0
1
0
0
=2
💡 Missing number 2 identified and returned
Return length if no mismatch
A
0
1
1
1
=3
B
────────
=
0
1
1
1
=3
💡 Missing number is n when all match
Final missing number output
A
0
1
0
0
=2
B
────────
=
0
1
0
0
=2
💡 Output confirmed as 2
Highlight bits of num 1
A
0
1
=1
B
💡 Binary form of 1
Algorithm complete
A
0
1
0
0
=2
B
────────
=
0
1
0
0
=2
💡 Final missing number output

Key Takeaways

✓ Sorting the array aligns numbers with their indices, enabling direct comparison to find the missing number.

This insight is hard to see from code alone because the importance of sorting for index alignment is implicit.

✓ The first index where the element does not match the index is the missing number.

Visualizing each comparison step clarifies why the mismatch reveals the missing number immediately.

✓ If all elements match their indices, the missing number is the length of the array.

This fallback case is often overlooked but is critical for correctness; the visualization highlights this clearly.

Practice

(1/5)
1. You need to generate all permutations of n distinct elements efficiently. Which approach best balances time and space by using a compact representation of visited elements and avoids redundant recomputation?
easy
A. Backtracking with a boolean visited array and recursion without memoization
B. Greedy algorithm that picks the next smallest unused element at each step
C. Bitmask DP with iterative tabulation that uses bitmasks to track visited elements and builds permutations bottom-up
D. Dynamic programming on subsets without bitmasking, using nested loops over all permutations

Solution

  1. Step 1: Understand the problem constraints

    Generating all permutations requires enumerating all orderings of n elements, which is factorial in size. Efficient tracking of visited elements is crucial.
  2. Step 2: Identify the approach that uses bitmasking

    Bitmask DP uses an integer to represent visited elements compactly, enabling memoization and iterative building of permutations without redundant recomputation.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Bitmask DP with iterative tabulation is the known optimal approach for this problem [OK]
Hint: Bitmask DP uses bits to track visited elements efficiently [OK]
Common Mistakes:
  • Assuming greedy can generate all permutations correctly
  • Using DP without bitmasking leads to inefficient state tracking
2. Consider the following code that generates all permutations of 3 elements using bitmask DP with iterative tabulation. What is the content of dp[7] after the loops finish?

def generate_permutations_iterative(n):
    dp = [[] for _ in range(1 << n)]
    dp[0] = [[]]
    for mask in range(1 << n):
        for i in range(n):
            if not (mask & (1 << i)):
                for perm in dp[mask]:
                    dp[mask | (1 << i)].append(perm + [i])
    return dp[(1 << n) - 1]

perms = generate_permutations_iterative(3)
print(perms)
easy
A. [[0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0]]
B. [[0,1,2], [1,0,2], [2,0,1]]
C. [[0,1,2], [0,2,1], [1,0,2], [2,1,0]]
D. [[0,1,2], [1,2,0], [2,1,0], [2,0,1]]

Solution

  1. Step 1: Trace dp[0] initialization

    dp[0] starts with [[]], representing empty permutation.
  2. Step 2: Iteratively build dp for all masks

    For each mask, append unused elements to existing permutations, eventually filling dp[7] with all permutations of [0,1,2].
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    dp[7] contains all 3! = 6 permutations of [0,1,2] [OK]
Hint: dp[(1<
Common Mistakes:
  • Confusing mask indexing leading to missing permutations
  • Off-by-one errors in bitmask checks
3. 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
4. Identify the bug in the following code snippet that attempts to check if a number is a power of four:
medium
A. Using 'log_val == int(log_val)' causes false negatives due to floating point precision
B. The condition 'if n <= 0' should be 'if n < 0' to allow zero
C. The division by 2 should be multiplication by 0.5 for better precision
D. The function should use a loop instead of logarithm for accuracy

Solution

  1. Step 1: Understand floating point precision issue

    Floating point calculations can introduce tiny errors, so direct equality check can fail for valid powers of four.
  2. Step 2: Identify the bug

    The line 'return log_val == int(log_val)' is the bug because it does not allow for a tolerance margin.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Adding a tolerance check like abs(log_val - int(log_val)) < epsilon fixes the bug [OK]
Hint: Floating point equality without tolerance causes subtle bugs
Common Mistakes:
  • Ignoring floating point errors
  • Misusing inequality conditions for input validation
5. 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
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