Bird
Raised Fist0
Interview Prepbit-manipulationmediumAmazonGoogle

Find Two Missing Numbers

Choose your preparation mode4 modes available
🎯
Find Two Missing Numbers
mediumBIT_MANIPULATIONAmazonGoogle

Imagine you have a list of numbers from 1 to n, but two numbers are missing. You want to find those missing numbers efficiently without sorting or extra space.

💡 This problem is about using bit manipulation to find two missing numbers from a sequence. Beginners often struggle because they try to use sorting or hash sets, but the XOR approach is more optimal and elegant once understood.
📋
Problem Statement

Given an array containing n-2 distinct integers from the range 1 to n, find the two missing numbers. Input: an integer n and an array of length n-2 containing distinct integers from 1 to n except two missing numbers. Output: the two missing numbers in any order.

2 ≤ n ≤ 10^5Array length = n - 2All elements are distinct and in the range [1, n]The two missing numbers are distinct
💡
Example
Input"n = 6, arr = [1, 2, 4, 6]"
Output[3, 5]

Numbers 3 and 5 are missing from the array.

Input"n = 5, arr = [2, 3, 1]"
Output[4, 5]

Numbers 4 and 5 are missing.

  • n = 2, arr = [] → missing numbers are [1, 2]
  • Missing numbers are consecutive, e.g. n=5, arr=[1,2,5] → missing [3,4]
  • Missing numbers are at the start, e.g. n=5, arr=[3,4,5] → missing [1,2]
  • Missing numbers are at the end, e.g. n=5, arr=[1,2,3] → missing [4,5]
⚠️
Common Mistakes
Using sum and sum of squares without handling integer overflow

Incorrect results or runtime errors on large inputs

✅ Use 64-bit integers or XOR approach to avoid overflow

Not finding the rightmost set bit correctly in XOR approach

Incorrect partitioning leading to wrong missing numbers

✅ Use xor_all & (-xor_all) to find rightmost set bit

Assuming missing numbers are consecutive in math approach

Wrong answers when missing numbers are not consecutive

✅ Solve quadratic equations properly without assumptions

Using brute force for large n

Time limit exceeded or very slow performance

✅ Use optimized approaches like XOR or math formulas

🧠
Brute Force (Check All Pairs)
💡 This approach exists to build intuition by trying all possible pairs to find the missing numbers. It is straightforward but inefficient, showing why we need better methods.

Intuition

Try every pair of numbers from 1 to n and check if both are missing from the array. The pair that is missing is the answer.

Algorithm

  1. Generate all pairs of numbers from 1 to n.
  2. For each pair, check if both numbers are missing from the array.
  3. Return the pair that is missing.
💡 This algorithm is easy to visualize but inefficient because it checks many pairs unnecessarily.
</>
Code
def find_two_missing_brute(n, arr):
    nums_set = set(arr)
    for i in range(1, n+1):
        for j in range(i+1, n+1):
            if i not in nums_set and j not in nums_set:
                return [i, j]

# Driver code
if __name__ == '__main__':
    n = 6
    arr = [1, 2, 4, 6]
    print(find_two_missing_brute(n, arr))
Line Notes
nums_set = set(arr)Convert array to set for O(1) membership checks
for i in range(1, n+1)Iterate over all numbers from 1 to n
for j in range(i+1, n+1)Check pairs with j > i to avoid duplicates
if i not in nums_set and j not in nums_setCheck if both numbers are missing
import java.util.*;
public class FindTwoMissing {
    public static int[] findTwoMissingBrute(int n, int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr) set.add(num);
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                if (!set.contains(i) && !set.contains(j)) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
    public static void main(String[] args) {
        int n = 6;
        int[] arr = {1, 2, 4, 6};
        int[] res = findTwoMissingBrute(n, arr);
        System.out.println(Arrays.toString(res));
    }
}
Line Notes
Set<Integer> set = new HashSet<>()Use HashSet for O(1) lookups
for (int num : arr) set.add(num)Add all array elements to the set
for (int i = 1; i <= n; i++)Iterate over all numbers from 1 to n
if (!set.contains(i) && !set.contains(j))Check if both numbers are missing
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;

vector<int> findTwoMissingBrute(int n, vector<int>& arr) {
    unordered_set<int> s(arr.begin(), arr.end());
    for (int i = 1; i <= n; i++) {
        for (int j = i + 1; j <= n; j++) {
            if (s.find(i) == s.end() && s.find(j) == s.end()) {
                return {i, j};
            }
        }
    }
    return {};
}

