Missing And Repeating

easy

An array arr of size n was supposed to hold each number from 1 to n exactly once — but something went wrong. One value from the range appears twice, and one value from the range is missing entirely.

Find both. Return an array of two integers, repeating first, missing second: [repeating, missing].

Hints

If the array were perfect, every number from 1 to n would appear exactly once. You are hunting for exactly two deviations from that perfect picture.
Counting how many times each value appears answers both questions at once — but can you record those counts without allocating a second array?
Every value v names an address: index v - 1. All values are positive, so the sign of arr[v - 1] is free storage — negate it to mark v as seen. A slot that is already negative exposes the repeater; the slot left positive exposes the gap.

Common doubts

Yes — return the repeating number first, then the missing number: [repeating, missing]. Swapping them fails the tests even though both values are correct.
No. The duplicate occupies the slot the missing value vacated — if they were the same value, the array would be a perfect arrangement of 1..n with nothing missing at all.
The sign-marking trick does mutate arr (it flips entries negative). If mutation is forbidden, use the frequency-array approach, a math/XOR variant, or restore the signs with one extra abs pass at the end.

Interview follow-ups

Yes — with math: sum(arr) - n(n+1)/2 = R - M, and the sum of squares gives R² - M² = (R - M)(R + M); two equations, two unknowns. Use 64-bit arithmetic (the square sum reaches ~3.3 × 10^17). Alternatively, XOR all elements with 1..n to get R ^ M, then split by the lowest set bit into two groups to separate R from M.
Sign marking still works: collect every value whose home slot is already negative (the repeaters) and every index left positive (the missing values). The math approach breaks down, but marking generalizes cleanly.

Fun facts

  • The sum-and-sum-of-squares variant is a miniature error-correcting code: just two checksums are enough to pinpoint and repair a single corrupted value in the data.
  • The value-as-index sign trick reappears in Find All Duplicates in an Array and First Missing Positive — it turns any array of values in 1..n into its own hash map.

Asked at

AmazonMicrosoftAdobeOracle
Frequently Sometimes Occasionally
Example 1
Input: arr = [2, 2]
Output: [2, 1]
2 appears twice, and 1 never appears.
Example 2
Input: arr = [1, 3, 3]
Output: [3, 2]
3 appears twice, and 2 never appears.
Example 3
Input: arr = [4, 3, 6, 2, 1, 1]
Output: [1, 5]
1 appears twice, and 5 never appears.
Constraints

- 2 <= n <= 10^6 - 1 <= arr[i] <= n - Exactly one value repeats and exactly one value is missing

Solve this problem →