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

Coding · Two pointers

The repeated number, without changing the array

Medium · Target 20 minutes · Two pointers· Type asked at

You're given an array nums of n + 1 integers, each from 1 to n. Exactly one value turns up more than once (it might turn up several times). Return that value without changing the array and using only O(1) extra space.

Examples

InputOutputWhy
nums = [1, 3, 4, 2, 2]2
nums = [3, 1, 3, 4, 2]3
nums = [3, 3, 3, 3, 3]3I'd point out that the repeated value can take up most of the array (n is 4 here so 1, 2 and 4 never turn up at all).

Constraints

  • 1 ≤ n ≤ 10⁵
  • nums.length = n + 1
  • 1 ≤ nums[i] ≤ n
  • exactly one value repeats

Hints

Hint 1

A set would work but it's O(n) space, and sorting or marking with signs changes the array, so I'd think of the array as something else. What if index i had an arrow going to index nums[i]?

Hint 2

If you start at index 0 (which nothing points to since the values run from 1 to n) and keep following arrows you'll end up going round a cycle, and the value that two arrows share is where that cycle starts.

Hint 3

That's Floyd's method, where a slow pointer takes one step and a fast one takes two until they meet in the cycle. Then you'd put one of them back at 0 and move both one step at a time, and wherever they meet now is the start.

Where people lose marks

  • Starting at index 1, when it's index 0 that nothing points to and that's why it's the only safe place to start. From anywhere else you might already be inside the cycle and you'd miss the way in.
  • Returning the place where they met in the first phase, which is somewhere on the cycle and is only the start of it if you're lucky.
  • Starting slow and fast both at 0 with a plain while loop, so that they're equal before anything's moved and the loop never runs at all. I'd take the first steps before the loop (as here) or use a do-while.
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.