Skip to main content
All Questions

Determine if an array of integers from 1 to n contains a duplicate in constant time and space.

Medium
Unlock detailed company stats for this questionUpgrade

You're given an array nums of n + 1 integers, where every value is between 1 and n inclusive. Exactly one value appears more than once, possibly many times. Return that value.

Solve it without changing nums and using only O(1) extra space.

Example 1

Input: nums = [1, 3, 4, 2, 2] Output: 2

The array holds five values from 1 to 4, and 2 is the one that repeats.

Example 2

Input: nums = [3, 3, 3, 3, 3] Output: 3

The repeated value can fill most of the array.

Constraints

  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one value appears two or more times.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.