Tutorialspoint
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)
ArraysNumberTech MahindraAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Determine the expected length (n) of the complete array.

 Step 2: Calculate the expected sum of numbers from 0 to n using the formula n*(n+1)/2.
 Step 3: Iterate through the input array and calculate the actual sum of all elements.
 Step 4: Subtract the actual sum from the expected sum to find the missing number.
 Step 5: Return the missing number as the result.

Submitted Code :