Find All Duplicates in an Array
medium
arrays
hashing
You are given an integer array nums of length n where every element is in the range [1, n], and each integer appears either once or twice. Return an array of all the integers that appear twice. The returned array must be sorted in ascending order.
Input / output
- Input:
nums: int[] - Output:
int[]containing every value that appears exactly twice, sorted ascending
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= nums.length- Each integer in
numsappears either once or twice
Follow-up
Can you solve it in O(n) time and O(1) extra space (not counting the output array), for example by marking visited values in place with nums[abs(val) - 1] *= -1 and detecting when a position is already negative?
Examples
Example 1
Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2: no duplicates
Input: nums = [1,2,3,4,5]
Output: []
Example 3: every value is duplicated
Input: nums = [1,1,2,2,3,3]
Output: [1,2,3]