Find Missing and Repeated Values (LeetCode 2965): Solution and Explanation

Easy
Array
Hash Table
Math
Matrix

An n x n grid should contain each of 1..n^2 exactly once, but one value a appears twice and one value b is missing. Mark each value in a table indexed by value; the slot marked twice gives a and the slot never marked gives b.

Intuition

The values are bounded by n^2, so each value can be its own index into an array. No hashing or sorting is needed.

While reading the grid, a value whose slot is already marked must be the repeated one, because every other value appears only once.

After all cells are read, exactly one slot in 1..n^2 is still empty. That value was never written, so it is the missing one.

Approach: Seen table

  1. Create seen, a boolean array of size n * n + 1, and set repeated = 0.
  2. For every value v in the grid, if seen[v] is already true set repeated = v, then set seen[v] = true.
  3. Walk v from 1 to n * n and stop at the first v with seen[v] false.
  4. Return [repeated, v].

Step-by-step example

grid = [[9,1,7],[8,9,2],[3,4,6]]
  1. Read 9, 1, 7, 8 and mark their slots.
  2. Read 9 again. seen[9] is already true, so repeated = 9.
  3. Read 2, 3, 4, 6 and mark them. Slots 1, 2, 3, 4, 6, 7, 8, 9 are marked.
  4. The second loop passes 1, 2, 3, 4 and stops at 5, which is empty. Return [9,5].

Code: Python, Java, C++

1class Solution:
2    def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
3        n = len(grid)
4        seen = [False] * (n * n + 1)
5        repeated = 0
6        for row in grid:
7            for v in row:
8                if seen[v]:
9                    repeated = v
10                seen[v] = True
11        for v in range(1, n * n + 1):
12            if not seen[v]:
13                return [repeated, v]
14        return [repeated, 0]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Each cell is read once, and the second loop visits at most n^2 slots.

Space

O(n^2)

The seen table has one slot per possible value.

Other approaches

Sum and sum of squares (time O(n^2), space O(1))

Let d = actualSum - expectedSum = a - b and s = actualSquares - expectedSquares = a^2 - b^2. Then a + b = s / d, which gives both values with no extra array. Use 64-bit integers, since n^2 can be 2500 and the sums of squares grow large.

XOR partition (time O(n^2), space O(1))

XOR all grid values with 1..n^2 to get a XOR b, split the numbers by any set bit, and XOR each group to separate a and b. Then check which one appears in the grid.

Common mistakes

  • Sizing the table as n * n, which leaves no slot for the value n^2.
  • Returning [missing, repeated] instead of [repeated, missing].
  • With the math approach, letting the sum of squares overflow a 32-bit integer in Java, C++ or C#.
  • Stopping the second loop at n instead of n^2.

Frequently asked questions

Why not use a hash set?

A hash set works, but the values are dense integers from 1 to n^2, so a plain array does the same job with no hashing and less memory overhead.

Can this be done in constant extra space?

Yes. Using the sum and the sum of squares, a - b and a^2 - b^2 are both known, and dividing gives a + b, which solves for a and b.

What is the time and space complexity of Find Missing and Repeated Values?

The seen-table approach runs in O(n^2) time and O(n^2) space. The math or XOR approaches keep O(n^2) time with O(1) extra space.