Tutorialspoint
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.
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.
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)
ArraysCapgeminiAdobe
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

  • 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

Steps to solve by this approach:

 Step 1: Calculate the length of the input array to determine n.
 Step 2: Use the mathematical formula n * (n + 1) / 2 to find the expected sum of numbers from 0 to n.
 Step 3: Calculate the actual sum of all elements present in the given array.
 Step 4: Subtract the actual sum from the expected sum to get the missing number.
 Step 5: Return the difference as the missing number.

Submitted Code :