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:
| |
Example 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.
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)
Con of this approach is array modification.