← Back to Algorithms, page 5

algorithms-0097 · Easy fresher

Use bits to find the missing number in a list containing all but one of the values 0 to n, and to enumerate every subset of a small list with bitmasks.

XOR all indices 0..n with all values: every present number appears twice and cancels, leaving the missing one, in O(n) time and O(1) space with no overflow risk. For subsets, each integer mask from 0 to 2^n - 1 picks the items whose bit is set, giving all 2^n subsets in O(n * 2^n).

Full answer

Problem

Part 1: nums contains n distinct numbers from 0..n with exactly one missing; return the missing number.

Part 2: return all subsets of a list of n distinct items.

Example: [3, 0, 1] is missing 2; [0, 1] is missing 2; [1] is missing 0. Subsets of [1, 2, 3] in mask order are [], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3].

Constraints: up to 10^4 numbers for part 1; n <= 16 for part 2 (65,536 subsets).

Brute force

Part 1: sort and scan for the gap (O(n log n)), or build a set and check each value (O(n) time, O(n) space). The sum formula n(n+1)/2 - sum(nums) is O(1) space but can overflow in fixed-width languages.

Part 2: recursive include or exclude for each item (also O(n * 2^n), but more code).

Optimal approach

Part 1: start with x = n; for each index i and value v, x ^= i ^ v. Return x.

Part 2: for mask in range(1 << n), include items[i] when (mask >> i) & 1 is 1.

Why it works

Part 1: the XOR covers every number in 0..n once from the indices (plus n), and every present number once more from the values. Present numbers cancel in pairs, leaving the missing one.

Part 2: the integers 0..2^n - 1 are in one-to-one correspondence with subsets of n items, bit i saying whether item i is chosen. Enumerating every integer enumerates every subset exactly once.

Complexity

Part 1: O(n) time, O(1) space. Part 2: O(n * 2^n) time and output size.

Code

python
import random
from itertools import combinations


def missing_number(nums):
    """nums holds n distinct values from 0..n with one missing. XOR all indices and values."""
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x


def subsets_bitmask(items):
    """All 2^n subsets: bit i of mask says whether items[i] is in. O(n * 2^n)."""
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]


def brute_missing(nums):
    return (set(range(len(nums) + 1)) - set(nums)).pop()


if __name__ == "__main__":
    assert missing_number([3, 0, 1]) == 2 and missing_number([0, 1]) == 2 and missing_number([1]) == 0
    assert subsets_bitmask([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    assert subsets_bitmask([]) == [[]]
    rng = random.Random(97)
    for _ in range(500):
        n = rng.randint(1, 50)
        vals = list(range(n + 1))
        vals.remove(rng.randint(0, n))
        rng.shuffle(vals)
        assert missing_number(vals) == brute_missing(vals)
    for n in range(0, 8):
        items = list(range(n))
        got = sorted(map(tuple, subsets_bitmask(items)))
        want = sorted(c for k in range(n + 1) for c in combinations(items, k))
        assert got == want
    print("all tests passed")

Save as b97_missing_number_subsets.py and run python3 b97_missing_number_subsets.py. It prints all tests passed (Python 3.13.5).

Edge cases

Missing 0 or missing n. Single element. Part 2 with an empty list (one subset, the empty one). Large n in part 2: 2^n explodes, so masks are only practical up to about 20 items.

Pattern

XOR cancellation and masks as sets. Related: find the duplicate and the missing number together, single number variants, bitmask DP (TSP, assignment), and iterating submasks of a mask with sub = (sub - 1) & mask.

python
import random
from itertools import combinations


def missing_number(nums):
    """nums holds n distinct values from 0..n with one missing. XOR all indices and values."""
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x


def subsets_bitmask(items):
    """All 2^n subsets: bit i of mask says whether items[i] is in. O(n * 2^n)."""
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]


def brute_missing(nums):
    return (set(range(len(nums) + 1)) - set(nums)).pop()


if __name__ == "__main__":
    assert missing_number([3, 0, 1]) == 2 and missing_number([0, 1]) == 2 and missing_number([1]) == 0
    assert subsets_bitmask([1, 2, 3]) == [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    assert subsets_bitmask([]) == [[]]
    rng = random.Random(97)
    for _ in range(500):
        n = rng.randint(1, 50)
        vals = list(range(n + 1))
        vals.remove(rng.randint(0, n))
        rng.shuffle(vals)
        assert missing_number(vals) == brute_missing(vals)
    for n in range(0, 8):
        items = list(range(n))
        got = sorted(map(tuple, subsets_bitmask(items)))
        want = sorted(c for k in range(n + 1) for c in combinations(items, k))
        assert got == want
    print("all tests passed")

XOR missing number checked against a set difference on shuffled inputs, and mask-based subsets checked against itertools.combinations.

Complexity

Time: O(n) missing number; O(n * 2^n) subsets. Space: O(1) missing number; O(n * 2^n) output. The sum formula is also O(1) space in Python, where integers do not overflow.

By level

Fresher: Solves the missing number with XOR and explains cancellation on a small list. Lists subsets by counting masks.

Mid: Compares XOR, sum and set methods on space and overflow. Iterates submasks and explains the 2^n limit.

Senior: Applies masks to DP over subsets and discusses limits, meet-in-the-middle for n around 40, and bitset representations for large sets. Estimates 2^n work before committing to a mask-based method.

Key points

  • XOR indices and values to cancel present numbers
  • Start with x = n
  • Mask bit i selects item i
  • 2^n masks enumerate all subsets
  • Practical for n up to about 20

Common mistakes

  • Forgetting to include n in the XOR
  • Overflow with the sum formula in fixed-width languages
  • Using masks for n = 40
  • Off-by-one in the mask range

Follow-ups

  • How would you find both a duplicate and a missing number?
  • How do you iterate all submasks of a mask?
  • How do subsets become a DP over masks?

Tips

  • Explain cancellation with a 4-element example
  • Mention the overflow risk of the sum formula
  • Draw mask bits next to items

Evaluation rubric

  • Correct XOR method
  • Correct subset enumeration
  • Correct complexity
  • Edge cases