Start learning free

LESSON 18 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Java: Counting Adjacent Runs with String.format

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as String.format("%7d %s", count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

public String uniqCount(List<String> lines)

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track String prev and int count. When a NEW value comes in (or you reach end), flush the previous run with String.format("%7d %s", count, prev) and reset.

Don't forget to flush AFTER the loop too. Use .equals() for the string comparison.
if (count > 0 && lines.get(i).equals(prev)) {
    count++;
} else {
    if (count > 0) {
        result.add(String.format("%7d %s", count, prev));
    }
    prev = lines.get(i);
    count = 1;
}


The full solution:
class Solution {
    public String uniqCount(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 > 0) {
                    result.add(String.format("%7d %s", count, prev));
                }
                prev = lines.get(i);
                count = 1;
            }
        }
        if (count > 0) {
            result.add(String.format("%7d %s", count, prev));
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Java, explained

    Problem overview

    The method uniqCount takes a List<String> of lines and collapses every run of adjacent duplicates into one output line: the run's length, then the line's text. Each output line is built as String.format("%7d %s", count, value), which is the count right-aligned in 7 characters, a single space, then the value. The output lines are joined with \n. This is the -c flag of the Unix uniq command.

    For ["a", "a", "b", "c", "c", "c"] the output, printed, is:

          2 a
          1 b
          3 c
    

    The runs are two "a"s, one "b" and three "c"s, so there are three output lines.

    Approach: track the current run

    The earlier version only needed to know whether a line differed from the last one kept. Here the length of each run matters, so the method keeps two variables that describe the run the loop is currently in: prev, the text of the run, and count, how many lines it has so far.

    For each line there are two cases:

    • The line equals prev and a run is going: the run grows, so count goes up by 1.
    • Otherwise, the old run has just ended. If there was a run, write its output line. Then start a new run with this line, prev = line and count = 1.

    A run is written only when something different follows it. The last run has nothing after it, so the loop never writes it, and the method must write it once more after the loop.

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

    ilinecountprevoutput lines written so far
    0a1a0
    1a2a0
    2b1b1
    3c1c2
    4c2c2
    5c3c2

    After the loop, count is 3 and prev is c, with two output lines written. The final run is still unwritten. The after-the-loop step adds 3 c as the third.

    Step by step

    1. Create result, an empty ArrayList in a List<String> variable. It holds one output line per run.
    2. Create count, an int starting at 0. Zero means no run has started yet.
    3. Create prev, a String set to null, meaning no text yet.
    4. Loop with an index from 0 while i < lines.size().
    5. Test for a continuing run: count > 0 && lines.get(i).equals(prev), with an else branch for everything else.
    6. Continue the run: in the if branch, count++.
    7. Check whether a run just ended: in the else branch, an inner if (count > 0). For the very first line count is still 0, so nothing is written for a run that does not exist.
    8. Write the finished run: inside that if, add String.format("%7d %s", count, prev) to result.
    9. Start the next run: after the inner if, set prev to lines.get(i), because the line that ended the old run is the first of the new one.
    10. Set count = 1, since the new run has one line so far.
    11. Flush the last run after the loop with the same test, if (count > 0).
    12. Write it inside that if with the same String.format call.
    13. Join and return with String.join("\n", result).

    The solution in Java

    class Solution {
        public String uniqCount(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 > 0) {
                        result.add(String.format("%7d %s", count, prev));
                    }
                    prev = lines.get(i);
                    count = 1;
                }
            }
            if (count > 0) {
                result.add(String.format("%7d %s", count, prev));
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • The format string. %7d prints an integer padded with spaces on the left to a width of 7, and %s prints a string. String.format("%7d %s", 3, "c") gives " 3 c": six spaces, the digit, a space and the letter.
    • Width is a minimum. A count with more than 7 digits is not cut. A run of 12,345,678 lines of z gives "12345678 z". A count of 12 gives " 12 a".
    • prev starts as null. lines.get(i).equals(prev) is safe even then, because the receiver is a real string and equals(null) returns false. The count > 0 test comes first anyway, which makes the intent clear.
    • Why flush after the loop. The in-loop write fires when a different line arrives. After the last line nothing arrives, so a second copy of the write is needed.
    • Imports. A standalone file needs import java.util.*;.

    Complexity

    Time: O(m), where m is the total number of characters: each line is compared once with prev, and each run is formatted once.

    Space: O(n + m). The result list has one string per run, and the joined result is a new string.

    Edge cases and common mistakes

    • An empty list. The loop does not run, count is 0, and the final if is skipped. The result is "".
    • One line. ["x"] gives " 1 x".
    • Forgetting the last run. Without the code after the loop, the output for the example would stop after b and lose c.
    • Not adjacent. ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a": the two as are separate runs.
    • Empty lines. ["", "", ""] gives " 3 ", a count, a space and nothing after it.
    • Resetting count to 0. After a new run starts, the count is 1, not 0. With 0 every run would be one short.
    • Using ==. Strings are compared with equals.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives " 2 a\n 1 b\n 3 c".
    • [] gives "".
    • ["x"] gives " 1 x".
    • ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a".
    • Twelve copies of "a" give " 12 a".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free