Search⌘ K
AI Features

Find the Duplicate Number

Explore how to find the duplicate number in an array where numbers range from 1 to n, using fast and slow pointer techniques. Learn to solve this problem efficiently without modifying the input array and with constant extra space. This lesson helps you understand cycle detection concepts applied to arrays, and guides you through problem analysis, hints, and hands-on coding practice.

Statement

Given an array of positive numbers, nums, such that the values lie in the range [1,n][1, n], inclusive, and that there are n+1n+1 numbers in the array, find and return the duplicate number present in nums. There is only one repeated number in nums, but it may appear more than once in the array.

Note: You cannot modify the given array nums. You have to solve the problem using only constant extra space.

Constraints:

  • 1n1031 \leq n \leq 10^3
  • nums.length =n+1= n + 1
  • 11 \leq nums[i] n\leq n
  • All the integers in nums are unique, except for one integer that will appear more than once.

Examples

canvasAnimation-image
1 / 5

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Find The Duplicate Number

1.

What is the output if the following list of integers is given as input?

[1, 5, 4, 3, 2, 4, 6]

A.

5

B.

3

C.

4

D.

7


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Need a nudge?

Explore these hints—each one is designed to guide you a step closer to the solution.

C++
usercode > main.cpp
#include <iostream>
#include <vector>
int FindDuplicate(vector<int> nums)
{
// Replace this placeholder return statement with your code
return -1;
}
Find the Duplicate Number