← Hims & Hers Interview Insights
The naive answer is a hashmap and they'll let you say it, but then they ask you to drop the extra space and that's where it gets interesting.
Use the array itself as a hash table by marking visited indices. For each element, treat its value as an index and negate the value at that index; if it's already negative, the value is a duplicate. This achieves O(n) time and O(1) space without modifying the input permanently (or note that modification is acceptable).
Pro tip: Clarify whether the input can be modified; if not, propose an alternative like Floyd's cycle detection. Also, mention that the solution relies on values being in the range 1 to n, which is a key constraint.
Confirm that the array length is n, values are between 1 and n, and each value appears once or twice. This allows using values as indices.
Decide to use the array itself to track seen numbers by negating the value at the index corresponding to the current number.
For each element, compute the index as abs(value) - 1. If the value at that index is negative, the number is a duplicate; otherwise, negate it.
When a duplicate is found, add the absolute value to the result list.
If the problem requires the original array to be unchanged, iterate again and take absolute values to restore.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.