Start learning free

LESSON 20 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in Python: Keep Only Lines That Never Repeat

Practice Read the full explanation

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:

def uniqOnce(self, lines: List[str]) -> str:

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.


Same scaffolding as uniq -d, but the filter flips: flush prev only when count == 1 (a singleton run).

if count == 1:
    result.append(prev)
Flush again AFTER the loop ends.

The full solution:
class Solution:
    def uniqOnce(self, lines):
        result = []
        count = 0
        prev = None
        for line in lines:
            if count > 0 and line == prev:
                count += 1
            else:
                if count == 1:
                    result.append(prev)
                prev = line
                count = 1
        if count == 1:
            result.append(prev)
        return "\n".join(result)

STEP 1 OF 13
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in Python, explained

    Problem overview

    This version of the uniq tool mimics uniq -u. The method uniqOnce receives a list of lines and returns a single string with the lines that did not repeat back to back, joined by "\n".

    The key word is adjacent. A line counts as repeated only when the line right next to it is equal. For ["a", "a", "b", "c", "c", "c"] the function returns "b": the two "a"s and the three "c"s form runs longer than one line, so they are dropped, and the lone "b" survives. The earlier versions of this tool already walked through runs of equal lines; this one keeps a run only when its length is exactly 1.

    Approach: measure each run, keep the runs of length 1

    Because only neighbours matter, there is no need for a dictionary of counts. One pass over the list is enough, as long as the loop remembers two things about the run it is currently in:

    • prev, the text of the run's lines;
    • count, how many lines the run has so far.

    When the next line equals prev, the run grows. When it differs, the run has ended, and that is the moment to decide: if count is 1, the run was a loner and goes into result. Then the new line starts a fresh run with a count of 1.

    The real uniq works on adjacent lines for the same reason: it is meant to run on sorted input, where equal lines are already neighbours. This version does not sort anything. It takes the lines in the order they arrive, so the same text can appear in several separate runs, and each run is judged on its own.

    Notice also that the function never changes lines and never looks backwards at more than one remembered value. The whole history of the loop fits in two variables, which is what makes a single pass possible.

    Step by step

    1. Create result as an empty list, count as 0 (no run has started) and prev as None (no line yet).
    2. Loop over every line. The first condition is count > 0 and line == prev: a run exists and this line continues it. In that case add 1 to count.
    3. Otherwise a different line has arrived and the previous run is over. If its count was exactly 1, append prev to result. On the very first line count is 0, so nothing is appended.
    4. Still in that branch, start the new run: prev = line and count = 1.
    5. After the loop the last run is still open, because no later line came to end it. Repeat the same test, if count == 1, and append prev.
    6. Return "\n".join(result), which puts a newline between lines but not after the last one.

    The solution in Python

    class Solution:
        def uniqOnce(self, lines):
            result = []
            count = 0
            prev = None
            for line in lines:
                if count > 0 and line == prev:
                    count += 1
                else:
                    if count == 1:
                        result.append(prev)
                    prev = line
                    count = 1
            if count == 1:
                result.append(prev)
            return "\n".join(result)
    

    A few details are worth noticing:

    • count > 0 guards the first line: before any run exists, prev is only a placeholder and must not be treated as a run to continue.
    • None is Python's "no value yet" marker. It sits in prev until the first line arrives, and it is never appended, because count is 0 at that point and the test count == 1 fails.
    • The loop only ever tests a run when the next different line shows up, so a run is judged exactly once, at its end.
    • "\n".join(result) returns an empty string for an empty list, so empty input and all-repeated input need no special case.

    Tracing a small input

    For ["a", "a", "b", "a"], this is the state after each line:

    lineprevcountresult
    "a""a"1[]
    "a""a"2[]
    "b""b"1[]
    "a""a"1["b"]

    When the second "a" arrives the run grows to 2. When "b" arrives, that run of two is discarded without being appended. When the last "a" arrives, the run of "b" had length 1, so it is appended. After the loop the final "a" run also has count 1, so it is appended, and the function returns "b\na".

    Complexity

    The loop visits each line once and does constant work per line, so the time is O(n) for n lines (plus the cost of comparing the strings themselves). The extra space is O(n) in the worst case, when no line repeats and result holds them all.

    Edge cases and common mistakes

    Here is what the solution returns for a few inputs:

    linesresult
    ["a", "a", "b", "c", "c", "c"]"b"
    ["a", "b", "a"]"a\nb\na"
    ["a", "b", "b", "c"]"a\nc"
    ["a", "a", "b", "a"]"b\na"
    ["x", "x"]""
    []""

    The second row shows the main trap: "a" appears twice, but not side by side, so both occurrences are separate runs of length 1 and both stay. A solution that counts occurrences over the whole list would drop them. The fourth row shows the same thing in a different order.

    The other classic mistake is forgetting the check after the loop. Without it, the final run is never judged, and a list like ["a", "a", "b"] would lose its last loner "b". Also keep the test as count == 1. A looser test such as count < 2 would also accept 0, the "no run yet" state, and append None on the first line.

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free