Start learning free

LESSON 387 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v3 — Duplicates Only in Python

Practice

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:

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

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.


Same scaffolding as uniq -c: track prev and count, flush when the value changes (or you reach the end). The only difference is the FILTER: only flush if count > 1, and emit just the value (no count).

if count > 1:
    result.append(prev)
Don't forget to flush after the loop too.

The full solution:
class Solution:
    def uniqDups(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 V3 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