Leetcode 2965: Find Missing and Repeated Values

grid47
grid47
Exploring patterns and algorithms
Jan 15, 2024 8 min read

You are given a 2D integer matrix grid of size n * n. The matrix contains integers in the range [1, n²], and each number appears exactly once, except for two numbers. One number a is repeated twice, and another number b is missing. Find the repeating and missing numbers a and b.
Problem
Approach
Steps
Complexity
Input: You are given a 2D matrix `grid` where the matrix size is `n * n` and contains values in the range [1, n²]. The matrix has one repeated number `a` and one missing number `b`.
Example: grid = [[4, 1], [2, 4]]
Constraints:
• 2 <= n == grid.length == grid[i].length <= 50
• 1 <= grid[i][j] <= n * n
• Exactly one number appears twice and exactly one number is missing.
Output: Return a 0-indexed integer array of size 2 where `ans[0]` is the repeated number `a` and `ans[1]` is the missing number `b`.
Example: [4, 3]
Constraints:
Goal: Use XOR operations to efficiently find the repeated and missing numbers.
Steps:
• XOR all numbers from 1 to n².
• XOR all elements from the grid.
• Find the differing bit between the repeated and missing numbers.
• Use the differing bit to segregate the numbers and identify `a` and `b`.
Goal: The matrix contains exactly one duplicate number and one missing number.
Steps:
• 2 <= n == grid.length == grid[i].length <= 50
• 1 <= grid[i][j] <= n * n
• Exactly one number appears twice and exactly one number is missing.
Assumptions:
• The matrix will always have one repeated and one missing number.
• All integers are within the valid range [1, n²].
Input: Input: grid = [[4, 1], [2, 4]]
Explanation: The repeated number is 4, and the missing number is 3. Hence, the result is [4, 3].

Input: Input: grid = [[1, 3, 4], [2, 1, 7], [8, 5, 9]]
Explanation: The repeated number is 1, and the missing number is 6. Hence, the result is [1, 6].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus