The Find All Duplicates in an Array coding problem provides an integer array of length where each integer is in the range . Each integer appears either once or twice. Your goal is to return an array of all the integers that appear twice. The significant constraint here is to do it in time and without using any extra space (aside from the output array).
This is a classic "In-place" manipulation problem frequently asked by Apple, Microsoft, and Amazon. It tests whether you can use the input array itself as a data structure to store state. It evaluation your understanding of how to map values to indices, which is a common optimization technique in low-level system programming where memory is restricted. The Array interview pattern of using sign-flipping is a high-signal indicator of a candidate's ability to optimize for space.
This problem uses the Negative Marking interview pattern. Since all numbers are in the range , you can treat each value as an index (offset by 1).
nums[|x|-1].Array: [4, 3, 2, 7, 8, 2, 3, 1]
nums[3] becomes -7.nums[2] becomes -2.nums[1] is already negative? Wait, if we use indices correctly:
nums[1] was marked negative when we processed the first '3'.nums[1].nums[1]. If it's already negative, '2' is a duplicate.Whenever you see a problem with values in the range and a constraint of space, your mind should immediately jump to "Array as a Hash Table" or "Cyclic Sort" patterns. These are the only ways to track state without extra memory.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Convert an Array Into a 2D Array With Conditions | Medium | Solve | |
| Brick Wall | Medium | Solve | |
| 4Sum II | Medium | Solve | |
| Find the Number of Good Pairs II | Medium | Solve | |
| Card Flipping Game | Medium | Solve |