BackmediumArrays

Detect Duplicate Element Solution

Problem Statement

Given an array of integers `nums` of length `n`, where each element is an integer in the range `[1, n - 1]` inclusive. There is guaranteed to be at least one duplicate integer in the array. Find and return this duplicate number without modifying the original array and using only constant extra space `O(1)`.

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

Explanation: The number 2 appears twice in the array, so it is returned as the duplicate.

Constraints

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i] < nums.length
  • All integers in nums except one appear once or more.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free