Find All Duplicates in an Array

MediumArrays & Hashinghashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums of length n. Every value lies in the range [1, n], and each value appears either once or twice. Return all values that appear twice. The result may be in **any order**; each such value is listed once. Aim for O(n) time and O(1) extra space besides the output. Since values are valid indices, you may use the array itself as the bookkeeping space.

Examples

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
2 and 3 each appear twice.
Input: nums = [1,1,2]
Output: [1]
Input: nums = [1]
Output: []
No value repeats.

Constraints

  • n == nums.length
  • 1 <= n <= 10^5
  • 1 <= nums[i] <= n
  • Each value appears once or twice.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems