Search⌘ K
AI Features

Find the Duplicate Number

Explore how to identify the duplicate number in an array without modifying it, using the fast and slow pointer technique. This lesson teaches you to detect cycles and duplicates with constant extra space, helping you understand a key coding interview pattern fundamental for algorithmic problem solving.

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.

Java
usercode > FindDuplicate.java
import java.util.*;
public class FindDuplicate{
public static int findDuplicate(int[] nums) {
// Replace this placeholder return statement with your code
return 0;
}
}
Find the Duplicate Number