N-Repeated Element in Size 2N Array - Problem

You are given an integer array nums with the following properties:

  • nums.length == 2 * n
  • nums contains n + 1 unique values
  • n of the unique values occur exactly once in the array
  • Exactly one element of nums is repeated n times

Return the element that is repeated n times.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,3]
Output: 3
💡 Note: Array length is 4 = 2*2, so n=2. Element 3 appears exactly 2 times, while 1 and 2 appear once each.
Example 2 — Different Arrangement
$ Input: nums = [2,1,2,5,3,2]
Output: 2
💡 Note: Array length is 6 = 2*3, so n=3. Element 2 appears exactly 3 times, while other elements appear once.
Example 3 — Minimum Size
$ Input: nums = [5,1,5,2,5,3,5,4]
Output: 5
💡 Note: Array length is 8 = 2*4, so n=4. Element 5 appears exactly 4 times, occupying half the array.

Constraints

  • 2 ≤ nums.length ≤ 2 * 104
  • nums.length is even
  • -109 ≤ nums[i] ≤ 109
  • nums contains exactly n + 1 unique values
  • Exactly one value appears n times

Visualization

Tap to expand
N-Repeated Element in Size 2N Array INPUT nums = [1, 2, 3, 3] 1 idx 0 2 idx 1 3 idx 2 3 idx 3 Properties: • Length = 2n = 4 (n=2) • n+1 = 3 unique values • One element repeats n times Unique values: {1, 2, 3} 1 appears: 1 time 2 appears: 1 time 3 appears: 2 times (n times!) ALGORITHM STEPS 1 Check Adjacent Pairs Compare nums[i] with nums[i+1] 2 Check Gap-1 Pairs Compare nums[i] with nums[i+2] 3 If Match Found Return the repeated element 4 Edge Case Check first and last elements Execution Trace: i=0: nums[0]=1, nums[1]=2 X i=1: nums[1]=2, nums[2]=3 X i=2: nums[2]=3, nums[3]=3 OK Match found! Return 3 FINAL RESULT The repeated element is: 3 Output: 3 Element 3 appears n=2 times in the array of length 2n=4 Complexity Analysis Time: O(n) - single pass Space: O(1) - constant Key Insight: With n repeated elements in array of size 2n, at least two copies must be within distance 2 of each other. By pigeonhole principle: checking adjacent pairs (gap 0, 1, 2) guarantees finding the repeated element in O(n) time, O(1) space. TutorialsPoint - N-Repeated Element in Size 2N Array | Adjacent Pair Check - Space Optimal
Asked in
Google 15 Amazon 12 Apple 8 Microsoft 6
28.0K Views
Medium Frequency
~10 min Avg. Time
950 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen