Tutorialspoint
Problem
Solution
Submissions

All Disappeared Numbers

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

Write a C program to find all the elements that are missing from an array containing integers from 1 to n, where n is the length of the array. Each integer in the range [1, n] should appear exactly once in the array, but some are missing. Return an array of all the integers in the range [1, n] that do not appear in the input array.

Example 1
  • Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
  • Output: [5, 6]
  • Explanation:
    • The array length is 8, so we expect numbers from 1 to 8.
    • After checking the array, we find that 5 and 6 are missing.
    • Therefore, the output is [5, 6].
Example 2
  • Input: nums = [1, 1]
  • Output: [2]
  • Explanation:
    • The array length is 2, so we expect numbers from 1 to 2.
    • The number 1 appears twice, so the number 2 is missing.
    • Therefore, the output is [2].
Constraints
  • The array length will be in the range [1, 3 * 10^4]
  • The integers in the array will be in the range [1, n], where n is the array length
  • Each integer may appear multiple times in the array
  • Time Complexity: O(n)
  • Space Complexity: O(1) excluding the output array
ArraysDeloitteDropbox
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

  • Consider using the array itself as a hash table
  • Mark the presence of each number by manipulating the sign of the value at the corresponding index
  • After marking, iterate through the array to find indices where the values are positive
  • Those indices (plus 1) represent the missing numbers
  • Be careful not to modify the array permanently if needed for further use

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 :