Interview Q&A / Java

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a Java method to remove duplicates from a list while keeping the original order.

SHORT ANSWER

Put the elements into a LinkedHashSet, which drops repeats and remembers first-seen order, then copy it back into a list. It takes O(n) time and O(n) space.

Explain it simply

A plain HashSet removes duplicates but scrambles order. A LinkedHashSet does the same and keeps the order in which elements first arrived.

Line by line

java
import java.util.*;

public static <T> List<T> unique(List<T> input) {
    return new ArrayList<>(new LinkedHashSet<>(input));
}

// List<Integer> data = List.of(4, 2, 4, 7, 2, 9);
// unique(data)  returns [4, 2, 7, 9]

The LinkedHashSet constructor adds elements one by one. Each repeat is rejected by equals and hashCode, so only the first copy of 4 and 2 survives. The ArrayList constructor then copies the survivors in order.

A manual version, if the interviewer asks you not to use a ready-made set trick:

java
public static List<Integer> uniqueManual(List<Integer> input) {
    Set<Integer> seen = new HashSet<>();
    List<Integer> out = new ArrayList<>();
    for (int x : input) {
        if (seen.add(x)) out.add(x);     // add() is true only for new values
    }
    return out;
}

Complexity

Time O(n) on average, space O(n).

What to say in the interview

"I use LinkedHashSet for order-preserving de-duplication. The elements need correct equals and hashCode. With streams the same thing is list.stream().distinct().toList()."

Common mistakes

  • Using HashSet and getting a different order.

#java#collections#linkedhashset

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.