Start learning free

LESSON 385 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v1 — Drop Adjacent Duplicates in Python

Practice

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Walk the input list and append a line to the result only if it differs from the previous one you appended. Don't compare against ALL previous lines — only the most recent one in your output.

Use result[-1] to peek at the last appended line. Always append when the result is empty:
if not result or line != result[-1]:
    result.append(line)


The full solution:
class Solution:
    def uniq(self, lines):
        result = []
        for line in lines:
            if not result or line != result[-1]:
                result.append(line)
        return "\n".join(result)

STEP 1 OF 5
    Ctrl + Enter to check

    Uniq V1 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