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 INPUT 2D Grid (n=2) 1 3 2 2 repeated! Expected: [1, n²] = [1, 4] Values in grid: 1, 3, 2, 2 Input: grid = [[1,3],[2,2]] n = 2 HASH APPROACH 1 Create Hash Set Track seen numbers 2 Traverse Grid Check each value Hash Set State 1 2 3 X 4 missing 2 already in set = repeated 3 Find Repeated If in set: a = 2 4 Find Missing Check 1 to n²: b = 4 Time: O(n²) | Space: O(n²) Single pass + lookup FINAL RESULT Found Values: REPEATED 2 a = 2 MISSING 4 b = 4 Verification: Grid has: 1, 2, 2, 3 Expected: 1, 2, 3, 4 2 repeated, 4 missing - OK Output: [2, 4] [repeated, missing] --> --> Key Insight: Hash-based approach uses a Set to track seen numbers. When a number is already in the set, it's the repeated value (a). Then iterate 1 to n² to find which number is not in the set - that's the missing value (b). O(1) lookup makes this efficient! TutorialsPoint - Find Missing and Repeated Values | Hash Approach
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