int main() {
    int n = 6;
    vector<int> arr = {1, 2, 4, 6};
    vector<int> res = findTwoMissingBrute(n, arr);
    cout << res[0] << " " << res[1] << endl;
    return 0;
}
Line Notes
unordered_set<int> s(arr.begin(), arr.end())Create hash set for O(1) membership
for (int i = 1; i <= n; i++)Loop over all numbers from 1 to n
for (int j = i + 1; j <= n; j++)Check pairs with j > i to avoid duplicates
if (s.find(i) == s.end() && s.find(j) == s.end())Check if both numbers are missing
function findTwoMissingBrute(n, arr) {
    const set = new Set(arr);
    for (let i = 1; i <= n; i++) {
        for (let j = i + 1; j <= n; j++) {
            if (!set.has(i) && !set.has(j)) {
                return [i, j];
            }
        }
    }
}

// Test
console.log(findTwoMissingBrute(6, [1, 2, 4, 6]));
Line Notes
const set = new Set(arr)Create set for O(1) membership checks
for (let i = 1; i <= n; i++)Iterate over all numbers from 1 to n
for (let j = i + 1; j <= n; j++)Check pairs with j > i to avoid duplicates
if (!set.has(i) && !set.has(j))Check if both numbers are missing
⏱
Complexity
TimeO(n^2)
SpaceO(n)

We check all pairs (n*(n-1)/2) and use a set for O(1) lookups, so time is quadratic. Space is linear for the set.

💡 For n=1000, this means about 500,000 checks, which is too slow for large inputs.
Interview Verdict: TLE / Use only to introduce

This approach is too slow for large inputs but helps understand the problem and motivates better solutions.

🧠
Sum and Sum of Squares Equations
💡 This approach uses math formulas to find the missing numbers by solving two equations. It is more efficient but requires careful algebra.

Intuition

The sum of numbers from 1 to n and the sum of their squares are known. Subtracting the sums of the given array gives two equations with two unknowns (the missing numbers). Solve these equations to find the missing numbers.

Algorithm

  1. Calculate total sum and total sum of squares for numbers 1 to n.
  2. Calculate sum and sum of squares of the given array.
  3. Find the difference in sums (sum_missing) and difference in sum of squares (sq_sum_missing).
  4. Use the equations: x + y = sum_missing and x^2 + y^2 = sq_sum_missing to solve for x and y.
💡 This algorithm uses algebraic manipulation to reduce the problem to solving two equations.
</>
Code
import math

def find_two_missing_sum(n, arr):
    total_sum = n * (n + 1) // 2
    total_sq_sum = n * (n + 1) * (2 * n + 1) // 6
    arr_sum = sum(arr)
    arr_sq_sum = sum(x*x for x in arr)

    sum_missing = total_sum - arr_sum  # x + y
    sq_sum_missing = total_sq_sum - arr_sq_sum  # x^2 + y^2

    # x^2 + y^2 = (x + y)^2 - 2xy => xy = ((x + y)^2 - (x^2 + y^2)) / 2
    product_missing = (sum_missing * sum_missing - sq_sum_missing) // 2

    # Solve quadratic t^2 - sum_missing*t + product_missing = 0
    discriminant = int(math.sqrt(sum_missing * sum_missing - 4 * product_missing))
    x = (sum_missing + discriminant) // 2
    y = sum_missing - x
    return [x, y]

# Driver code
if __name__ == '__main__':
    n = 6
    arr = [1, 2, 4, 6]
    print(find_two_missing_sum(n, arr))
