Tech Interview RoomStudy guides

Java 8

Java 8: Find duplicate elements in a list. Show every approach from brute force to optimal.

Intermediate · 2 min read · Lesson 2 of 10 in Java 8

Problem

Given a List<Integer>, return each value that appears more than once, in the order it was first seen. For example [4, 7, 4, 9, 7, 4] → [4, 7].

Approach 1: Nested loops (feasible, O(n²))

Compare every pair. No extra data structures besides the result, but quadratic.

java
import java.util.ArrayList;
import java.util.List;

class DupBrute {
    static List<Integer> find(List<Integer> list) {
        List<Integer> dups = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (list.get(i).equals(list.get(j)) && !dups.contains(list.get(i))) {
                    dups.add(list.get(i));
                    break;
                }
            }
        }
        return dups;
    }
}

Approach 2: Sort, then compare neighbours (O(n log n), little extra memory)

After sorting, duplicates are adjacent. Good when memory is tight, but the original order is lost.

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class DupSort {
    static List<Integer> find(List<Integer> list) {
        List<Integer> sorted = new ArrayList<>(list);
        Collections.sort(sorted);
        List<Integer> dups = new ArrayList<>();
        for (int i = 1; i < sorted.size(); i++) {
            boolean same = sorted.get(i).equals(sorted.get(i - 1));
            boolean alreadyAdded = !dups.isEmpty() && dups.get(dups.size() - 1).equals(sorted.get(i));
            if (same && !alreadyAdded) dups.add(sorted.get(i));
        }
        return dups;   // sorted order, not first-seen order
    }
}

Approach 3: HashSet "seen" set (O(n), the standard answer)

Set.add returns false when the element is already present, which detects the duplicate in one call. A LinkedHashSet for the result keeps first-seen order and removes repeats.

java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class DupHashSet {
    static List<Integer> find(List<Integer> list) {
        Set<Integer> seen = new HashSet<>();
        Set<Integer> dups = new LinkedHashSet<>();
        for (Integer x : list) {
            if (!seen.add(x)) dups.add(x);
        }
        return new ArrayList<>(dups);
    }
}

Approach 4: Java 8 Streams with groupingBy (O(n))

Count every element, then keep keys with a count above one. LinkedHashMap::new preserves first-seen order. Side-effect free, so it is also safe to run in parallel.

java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

class DupStreams {
    static List<Integer> find(List<Integer> list) {
        return list.stream()
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
            .entrySet().stream()
            .filter(e -> e.getValue() > 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
    }

    // Shorter, using the HashSet trick inside a stream (fine sequentially, NOT thread-safe in parallel)
    static List<Integer> findWithSet(List<Integer> list) {
        java.util.Set<Integer> seen = new java.util.HashSet<>();
        return list.stream().filter(x -> !seen.add(x)).distinct().collect(Collectors.toList());
    }

    // Anti-pattern often seen in interviews: Collections.frequency inside filter is O(n²)
    static List<Integer> findSlow(List<Integer> list) {
        return list.stream().filter(x -> java.util.Collections.frequency(list, x) > 1)
                   .distinct().collect(Collectors.toList());
    }
}

Approach 5: BitSet for bounded non-negative integers (O(n), fastest constant factors)

When values are known to lie in a small range (ids 0 to 10 million), a BitSet uses one bit per possible value: no boxing, no hashing.

java
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

class DupBitSet {
    static List<Integer> find(int[] values) {
        BitSet seen = new BitSet(), reported = new BitSet();
        List<Integer> dups = new ArrayList<>();
        for (int v : values) {
            if (seen.get(v) && !reported.get(v)) { dups.add(v); reported.set(v); }
            seen.set(v);
        }
        return dups;
    }
}

Run all approaches

java
import java.util.Arrays;
import java.util.List;

class DupDemo {
    public static void main(String[] args) {
        List<Integer> in = Arrays.asList(4, 7, 4, 9, 7, 4);
        System.out.println(DupBrute.find(in));        // [4, 7]
        System.out.println(DupSort.find(in));         // [4, 7] (sorted order)
        System.out.println(DupHashSet.find(in));      // [4, 7]
        System.out.println(DupStreams.find(in));      // [4, 7]
        System.out.println(DupStreams.findWithSet(in));
        System.out.println(DupStreams.findSlow(in));
        System.out.println(DupBitSet.find(new int[] {4, 7, 4, 9, 7, 4}));
    }
}

Feasible → optimal

  1. Nested loops and Collections.frequency in a stream: O(n²).
  2. Sort and scan: O(n log n), loses order, little memory.
  3. HashSet seen-set or groupingBy: O(n) time, O(n) memory: the default answer.
  4. BitSet: O(n) with the smallest memory and no boxing when values are small non-negative integers.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you find duplicates in an array of n+1 integers in the range 1..n without modifying it and with O(1) extra space?

Treat each value as a pointer to an index (i → nums[i]); a duplicate creates a cycle, so Floyd's cycle detection finds it: move a slow pointer one step and a fast pointer two steps until they meet, then reset one to the start and move both one step until they meet at the duplicate. O(n) time, O(1) space.

How would you remove duplicates while preserving order?

new ArrayList<>(new LinkedHashSet<>(list)), or list.stream().distinct().collect(toList()). Both are O(n) and keep the first occurrence; distinct() uses equals/hashCode, so custom objects need those implemented (records do this automatically).