Find missing number
The problem
Given an integer array of size n containing distinct values in the range from 0 to n (inclusive), return the only number missing from the array within this range.
Input: nums = [0, 2, 3, 1, 4] Output: 5 Explanation: nums contains 0, 1, 2, 3, 4 thus leaving 5 as the only missing number in the range [0, 5]
Input: nums = [0, 1, 2, 4, 5, 6] Output: 3 Explanation: nums contains 0, 1, 2, 4, 5, 6 thus leaving 3 as the only missing number in the range [0, 6]
Input: nums = [1, 3, 6, 4, 2, 5]
- n == nums.length
- 1 <= n <= 104
- 0 <= nums[i] <= n
- All the numbers of nums are unique.
cpp
class Solution {
public:
int missingNumber(vector<int>& nums) {
}
};java
class Solution {
public int missingNumber(int[] nums) {
}
}python
class Solution:
def missingNumber(self, nums):javascript
class Solution {
missingNumber(nums) {
}
}csharp
public class Solution {
public int MissingNumber(List<int> nums) {
}
}go
func missingNumber(nums []int) int {
//your code goes here
}Stuck? Show a way to structure it+
- 01Use the fact that expected values are 0 through n.
- 02Either sum the expected range and subtract array values or XOR both sets.
- 03Prefer XOR when overflow is a concern.
- 04Return the remaining unmatched value.
Reference answer
Then expect these follow-ups
How would you find a duplicate when values are 1..n?
Tests: cycle detection or arithmetic
How would you handle many missing values?
Tests: set/bitset trade-offs
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question