Drill

ProblemsJava › data

Drop the repeats

easydataHash mapsArraysJava

A feed sometimes sends the same id twice, and a clean list keeps only the first sighting.

dedupe(values: list<int>) → list<int>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> dedupe(List<Integer> values) {
    
}

Worked examples

CallResult
dedupe(Main.<Integer>ls(1, 2, 3, 1, 2))Main.<Integer>ls(1, 2, 3)
dedupe(Main.<Integer>ls(1, 1, 1))Main.<Integer>ls(1)
dedupe(Main.<Integer>ls())Main.<Integer>ls()
dedupe(Main.<Integer>ls(3, 1, 2, 1, 3))Main.<Integer>ls(3, 1, 2)

Hint

Carry a set of what you have already seen, and only push a value the first time you meet it.

Reference solution in Java
List<Integer> dedupe(List<Integer> values) {
    Set<Integer> seen = new HashSet<>();
    List<Integer> result = new ArrayList<>();
    for (int v : values) {
        if (seen.add(v)) result.add(v);
    }
    return result;
}

The same problem in another language

More data problems in Java