Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq in Java: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

public String uniq(List<String> lines)

Example:

Input: lines = ["a", "a", "b", "c", "c", "c", "a"]

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build a List<String> result and add the current line only if it differs from the last entry in result. Use .equals() for the comparison, NOT ==.

if (result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1))) {
    result.add(lines.get(i));
}


The full solution:
class Solution {
    public String uniq(List<String> lines) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < lines.size(); i++) {
            if (result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1))) {
                result.add(lines.get(i));
            }
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Java, explained

    Problem overview

    The method uniq takes a List<String> of lines and drops adjacent duplicates: in every run of identical consecutive lines only the first is kept. The surviving lines are returned as one string, joined by newline characters. This is a small version of the Unix uniq command.

    For lines = ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". Printed, that is:

    a
    b
    c
    a
    

    The last "a" survives because it is not next to the first run of "a"s. Only consecutive duplicates are removed, so this is not the same as removing every repeated value.

    Approach: compare with the last line kept

    A line is a duplicate when it equals the line right before it. Since the lines of a run are all equal, comparing with the last line that was kept gives the same answer as comparing with the previous input line. The method builds a result list, and for each line asks one question: is the result empty, or does this line differ from the last item in the result? If so, the line starts a new run and is added.

    That works without any counters or flags, and the list itself remembers what was kept last. The only special case is the very first line, which has nothing before it. An empty result list covers that case.

    Removing all repeated values, not just adjacent ones, would need a set of lines seen so far. This lesson needs no extra structure, because only the neighbour matters.

    Step by step

    1. Create result, an empty ArrayList held in a List<String> variable, for the lines to keep.
    2. Loop with an index. A for loop runs i from 0 while i < lines.size(). lines.get(i) is the line at position i.
    3. Decide whether to keep line i. The condition is result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1)). The last item of result is at index result.size() - 1. The strings are compared with equals, and the ! turns "equal" into "differs". The empty check comes first for a reason explained below.
    4. Add the line with result.add(lines.get(i)). A line equal to the one kept just before it never gets here.
    5. Join and return with String.join("\n", result). The separator goes only between two lines, so the result has no newline at the end.

    The solution in Java

    class Solution {
        public String uniq(List<String> lines) {
            List<String> result = new ArrayList<>();
            for (int i = 0; i < lines.size(); i++) {
                if (result.isEmpty() || !lines.get(i).equals(result.get(result.size() - 1))) {
                    result.add(lines.get(i));
                }
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • Short-circuit ||. In A || B, Java evaluates B only when A is false. When result is empty, result.isEmpty() is true, so result.get(result.size() - 1) never runs. If the two operands were swapped, the first line would call result.get(-1) and throw an IndexOutOfBoundsException.
    • equals against ==. On strings, == compares references, not text. Two lines with the same characters can be different objects, and == would call them different. equals compares the characters, and it is the right tool here.
    • List.get against array indexing. A List has no [i]; it uses get(i) and size(). An array would use [i] and length.
    • Imports. A standalone file needs import java.util.*; for List and ArrayList.

    Complexity

    Time: O(n) in the number of lines, times the cost of comparing two lines. Each line is compared with at most one other string, and ArrayList.get and add take constant time on average. Joining copies every kept character once.

    Space: O(n). The result list holds up to n references, and the joined string is a new copy of the kept text.

    Edge cases and common mistakes

    • An empty list. The loop does not run and the result is "".
    • One line. ["x"] gives "x": the result is empty at that moment, so the line is kept.
    • Everything identical. ["z", "z", "z"] gives "z".
    • Not adjacent. ["a", "b", "a", "b"] gives "a\nb\na\nb". Nothing is removed, because no two neighbours are equal.
    • Case counts. ["a", "A", "a"] gives "a\nA\na", since equals is case-sensitive.
    • Empty lines. ["", "", "a"] gives "\na": the two empty lines collapse into one, which comes out as an empty line before a.
    • Using == on strings. It may seem to work for literals typed in the source, but it fails for strings built at run time.
    • Using a set. A HashSet would remove every repeat, and it loses the order of first appearance unless it is a LinkedHashSet. The task keeps repeats that are not adjacent.

    Testing

    • ["a", "a", "b", "c", "c", "c", "a"] gives "a\nb\nc\na".
    • [] gives "".
    • ["x"] gives "x".
    • ["a", "b", "a", "b"] gives "a\nb\na\nb".
    • ["", "", "a"] gives "\na".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free