Tutorialspoint
Problem
Solution
Submissions

Missing Number

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program that finds the missing number in an array containing n distinct numbers taken from the range 0 to n. The array should contain all the numbers in the range except one number which is missing.

Example 1
  • Input: nums = [3, 0, 1]
  • Output: 2
  • Explanation:
    We have an array with numbers from the range 0 to 3, with one number missing.
    The array contains [3, 0, 1], so the missing number must be from the range 0 to 3.
    The numbers 0, 1, and 3 are present, but 2 is not in the array.
    Therefore, the missing number is 2.
Example 2
  • Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
  • Output: 8
  • Explanation:
    We have an array with numbers from the range 0 to 9, with one number missing.
    The array contains [9, 6, 4, 2, 3, 5, 7, 0, 1], so the missing number must be from the range 0 to 9.
    After checking each number, we find that 8 is not present in the array.
    Therefore, the missing number is 8.
Constraints
  • The array size will be n, and the range of numbers will be from 0 to n
  • The array will contain exactly n distinct numbers from the range 0 to n+1
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysPwCTutorix
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 formula for the sum of numbers from 0 to n
  • Calculate the expected sum of all numbers from 0 to n
  • Calculate the actual sum of the numbers in the array
  • The difference between the expected sum and the actual sum is the missing number
  • You can also consider using XOR operations for an elegant solution

Steps to solve by this approach:

 Step 1: Calculate the expected sum of all numbers from 0 to n using the formula n*(n+1)/2.

 Step 2: Iterate through the array and calculate the actual sum of all elements.
 Step 3: Subtract the actual sum from the expected sum to find the missing number.
 Step 4: Return the missing number.
 Step 5: An alternative approach is to use XOR operations, as XOR of a number with itself is 0, and XOR of all numbers from 0 to n with all array elements will leave only the missing number.

Submitted Code :