Line Notes
total_sum = n * (n + 1) // 2Sum of first n natural numbers formula
total_sq_sum = n * (n + 1) * (2 * n + 1) // 6Sum of squares formula
arr_sum = sum(arr)Sum of elements in the given array
arr_sq_sum = sum(x*x for x in arr)Sum of squares of elements in the array
sum_missing = total_sum - arr_sumSum of missing numbers x + y
sq_sum_missing = total_sq_sum - arr_sq_sumSum of squares of missing numbers x^2 + y^2
product_missing = (sum_missing * sum_missing - sq_sum_missing) // 2Calculate product xy using algebra
discriminant = int(math.sqrt(sum_missing * sum_missing - 4 * product_missing))Calculate discriminant for quadratic formula
import java.util.*;
public class FindTwoMissing {
    public static int[] findTwoMissingSum(int n, int[] arr) {
        long totalSum = (long)n * (n + 1) / 2;
        long totalSqSum = (long)n * (n + 1) * (2 * n + 1) / 6;
        long arrSum = 0, arrSqSum = 0;
        for (int num : arr) {
            arrSum += num;
            arrSqSum += (long)num * num;
        }
        long sumMissing = totalSum - arrSum; // x + y
        long sqSumMissing = totalSqSum - arrSqSum; // x^2 + y^2
        long productMissing = (sumMissing * sumMissing - sqSumMissing) / 2; // xy
        long discriminant = (long)Math.sqrt(sumMissing * sumMissing - 4 * productMissing);
        int x = (int)((sumMissing + discriminant) / 2);
        int y = (int)(sumMissing - x);
        return new int[]{x, y};
    }
    public static void main(String[] args) {
        int n = 6;
        int[] arr = {1, 2, 4, 6};
        System.out.println(Arrays.toString(findTwoMissingSum(n, arr)));
    }
}
Line Notes
long totalSum = (long)n * (n + 1) / 2Calculate sum of 1 to n safely with long
long totalSqSum = (long)n * (n + 1) * (2 * n + 1) / 6Sum of squares formula
long arrSum = 0, arrSqSum = 0Initialize sums for array elements
for (int num : arr) { arrSum += num; arrSqSum += (long)num * num; }Calculate sum and sum of squares of array
long sumMissing = totalSum - arrSumSum of missing numbers x + y
long sqSumMissing = totalSqSum - arrSqSumSum of squares of missing numbers x^2 + y^2
long productMissing = (sumMissing * sumMissing - sqSumMissing) / 2Calculate product xy
long discriminant = (long)Math.sqrt(...)Calculate discriminant for quadratic formula
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

vector<int> findTwoMissingSum(int n, vector<int>& arr) {
    long long totalSum = (long long)n * (n + 1) / 2;
    long long totalSqSum = (long long)n * (n + 1) * (2 * n + 1) / 6;
    long long arrSum = 0, arrSqSum = 0;
    for (int num : arr) {
        arrSum += num;
        arrSqSum += (long long)num * num;
    }
    long long sumMissing = totalSum - arrSum; // x + y
    long long sqSumMissing = totalSqSum - arrSqSum; // x^2 + y^2
    long long productMissing = (sumMissing * sumMissing - sqSumMissing) / 2; // xy
    long long discriminant = (long long)sqrt(sumMissing * sumMissing - 4 * productMissing);
    int x = (sumMissing + discriminant) / 2;
    int y = sumMissing - x;
    return {x, y};
}

int main() {
    int n = 6;
    vector<int> arr = {1, 2, 4, 6};
    vector<int> res = findTwoMissingSum(n, arr);
    cout << res[0] << " " << res[1] << endl;
    return 0;
}
Line Notes
long long totalSum = (long long)n * (n + 1) / 2Use long long to avoid overflow
long long totalSqSum = (long long)n * (n + 1) * (2 * n + 1) / 6Sum of squares formula
long long arrSum = 0, arrSqSum = 0Initialize sums for array elements
for (int num : arr) { arrSum += num; arrSqSum += (long long)num * num; }Calculate sum and sum of squares of array
long long sumMissing = totalSum - arrSumSum of missing numbers x + y
long long sqSumMissing = totalSqSum - arrSqSumSum of squares of missing numbers x^2 + y^2
long long productMissing = (sumMissing * sumMissing - sqSumMissing) / 2Calculate product xy
long long discriminant = (long long)sqrt(...)Calculate discriminant for quadratic
function findTwoMissingSum(n, arr) {
    let totalSum = n * (n + 1) / 2;
    let totalSqSum = n * (n + 1) * (2 * n + 1) / 6;
    let arrSum = 0, arrSqSum = 0;
    for (let num of arr) {
        arrSum += num;
        arrSqSum += num * num;
    }
    let sumMissing = totalSum - arrSum; // x + y
    let sqSumMissing = totalSqSum - arrSqSum; // x^2 + y^2
    let productMissing = (sumMissing * sumMissing - sqSumMissing) / 2; // xy
    let discriminant = Math.sqrt(sumMissing * sumMissing - 4 * productMissing);
    let x = (sumMissing + discriminant) / 2;
    let y = sumMissing - x;
    return [x, y];
}

