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 number from 1 to n that is missing

Easy · Target 15 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 a value can turn up any number of times. I'd like you to return every number from 1 to n that doesn't appear in the array, in increasing order.

Try to do it in O(n) time with no extra memory apart from the list you hand back. You're allowed to change the array as you go.

Examples

InputOutputWhy
nums = [4, 3, 2, 7, 8, 2, 3, 1][5, 6]Eight values and the two that never turn up are 5 and 6.
nums = [1, 1][2]The 1 is there twice and that leaves no room for the 2.
nums = [1, 2, 3][]Every number from 1 to 3 is there, so nothing is missing.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ n

Hints

Hint 1

With a set you'd put every value in and then count from 1 to n looking for gaps, so ask yourself what the set is actually storing for each number.

Hint 2

All it stores is a yes or a no for each number from 1 to n, and you've already got an array with exactly n slots you're allowed to write on.

Hint 3

Make nums[v − 1] negative whenever you meet v, and when you've gone through the whole array the slots that are still positive tell you which numbers never turned up.

Where people lose marks

  • Flipping the sign with nums[j] = −nums[j] on every visit. A value that turns up twice flips its slot back to positive and the number then looks missing, so you want to set it to minus its absolute value.
  • Reading nums[i] where you meant |nums[i]|, which goes wrong as soon as an earlier step has flipped the slot you're standing on.
  • Leaving the array full of minus signs when the caller still needs it. If that matters you can take the absolute value of every slot in the second pass while you collect the answer.
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.