DSA Tracker

Medium

Repeat and Missing Number Array

A medium Arrays problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
2
Core for
25 roles
Platform
GeeksforGeeks

The problem

Given an array of size n containing numbers from 1 to n, one number appears twice and another is missing. Find both.

Example 1

Input
[1,3,3,4]
Output
missing=2, repeating=3

Example 2

Input
[4,3,6,2,1,1]
Output
missing=5, repeating=1

Example 3

Input
[1,2,2,4]
Output
missing=3, repeating=2

Constraints

  • 2 <= n <= 10^5
  • 1 <= arr[i] <= n

How to think about it

Updated 2026-09-09

Every expected number from 1 to n can pair with its appearance in the input. If you take the difference between expected and actual sums, and expected and actual sums of squares, the duplicate and missing values become two unknowns in a system of two linear equations that solve cleanly.

Approaches, worst first

  1. Frequency count array

    time O(n) · space O(n)

    Count occurrences of every value from 1 to n in a separate tally array. A single subsequent scan identifies which index has a count of 2 and which has 0, but consumes O(n) auxiliary space.

  2. Sum and sum of squares

    time O(n) · space O(1)

    Let x be repeating and y be missing. Calculate sum differences to get (x - y) and sum of squares differences to get (x^2 - y^2). Dividing the latter by the former yields (x + y), allowing direct computation of both x and y in O(1) extra space.

  3. XOR partitioningWrite this one

    time O(n) · space O(1)

    XOR all array values together with numbers 1 through n to produce (x ^ y). Find the lowest set bit in the result to partition numbers into two sets, separating x and y into distinct XOR buckets without any risk of numeric arithmetic overflow.

Where people lose marks · 3
  • Sum of squares of numbers up to 10^5 reaches roughly 3.33 * 10^14, which immediately overflows standard 32-bit signed integers if not accumulated using 64-bit integers.
  • Dividing (x^2 - y^2) by (x - y) without checking for order or confusing which variable represents the duplicate versus the missing element flips the two outputs.
  • When using sign negation as an in-place visited flag, failing to take absolute values before indexing causes negative array index faults.

Full solution

XOR partitioning: XOR the array with 1..n to get repeating ^ missing, then split every number by the lowest set bit so the two unknowns land in separate buckets. Same O(n)/O(1) as the sum-of-squares trick but with no overflow to worry about, which is why it is the one to write.

Python
def repeat_and_missing(arr: list[int]) -> tuple[int, int]:
    """Returns (repeating, missing) using XOR partitioning, O(1) extra space."""
    n = len(arr)
    xor_all = 0
    for i, v in enumerate(arr):
        xor_all ^= v ^ (i + 1)  # every value paired with its expected 1..n counterpart
    # xor_all == repeating ^ missing; they differ at the lowest set bit
    low_bit = xor_all & -xor_all
    a = 0  # XOR of everything with low_bit set
    b = 0  # XOR of everything with low_bit clear
    for i, v in enumerate(arr):
        a, b = (a ^ v, b) if v & low_bit else (a, b ^ v)
        k = i + 1
        a, b = (a ^ k, b) if k & low_bit else (a, b ^ k)
    # {a, b} == {repeating, missing}; a scan of arr decides which is which
    repeating = a if a in arr else b
    return repeating, xor_all ^ repeating
JavaScript
function repeatAndMissing(arr) {
  const n = arr.length;
  let xorAll = 0;
  for (let i = 0; i < n; i++) xorAll ^= arr[i] ^ (i + 1); // pair each value with expected 1..n
  // xorAll === repeating ^ missing; they differ at the lowest set bit
  const lowBit = xorAll & -xorAll;
  let a = 0; // XOR of everything with lowBit set
  let b = 0; // XOR of everything with lowBit clear
  for (let i = 0; i < n; i++) {
    if (arr[i] & lowBit) a ^= arr[i]; else b ^= arr[i];
    const k = i + 1;
    if (k & lowBit) a ^= k; else b ^= k;
  }
  // {a, b} === {repeating, missing}; a scan of arr decides which is which
  const repeating = arr.includes(a) ? a : b;
  return [repeating, xorAll ^ repeating];
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .