Problem
Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
Examples
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Solution
We can use usual methods like hashmap, etc, but here we can use numbers as indices.
Method 1 - Using Numbers as Indices
As numbers are between [1,n]
, we can use them as index [0, n-1]
. When we see the number, we will make nums[num-1]
as negative as a visited array.
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i]) - 1;
if (nums[idx] > 0) {
nums[idx] = -nums[idx];
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
result.add(i + 1);
}
}
return result;
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Con of this approach is array modification.