Find Missing and Repeated Values

You are given a 0-indexed `n x n` integer matrix `grid` with values in the range `[1, n^2]`. Every integer appears exactly once except `a`, which appears twice, and `b`, which is missing. Return a 0-indexed integer array `ans` of size 2 where `ans[0] = a` and `ans[1] = b`.

30:00

Find Missing and Repeated Values
easy
Free written solution
Topics
Companies

You are given a 0-indexed n x n integer matrix grid with values in the range [1, n^2]. Every integer appears exactly once except a, which appears twice, and b, which is missing.

Return a 0-indexed integer array ans of size 2 where ans[0] = a and ans[1] = b.

Example 1:
Input: {"grid":[[1,3],[2,2]]}
Output: [2,4]
Constraints:
  • 2≤n==grid.length==grid[i].length≤502 \leq n == \text{grid.length} == \text{grid}[i].\text{length} \leq 50

  • 1≤grid[i][j]≤n⋅n1 \leq \text{grid}[i][j] \leq n \cdot n

  • Exactly one value in [1,n2][1, n^2] appears twice and exactly one is missing; every other value appears once.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[1,3],[2,2]]}

The 4 cells should hold each of 1..4 exactly once. Keep a seen table indexed by value: a value already marked is the repeat, and the one slot never marked is the missing value.

repeated = ?
missing = ?

grid (0/4 read)

1
3
2
2

seen table, values 1..4

1
2
3
4

Each value read lights its own slot.

Green slots were seen once, a red slot was seen twice, and the dashed purple slot is the value nobody wrote.

Variables
VariableValue
n2
repeated0
DepthFunction Call
Stack empty
0/8