← hims & hers Interview Insights
I knew this one but blanked on articulating why the negation trick works under the space constraint.
Use the array itself as a hash table by marking visited indices through sign flipping or value negation. Iterate through the array, and for each value, treat its absolute value minus one as an index; if the value at that index is already negative, the current value is a duplicate. Otherwise, negate the value at that index to mark it as seen.
Pro tip: Clarify upfront that the input array is mutable and that modifying it is acceptable; if not, mention that the problem requires a different approach or additional space. Also, handle edge cases like n=0 or n=1 explicitly.
Confirm that the array can be modified in-place and that values are 1-indexed. Discuss time and space complexity requirements.
Decide between sign flipping (negation) or adding n to visited indices. Sign flipping is simpler but fails if zeros are present; here values are 1..n, so it's safe.
For each element, compute index = abs(value) - 1. If array[index] is negative, record abs(value) as duplicate. Else, negate array[index].
After the pass, the duplicates list is complete. If the array must be restored, do a second pass to take absolute values.
State O(n) time and O(1) extra space (excluding output). Discuss edge cases: no duplicates, all duplicates, n=0, n=1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.