
Problem
Solution
Submissions
Missing Number in Array
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to find the missing number in an array containing n distinct numbers taken from the range 0 to n. The array will have exactly one missing number from this consecutive sequence.
Example 1
- Input: nums = [3, 0, 1]
- Output: 2
- Explanation:
- The array contains numbers [3, 0, 1] from range 0 to 3.
- The complete sequence should be [0, 1, 2, 3].
- Comparing with the given array, number 2 is missing.
- Therefore, the missing number is 2.
- The array contains numbers [3, 0, 1] from range 0 to 3.
Example 2
- Input: nums = [0, 1, 3, 4, 5, 6, 7, 9]
- Output: 2
- Explanation:
- The array contains numbers from range 0 to 9.
- The complete sequence should be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
- Comparing with the given array, number 2 is missing.
- Therefore, the missing number is 2.
- The array contains numbers from range 0 to 9.
Constraints
- 1 ≤ nums.length ≤ 10^4
- 0 ≤ nums[i] ≤ nums.length
- All numbers in nums are unique
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the mathematical sum formula to calculate expected sum of numbers from 0 to n
- Calculate the actual sum of all numbers in the given array
- The difference between expected sum and actual sum gives the missing number
- Expected sum formula: n * (n + 1) / 2, where n is the length of complete sequence
- Alternatively, use XOR operation to find the missing number efficiently