// Test
console.log(findTwoMissingSum(6, [1, 2, 4, 6]));
Line Notes
let totalSum = n * (n + 1) / 2Sum of first n natural numbers
let totalSqSum = n * (n + 1) * (2 * n + 1) / 6Sum of squares formula
let arrSum = 0, arrSqSum = 0Initialize sums for array elements
for (let num of arr) { arrSum += num; arrSqSum += num * num; }Calculate sum and sum of squares of array
let sumMissing = totalSum - arrSumSum of missing numbers x + y
let sqSumMissing = totalSqSum - arrSqSumSum of squares of missing numbers x^2 + y^2
let productMissing = (sumMissing * sumMissing - sqSumMissing) / 2Calculate product xy
let discriminant = Math.sqrt(...)Calculate discriminant for quadratic formula
⏱
Complexity
TimeO(n)
SpaceO(1)

We do a single pass to compute sums and squares, so linear time. Space is constant as only variables are used.

💡 For n=100000, this means about 100000 operations, which is efficient for interviews.
Interview Verdict: Accepted / Efficient math approach

This approach is efficient and acceptable but requires careful algebra and handling of large numbers.

🧠
Optimal XOR Partitioning
💡 This approach uses XOR properties to find the two missing numbers without arithmetic overflow or complex algebra. It is elegant and efficient.

Intuition

XOR all numbers from 1 to n and XOR all elements in the array. The result is XOR of the two missing numbers. Use a set bit to partition numbers into two groups and XOR separately to find the missing numbers.

Algorithm

  1. XOR all numbers from 1 to n and XOR all elements in the array to get xor_missing = x ^ y.
  2. Find a set bit in xor_missing to partition numbers into two groups.
  3. XOR numbers in each group separately for both the full range and the array.
  4. The two results are the missing numbers.
💡 This algorithm cleverly uses XOR to separate the two missing numbers without extra space or arithmetic.
</>
Code
def find_two_missing_xor(n, arr):
    xor_all = 0
    for i in range(1, n+1):
        xor_all ^= i
    for num in arr:
        xor_all ^= num

    # Find rightmost set bit
    set_bit = xor_all & (-xor_all)

    x = 0
    y = 0
    for i in range(1, n+1):
        if i & set_bit:
            x ^= i
        else:
            y ^= i
    for num in arr:
        if num & set_bit:
            x ^= num
        else:
            y ^= num
    return [x, y]

# Driver code
if __name__ == '__main__':
    n = 6
    arr = [1, 2, 4, 6]
    print(find_two_missing_xor(n, arr))
Line Notes
xor_all = 0Initialize XOR accumulator
xor_all ^= iXOR all numbers from 1 to n
for num in arr: xor_all ^= numXOR all elements in the array to cancel out present numbers
set_bit = xor_all & (-xor_all)Find rightmost set bit to partition numbers
x = 0; y = 0Initialize variables to hold the two missing numbers
for i in range(1, n+1): if i & set_bit: x ^= i else: y ^= iPartition numbers based on set bit and XOR separately
for num in arr: if num & set_bit: x ^= num else: y ^= numPartition array elements similarly to cancel out present numbers
return [x, y]Return the two missing numbers
import java.util.*;
public class FindTwoMissing {
    public static int[] findTwoMissingXOR(int n, int[] arr) {
        int xorAll = 0;
        for (int i = 1; i <= n; i++) xorAll ^= i;
        for (int num : arr) xorAll ^= num;
        int setBit = xorAll & (-xorAll);
        int x = 0, y = 0;
        for (int i = 1; i <= n; i++) {
            if ((i & setBit) != 0) x ^= i;
            else y ^= i;
        }
        for (int num : arr) {
            if ((num & setBit) != 0) x ^= num;
            else y ^= num;
        }
        return new int[]{x, y};
    }
    public static void main(String[] args) {
        int n = 6;
        int[] arr = {1, 2, 4, 6};
        System.out.println(Arrays.toString(findTwoMissingXOR(n, arr)));
    }
}
Line Notes
int xorAll = 0Initialize XOR accumulator
for (int i = 1; i <= n; i++) xorAll ^= iXOR all numbers from 1 to n
for (int num : arr) xorAll ^= numXOR all elements in the array to cancel out present numbers
int setBit = xorAll & (-xorAll)Find rightmost set bit to partition
int x = 0, y = 0Initialize variables to hold the two missing numbers
for (int i = 1; i <= n; i++) { if ((i & setBit) != 0) x ^= i; else y ^= i; }Partition numbers based on set bit and XOR separately
for (int num : arr) { if ((num & setBit) != 0) x ^= num; else y ^= num; }Partition array elements similarly to cancel out present numbers
return new int[]{x, y}Return the two missing numbers
#include <iostream>
#include <vector>
using namespace std;

