Find All Duplicates in an Array

Medium Hash SetArray

Problem

Given an integer array nums where every value is in the range [1, n] (n = length) and each appears once or twice, return all the values that appear exactly twice. Return them in the order their second occurrence is encountered.

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

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def findDuplicates(self, nums):
        res = []
        for x in nums:
            i = abs(x) - 1
            if nums[i] < 0:
                res.append(abs(x))
            else:
                nums[i] = -nums[i]
        return sorted(res)

Java

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        List<Integer> res = new ArrayList<>();
        for (int n : nums) {
            if (!seen.add(n)) res.add(n); // add() returns false if already present
        }
        return res;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Find All Duplicates in an Array interactively → ← All solutions