Find Missing and Repeated Values - Problem

You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n²]. Each integer appears exactly once except:

  • a which appears twice
  • b which is missing

Your task is to find the repeating and missing numbers a and b.

Return a 0-indexed integer array ans of size 2 where:

  • ans[0] equals to a (the repeated number)
  • ans[1] equals to b (the missing number)

Input & Output

Example 1 — Basic Case
$ Input: grid = [[1,3],[2,2]]
Output: [2,4]
💡 Note: In a 2×2 grid, numbers should be [1,2,3,4]. Number 2 appears twice (repeated), number 4 is missing.
Example 2 — Larger Grid
$ Input: grid = [[9,1,7],[8,9,2],[3,4,6]]
Output: [9,5]
💡 Note: In a 3×3 grid, numbers should be [1,2,3,4,5,6,7,8,9]. Number 9 appears twice, number 5 is missing.
Example 3 — Edge Positions
$ Input: grid = [[1,2],[4,4]]
Output: [4,3]
💡 Note: Number 4 appears twice at positions (1,0) and (1,1). Number 3 is missing from the sequence [1,2,3,4].

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ grid[i][j] ≤ n²
  • Exactly one number appears twice
  • Exactly one number is missing

Visualization

Tap to expand
Find Missing and Repeated Values in n×n GridInput Grid:1322Expected [1,2,3,4]:✓ 1 appears once✗ 2 appears twice✓ 3 appears once✗ 4 missing (0 times)Solution:Repeated: 2Missing: 4Return [2, 4]Process: Count frequency of each number in gridFind number with count=2 (repeated) and count=0 (missing)Output: [2, 4]
Understanding the Visualization
1
Input Analysis
2D grid with one repeated and one missing number from range [1, n²]
2
Count & Compare
Compare actual numbers against expected sequence [1, 2, 3, 4]
3
Result
Return [repeated, missing] as the answer
Key Takeaway
🎯 Key Insight: Use frequency counting or mathematical formulas to efficiently identify the duplicate and missing values
Asked in
Amazon 25 Microsoft 20 Google 15 Apple 12
33.2K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen