Start learning free

LESSON 618 OF 671 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v4 — Loners Only

Practice

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

public String uniqOnce(List<String> lines)

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track prev and count. When the line changes (or after the loop), flush prev only if count == 1.

if (count == 1) {
    result.add(prev);
}
Use .equals() to compare strings.

The full solution:
class Solution {
    public String uniqOnce(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