Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Find every value that appears twice

Medium · Target 20 minutes · Arrays and hashing· Type asked at

You're given an array nums of length n where every value lies between 1 and n and each value shows up once or twice. I'd like you to return every value that shows up twice, in increasing order.

Your solution should run in O(n) time and use only constant extra space apart from the list you return. You're allowed to change the array while you work.

Examples

InputOutputWhy
nums = [4, 3, 2, 7, 8, 2, 3, 1][2, 3]Both 2 and 3 turn up twice and the other values only once.
nums = [1, 1, 2][1]There's a single repeat, which is the 1.
nums = [1][]A single value can't be repeated, so the list is empty.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ n
  • each value appears once or twice

Hints

Hint 1

Ask yourself what a hash set would be doing for you here, because all it records is one yes or no for each value from 1 to n.

Hint 2

You already own n slots and there are n values you might have to remember, so slot v − 1 can hold the yes or no for value v.

Hint 3

Every value in the array is positive, so you can flip the sign of nums[v − 1] the first time you meet v and still read the value back with an absolute value later on.

Where people lose marks

  • Reading nums[i] where you meant |nums[i]|. Once an earlier step has flipped that slot the value is negative, the index v − 1 goes below zero, and depending on the language you either crash or read garbage.
  • Checking whether slot v − 1 is negative after you've already flipped it. Then every value looks like a duplicate the first time you meet it, so do the check first and the flip second.
  • Leaving the array negated when the caller still needs it. If that matters, finish with one more pass that takes the absolute value of every slot.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.