MediumArrayHash Table

Find All Duplicates in an Array

LeetCode
1 approach, code in all languages

You are handed an array of length n where every stored value lies between 1 and n. Some values show up exactly twice while the rest show up exactly once. Return every value that appears twice.

The interesting twist is doing this without extra bookkeeping proportional to the input. Because the values themselves are valid indices, the array can double as its own visited-marker: flipping the sign at the slot a value points to records whether that value has been seen before.

Example 1

Input: nums = [4,3,2,7,8,2,3,1]

Output: [2,3]

Both 2 and 3 occur twice; every other number occurs once, so only 2 and 3 are reported.

Example 2

Input: nums = [1,1,2]

Output: [1]

Only the value 1 shows up twice.

Constraints

  • n == nums.length with 1 ≤ n ≤ 10^5
  • 1 ≤ nums[i] ≤ n
  • Each element of nums appears once or twice
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now