Tutorialspoint
Problem
Solution
Submissions

Missing Number in an Array

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 8

Write a C# 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.

Example 1
  • Input: nums = [3, 0, 1]
  • Output: 2
  • Explanation:
    • n = 3 since there are 3 numbers, so all numbers are in the range [0, 3].
    • 2 is the missing number since it does not appear in nums.
Example 2
  • Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
  • Output: 8
  • Explanation:
    • n = 9 since there are 9 numbers, so all numbers are in the range [0, 9].
    • 8 is the missing number since it does not appear in nums.
Constraints
  • n == nums.length
  • 1 ≤ n ≤ 10^4
  • 0 ≤ nums[i] ≤ n
  • All the numbers of nums are unique
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysAccentureSnowflake
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 first n natural numbers: n*(n+1)/2
  • Find the sum of the given array
  • The difference between the expected sum and actual sum is the missing number
  • Alternatively, you can use bit manipulation with XOR operations

Steps to solve by this approach:

 Step 1: Determine n from the length of the input array.
 Step 2: Calculate the expected sum of all numbers from 0 to n using the formula n*(n+1)/2.
 Step 3: Find the actual sum of all numbers in the array.
 Step 4: The difference between the expected sum and the actual sum is the missing number.
 Step 5: Return this difference as the result.
 Step 6: This approach works because exactly one number is missing from the sequence.
 Step 7: This solution achieves O(n) time complexity and O(1) space complexity.

Submitted Code :