15 · Linked Lists

#287 Find the Duplicate Number

Mediumsolve on LeetCode ↗

frequently reported atNVIDIAAmazonBloombergGoogleMicrosoft

the problem

In plain words

An array nums holds n + 1 integers, each between 1 and n. Exactly one value appears more than once (it may appear many times). Return that value — without modifying nums, and using only constant extra space.

in nums = [1,3,4,2,2]

out 2

in nums = [3,1,3,4,2]

out 3

in nums = [3,3,3,3,3]

out 3

  • 1 ≤ n ≤ 10⁵
  • nums.length == n + 1
  • 1 ≤ nums[i] ≤ n
  • Exactly one value repeats (possibly many times)
  • Don't modify nums; use only O(1) extra space
  • Follow-up: linear time

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #142
      Linked List Cycle II
      Mediumin Linked Lists
    2. #202
      Happy Number
      Easyin Math & Numbers
    3. #217
      Contains Duplicate
      Easyin Hashing
    4. #268
      Missing Number
      Easyin Bits
    5. #875
      Koko Eating Bananas
      Mediumin Binary Search