Problem Description
Given an n x n matrix containing numbers in the range [1, n²] where all but two numbers appear exactly once—one number appears twice and one is missing—find the repeating number and the missing number. Return the answer as a 0-indexed array where the first element is the repeated number and the second is the missing one.
Key Insights
- The grid is treated as a flattened list of numbers in the range [1, n²].
- Use a frequency counter (hash table or array) to track occurrences of each integer.
- The number with frequency 2 is the repeated value, while the one with frequency 0 is the missing value.
- The grid size is small (n up to 50), so a simple O(n²) approach is efficient.
Space and Time Complexity
Time Complexity: O(n²), where n² is the total number of elements in the grid. Space Complexity: O(n²), for storing the frequency of each number in the worst case.
Solution
Flatten the grid and use a hash table (or frequency array) to count appearances of each number from 1 to n². Then iterate through the range [1, n²] to determine which number appears twice (the repeated value) and which number is missing (has a count of zero). Return these two numbers in an array where the repeated number is first and the missing number is second. This method leverages simple counting and iteration to efficiently solve the problem.