Find All Duplicates
HardAcc. 86.4%
+45 XP 20
The Negation Mark (O(1) Space)
How do you find duplicates in a list without using extra memory? Since the numbers in our list are restricted to the range 1..N, we can use the numbers themselves as "markers." By flipping the sign of a number at a specific index to negative, we can "remember" that we've seen it before!
The Assignment
Your mission is to find all repeating numbers. Your function receives an array nums of size N.
- Iterate through the array. For each number, treat its absolute value as an index:
idx = Math.abs(nums[i]) - 1. - Check the value at that
idx:- If it is already negative, then the current number is a duplicate!
- Otherwise, multiply the value at
idxby -1 to mark it as "seen."
- Print every duplicate you find on a new line.
01EXAMPLE 1
Input
[4,3,2,7,8,2,3,1]Output
2
3Explanation: 2 and 3 repeat.
Constraints
- Solve in O(n) time and O(1) extra space.
ArraysAlgorithms
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[4,3,2,7,8,2,3,1]
Expected Output
2 3
Click RUN to test your solution