Start learning free

LESSON 19 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Java: Printing Only the Repeated Lines

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

public String uniqDups(List<String> lines)

Example:

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

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


Track prev and count. When the line changes (or after the loop), flush prev only if count > 1. Use .equals() to compare strings.

if (count > 1) {
    result.add(prev);
}


The full solution:
class Solution {
    public String uniqDups(List<String> lines) {
        List<String> result = new ArrayList<>();
        int count = 0;
        String prev = null;
        for (int i = 0; i < lines.size(); i++) {
            if (count > 0 && lines.get(i).equals(prev)) {
                count++;
            } else {
                if (count > 1) {
                    result.add(prev);
                }
                prev = lines.get(i);
                count = 1;
            }
        }
        if (count > 1) {
            result.add(prev);
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Java, explained

    Problem overview

    The method uniqDups takes a List<String> of lines and returns only the values whose adjacent run is longer than one line, which are the lines that really repeat back to back. Each such value appears once, with no count, and the values are joined by \n. This is the -d flag of the Unix uniq command.

    For ["a", "a", "b", "c", "c", "c"] the result is "a\nc". Printed:

    a
    c
    

    The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.

    Approach: measure each run, keep the long ones

    The method has the same shape as the one that counts runs. Two variables describe the run the loop is in: prev, its text, and count, its length so far. A run is complete when a different line arrives. At that moment the method decides whether to keep it: if count is above 1, the run was repeated, so prev goes into the result once.

    The last run needs special care. No line comes after it, so the loop never completes it, and the same test runs again after the loop.

    Here is the state after each iteration for the example, from a real run:

    ilinecountprevresult
    0a1a[]
    1a2a[]
    2b1b[a]
    3c1c[a]
    4c2c[a]
    5c3c[a]

    The run of "a"s is added when b arrives at index 2. The run of "c"s is still open after index 5. The test after the loop adds it, which gives [a, c].

    Step by step

    1. Create result, an empty ArrayList in a List<String> variable. It holds one copy of each repeated line.
    2. Create count, an int starting at 0, where 0 means no run has started.
    3. Create prev, a String set to null, which will remember which line the current run is made of.
    4. Loop with an index from 0 while i < lines.size().
    5. Test for a continuing run: count > 0 && lines.get(i).equals(prev), followed by an else.
    6. Continue the run: in the if branch, count++.
    7. Check whether the finished run was repeated: in the else branch, if (count > 1). A run of one line was not repeated. For the first line count is 0, which is not above 1 either, so nothing is added for a run that does not exist.
    8. Keep one copy: inside that if, result.add(prev). One copy is enough however long the run was.
    9. Start the next run: set prev to lines.get(i), because the line that ended the old run starts the new one.
    10. Set count = 1, since the new run has one line so far.
    11. Test the last run after the loop with the same if (count > 1).
    12. Add it with result.add(prev).
    13. Join and return with String.join("\n", result).

    The solution in Java

    class Solution {
        public String uniqDups(List<String> lines) {
            List<String> result = new ArrayList<>();
            int count = 0;
            String prev = null;
            for (int i = 0; i < lines.size(); i++) {
                if (count > 0 && lines.get(i).equals(prev)) {
                    count++;
                } else {
                    if (count > 1) {
                        result.add(prev);
                    }
                    prev = lines.get(i);
                    count = 1;
                }
            }
            if (count > 1) {
                result.add(prev);
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • null as "nothing yet". prev is a reference type, so it can hold null before the first line. lines.get(i).equals(prev) is safe with a null argument and returns false, and the count > 0 test already rules out the first iteration.
    • equals against ==. Run detection compares the text of two strings, so it needs equals. The == operator compares references.
    • The duplicated test. The condition count > 1 appears twice, inside the loop and after it. The repetition is the price of a loop that only reacts when a different line arrives: the last run never meets one.
    • Imports. A standalone file needs import java.util.*; for List and ArrayList.

    Complexity

    Time: O(m), where m is the total number of characters: each line is compared once with prev, and the work for a finished run is constant.

    Space: O(n + m). The result list holds up to one reference per run, and the joined string is a new copy of the kept text.

    Edge cases and common mistakes

    • No repeats. ["a", "b", "c"] gives "", and so does an empty list.
    • Only a repeated pair. ["x", "x"] gives "x". Nothing arrives after the pair, so only the test after the loop adds it.
    • Forgetting the last run. ["b", "a", "a"] should give "a". Without the code after the loop it would give "".
    • Not adjacent. ["a", "b", "a"] gives "", since the two as are never neighbours.
    • Two separate runs of the same value. ["a", "a", "b", "a", "a"] gives "a\na", because the a runs are different runs and each one is reported once.
    • Empty lines. ["", "", "a"] gives "". The repeated empty line would be a value, but the result is a single empty string, so it joins to "" and looks like no output.
    • Testing count >= 1. That keeps every run and turns the method into the one that drops adjacent duplicates.
    • Adding inside the if branch. Adding prev each time count grows would put one copy per extra line, not one per run.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives "a\nc".
    • ["a", "b", "c"] gives "".
    • ["x", "x"] gives "x".
    • ["b", "a", "a"] gives "a".
    • ["a", "a", "b", "a", "a"] gives "a\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