Start learning free

LESSON 388 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v4 — Loners Only in Python

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:

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

    Uniq V4 in Python

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