Start learning free

LESSON 396 OF 637 · LINKED LISTS

Find the Duplicate Number in C#

Practice O(n)

You get an array nums of n + 1 whole numbers. Each number is from 1 to n.

One number appears more than once. Return that number.

Don't change nums. The tests check that it stays the same.

Use only a few extra variables. Don't copy nums, and don't keep a HashSet of the numbers you have seen.

Why is this a linked list lesson? Think of each index as a node. Then nums[i] is the index of the next node.

 

Example 1:

Input: nums = [3,5,1,2,4,3]
Output: 3
Explanation: 3 appears at index 0 and at index 5.
As a linked list, the walk from index 0 goes:
0 -> 3 -> 2 -> 1 -> 5 -> 3 -> 2 -> ...
It goes around forever, and the loop starts at 3.

Example 2:

Input: nums = [4,2,4,4,1]
Output: 4
Explanation: 4 appears three times.
The number 3 does not appear at all.

Example 3:

Input: nums = [1,1]
Output: 1
Explanation: Here n is 1, so both numbers must be 1.

 

Constraints:

  • n is from 1 to 100,000.
  • nums has n + 1 numbers.
  • Each number is from 1 to n.
  • Exactly one number repeats, maybe many times.
  • Every other number appears at most once.
Note:

Your solution should run in O(n) time with O(1) extra memory.



Start at index 0 and follow the arrows: from index i, go to index nums[i]. No number is 0, so the walk never comes back to index 0. It has only n other indexes to visit, so it must run into a loop.

Two indexes hold the repeated number, so two arrows lead into it. That is where the loop starts. Find that index as in Linked List Cycle: a slow and a fast pointer meet inside the loop. Then put one pointer back at index 0. Move both one step at a time. They meet where the loop starts.

Each of the two walks takes at most a few times n steps: O(n) time.
Only two indexes are kept: O(1) extra memory.
Keeping a HashSet of seen numbers also takes O(n) time, but it needs O(n) extra memory. Sorting would change nums.
STEP 1 OF 9
    Ctrl + Enter to check

    Find The Duplicate Number in C#

    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free