Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq in Python: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Python, explained

    Problem overview

    This lesson builds a tiny uniq. The method uniq(self, lines) receives a list of strings, drops the lines that repeat the line right before them, and returns the surviving lines joined with newline characters. In each run of equal consecutive lines, only the first one is kept.

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The final "a" survives because it isn't next to the first run of "a"s. Only consecutive duplicates are removed, so this is not the same as removing every repeated value.

    Approach: compare with the last kept line

    You don't need to look ahead or remember every line seen. A line is a duplicate exactly when it equals the line just before it, and since duplicates are dropped, the line before it is always the last one kept. So the rule is: keep a line if nothing has been kept yet, or if it differs from the last kept line.

    The kept lines go in a list, result. Python writes the last item of a list as result[-1]: a negative index counts from the end.

    result = ["a", "b", "c"]
    print(result[-1])
    print(result[-2])
    
    c
    b
    

    On an empty list, result[-1] raises an IndexError, so the check for emptiness has to come first.

    Step by step

    1. Create the empty list result. The lines arrive one at a time and none has been kept yet.
    2. Loop over lines with for line in lines, in order.
    3. Test not result or line != result[-1]. The first line has nothing before it, and an empty result has no last item to compare with. That is why not result goes first: when it is true, or stops and never evaluates result[-1].
    4. Append line inside the if. A line equal to the one kept just before it never gets here.
    5. Return "\n".join(result). The text before .join is the separator, placed between lines only, so the result has no newline after the last line.

    The solution in Python

    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)
    

    An empty list is false in a condition, so not result is true exactly when nothing has been kept. The or operator is short-circuiting: if its left side is true, the right side is skipped. This is what protects result[-1] from running on an empty list.

    The comparison line != result[-1] compares contents, not identity, so two separate strings with the same text count as equal. The empty string is a perfectly ordinary line: ["", "", "x"] gives "\nx", which is the single kept empty line, a newline and then "x".

    Complexity

    Time is O(n) in the number of lines (times the line length for each string comparison): one pass, with constant work per line. Extra space is O(k) for the k kept lines.

    Edge cases and common mistakes

    • Checking emptiness second. Writing line != result[-1] or not result raises IndexError on the first line.
    • Removing all duplicates. Using a set or if line not in result would drop the last "a" in the example. The comparison is only with the previous line.
    • Empty input. An empty list returns "".
    • A single line. ["a"] returns "a".
    • Comparing with the previous input line by index also works, but comparing with result[-1] needs no index arithmetic.

    Testing

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

    The next version builds on this one.

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