LeetCode 2965: Find Missing and Repeated Values Solution
Master LeetCode problem 2965 (Find Missing and Repeated Values), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2965. Find Missing and Repeated Values
Problem Explanation
Explanation:
To solve this problem, we can use a set to keep track of the numbers we have seen so far. We iterate through the grid, calculating the expected sum of numbers from 1 to n^2, the actual sum of numbers in the grid, and keep track of the repeated and missing numbers.
- Calculate the expected sum of numbers from 1 to n^2 using the formula n * (n + 1) / 2.
- Calculate the actual sum of numbers in the grid.
- Iterate through the grid:
- For each number in the grid:
- Check if the number has been seen before:
- If yes, mark it as the repeated number.
- If no, add it to the set of seen numbers.
- Check if the number has been seen before:
- For each number in the grid:
- Calculate the missing number as the difference between the expected sum and the actual sum minus the repeated number.
The time complexity of this solution is O(n^2) as we iterate through the grid once. The space complexity is O(n^2) to store the set of seen numbers.
:
Solution Code
class Solution {
public int[] findErrorNums(int[][] grid) {
int n = grid.length;
Set<Integer> seen = new HashSet<>();
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
int repeated = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (seen.contains(grid[i][j])) {
repeated = grid[i][j];
} else {
seen.add(grid[i][j]);
actualSum += grid[i][j];
}
}
}
int missing = expectedSum - actualSum + repeated;
return new int[]{repeated, missing};
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2965 (Find Missing and Repeated Values)?
This page provides optimized solutions for LeetCode problem 2965 (Find Missing and Repeated Values) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2965 (Find Missing and Repeated Values)?
The time complexity for LeetCode 2965 (Find Missing and Repeated Values) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2965 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2965 in Java, C++, or Python.