
Problem
Solution
Submissions
Missing Number in Array
Certification: Basic Level
Accuracy: 100%
Submissions: 4
Points: 5
Write a Java program to find the missing number in an array containing n distinct numbers taken from 0 to n. The array may be in any order and contains n-1 elements, with one number missing.
Example 1
- Input: nums = [3,0,1]
- Output: 2
- Explanation:
- Numbers from 0 to 3 → missing number is 2
Example 2
- Input: nums = [9,6,4,2,3,5,7,0,1]
- Output: 8
- Explanation:
- Numbers from 0 to 9 → missing number is 8
Constraints
- n == nums.length + 1
- 1 ≤ n ≤ 10^4
- 0 ≤ nums[i] ≤ n
- All numbers from 0 to n appear exactly once, except one
- 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
- Calculate the sum of all numbers from 0 to n using the formula n*(n+1)/2.
- Calculate the sum of all elements in the array.
- The difference between these two sums will be the missing number.
- Alternatively, consider using bit manipulation with XOR operations.
- Remember to handle edge cases like an empty array or arrays with special values.