MediumArrayHash Table

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Twice-Scanned Bin Labels is our own problem on the technique behind Find All Duplicates in an Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free