
Problem
Solution
Submissions
All Disappeared Numbers
Certification: Basic Level
Accuracy: 100%
Submissions: 2
Points: 5
Write a Java program to find all the numbers that have disappeared in an array. Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array.
Example 1
- Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
- Output: [5, 6]
- Explanation:
- Step 1: The array size is 8, so the numbers should range from 1 to 8.
- Step 2: For each number in the array, mark its presence by negating the value at index (abs(num)-1).
- Step 3: After marking, iterate through the array again. If a value is positive, its index+1 is a missing number.
- Step 4: In this case, values at indices 4 and 5 remain positive, so 5 and 6 are missing.
Example 2
- Input: nums = [1, 1]
- Output: [2]
- Explanation:
- Step 1: The array size is 2, so the numbers should range from 1 to 2.
- Step 2: For each number in the array, mark its presence by negating the value at index (abs(num)-1).
- Step 3: The value at index 0 is negated twice (due to two 1's), so it becomes positive again.
- Step 4: The value at index 1 remains positive, so 2 is missing from the array.
Constraints
- 1 ≤ nums.length ≤ 10^5
- 1 ≤ nums[i] ≤ nums.length
- You must solve this without using extra space (or with O(1) extra space)
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1) not counting the output list
Editorial
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. |
Solution Hints
- Use the array itself to mark visited numbers
- Since all numbers are positive and in the range [1, n], you can use negative marking
- For each number x in the array, mark the element at index (x-1) as negative
- After marking, iterate through the array again. If an element is still positive, it means its index+1 is missing
- This approach avoids using additional space for tracking