vector<int> findTwoMissingXOR(int n, vector<int>& arr) {
    int xorAll = 0;
    for (int i = 1; i <= n; i++) xorAll ^= i;
    for (int num : arr) xorAll ^= num;
    int setBit = xorAll & (-xorAll);
    int x = 0, y = 0;
    for (int i = 1; i <= n; i++) {
        if (i & setBit) x ^= i;
        else y ^= i;
    }
    for (int num : arr) {
        if (num & setBit) x ^= num;
        else y ^= num;
    }
    return {x, y};
}

int main() {
    int n = 6;
    vector<int> arr = {1, 2, 4, 6};
    vector<int> res = findTwoMissingXOR(n, arr);
    cout << res[0] << " " << res[1] << endl;
    return 0;
}
Line Notes
int xorAll = 0Initialize XOR accumulator
for (int i = 1; i <= n; i++) xorAll ^= iXOR all numbers from 1 to n
for (int num : arr) xorAll ^= numXOR all elements in the array to cancel out present numbers
int setBit = xorAll & (-xorAll)Find rightmost set bit to partition
int x = 0, y = 0Initialize variables to hold the two missing numbers
for (int i = 1; i <= n; i++) { if (i & setBit) x ^= i; else y ^= i; }Partition numbers based on set bit and XOR separately
for (int num : arr) { if (num & setBit) x ^= num; else y ^= num; }Partition array elements similarly to cancel out present numbers
return {x, y}Return the two missing numbers
function findTwoMissingXOR(n, arr) {
    let xorAll = 0;
    for (let i = 1; i <= n; i++) xorAll ^= i;
    for (let num of arr) xorAll ^= num;
    let setBit = xorAll & (-xorAll);
    let x = 0, y = 0;
    for (let i = 1; i <= n; i++) {
        if ((i & setBit) !== 0) x ^= i;
        else y ^= i;
    }
    for (let num of arr) {
        if ((num & setBit) !== 0) x ^= num;
        else y ^= num;
    }
    return [x, y];
}

// Test
console.log(findTwoMissingXOR(6, [1, 2, 4, 6]));
Line Notes
let xorAll = 0Initialize XOR accumulator
for (let i = 1; i <= n; i++) xorAll ^= iXOR all numbers from 1 to n
for (let num of arr) xorAll ^= numXOR all elements in the array to cancel out present numbers
let setBit = xorAll & (-xorAll)Find rightmost set bit to partition
let x = 0, y = 0Initialize variables to hold the two missing numbers
for (let i = 1; i <= n; i++) { if ((i & setBit) !== 0) x ^= i; else y ^= i; }Partition numbers based on set bit and XOR separately
for (let num of arr) { if ((num & setBit) !== 0) x ^= num; else y ^= num; }Partition array elements similarly to cancel out present numbers
return [x, y]Return the two missing numbers
⏱
Complexity
TimeO(n)
SpaceO(1)

We do two passes over the range and array, each O(n). Space is constant for variables.

💡 For n=100000, this means about 200000 operations, very efficient for interviews.
Interview Verdict: Accepted / Optimal approach

This is the best approach to implement in interviews due to its efficiency and elegance.

📊
All Approaches - One-Glance Tradeoffs
💡 In interviews, implement the XOR approach for best balance of speed and simplicity.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(n^2)O(n)NoYesMention only - never code
2. Sum and Sum of SquaresO(n)O(1)NoYesGood to mention, but careful with overflow
3. XOR PartitioningO(n)O(1)NoYesCode this approach in 95% of interviews
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice all approaches, and know when to use each. Read it before every mock interview to build confidence.

How to Present

Step 1: Clarify the problem and constraints with the interviewer.Step 2: Explain the brute force approach and why it is inefficient.Step 3: Discuss the math-based sum and sum of squares approach.Step 4: Present the optimal XOR partitioning approach and implement it.Step 5: Test your code with sample and edge cases.

Time Allocation

Clarify: 2min → Approach: 3min → Code: 10min → Test: 5min. Total ~20min

What the Interviewer Tests

The interviewer tests your problem understanding, ability to optimize, knowledge of bit manipulation, and coding correctness.

Common Follow-ups

  • What if there are more than two missing numbers? → Use generalized XOR or other methods.
  • Can you find missing numbers without extra space and without overflow? → XOR approach is best.
💡 These follow-ups test your ability to generalize and handle edge constraints.
🔍
Pattern Recognition

When to Use

1) Asked to find missing numbers from a range; 2) Exactly two missing numbers; 3) Constraints require O(n) time and O(1) space; 4) Bit manipulation hints or XOR mentioned.

Signature Phrases

two missing numbersXOR of missing numberspartition by set bit

NOT This Pattern When

Problems with multiple missing numbers or duplicates require different approaches.

Similar Problems

Find Missing Number - simpler case with one missing numberSingle Number - find unique element using XORMissing Two Numbers with Sum - uses sum equations

Practice

(1/5)
1. Consider the following Python code that uses Brian Kernighan's bit counting trick to count set bits from 0 to n. What is the output when n = 3?
def countBits(n):
    res = []
    for i in range(n + 1):
        count = 0
        x = i
        while x:
            x &= x - 1
            count += 1
        res.append(count)
    return res

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

Solution

  1. Step 1: Trace countBits for i=0 to 3

    i=0: binary 0, count=0; i=1: binary 1, count=1; i=2: binary 10, count=1; i=3: binary 11, count=2.
  2. Step 2: Confirm final result list

    Result list is [0, 1, 1, 2].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Matches manual bit count for each number [OK]
Hint: Count bits by clearing least significant set bit [OK]
Common Mistakes:
  • Off-by-one in range
  • Miscounting bits for 2 or 3
  • Confusing count initialization
2. 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
3. Given the following Python code implementing sum of two integers without using + operator, what is the output when calling getSum(1, 2)?
easy
A. 2
B. 3
C. 1
D. 0

Solution

  1. Step 1: First call getSum(1, 2)

    sum_ = (1 ^ 2) & MASK = 3, carry = ((1 & 2) << 1) & MASK = 0
  2. Step 2: Since carry is 0, return sum_ = 3

    Base case reached, final sum is 3.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    1 + 2 = 3 matches output [OK]
Hint: XOR sum with carry zero returns final sum [OK]
Common Mistakes:
  • Confusing carry calculation
  • Off-by-one in recursion
  • Returning carry instead of sum
4. What is the time complexity of the XOR approach to find the missing number in an array of length n containing numbers from 0 to n with one missing?
medium
A. O(n log n) due to sorting inside XOR operations
B. O(1) since XOR is a constant time operation
C. O(n^2) because XOR operations are nested
D. O(n) because it iterates over the range and array once each

Solution

  1. Step 1: Identify loops in the XOR approach

    There are two separate loops: one over range 0 to n, and one over the array of length n.
  2. Step 2: Calculate total time complexity

    Each loop runs O(n) times, so total time is O(n) + O(n) = O(n).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    No nested loops or sorting, linear time confirmed [OK]
Hint: Two separate linear loops sum to O(n) time [OK]
Common Mistakes:
  • Confusing XOR operations as nested loops
  • Assuming sorting inside XOR
  • Ignoring linear iteration over range
5. Suppose the input array can contain multiple elements that appear only once, while all others appear twice. Which modification to the XOR approach correctly finds all unique elements?
hard
A. Use XOR as before; it will return the XOR of all unique elements combined
B. Sort the array and scan to find all unique elements by comparing neighbors
C. Use a hash map to count occurrences and collect elements with count 1
D. Apply XOR pairwise on elements and recursively split the array

Solution

  1. Step 1: Understand XOR limitation

    XOR of multiple unique elements combined is a single number, not individual uniques.
  2. Step 2: Identify approach to find all unique elements

    Counting occurrences with a hash map correctly identifies all unique elements.
  3. Step 3: Compare alternatives

    Sorting works but is less efficient; recursive XOR splitting is complex and error-prone.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Hash map approach correctly handles multiple unique elements [OK]
Hint: XOR only isolates one unique element, not multiple [OK]
Common Mistakes:
  • Assuming XOR returns all unique elements
  • Ignoring multiple unique elements case
  • Overcomplicating with recursion
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