Start learning free

LESSON 619 OF 673 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Python: Printing Only Repeated Lines

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Python, explained

    Problem overview

    This version adds the -d flag of uniq. The method uniqDups(self, lines) returns only the values whose run of adjacent equal lines is longer than one, each printed once, with no count, joined by \n.

    For ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of "a"s has length 2 and the run of "c"s has length 3, so both survive, once each. The lone "b" is dropped. Only adjacent lines count: in ["a", "a", "b", "a", "a"] there are two separate runs of "a", and the result is "a\na".

    Approach: measure each run, keep the long ones

    The structure is the same as for counting runs. Track the current run with prev (its value) and count (its length so far). When a different line arrives, the previous run is finished, and only now do you know its final length. If that length is greater than 1, add the value to the result once.

    As before, the last run never meets a different line, so it has to be checked after the loop. Before the first line, count is 0, which is not above 1 either, so the first line needs no special case: nothing is written for a run that doesn't exist.

    Step by step

    1. Create the empty list result. It will hold one copy of each repeated line.
    2. Set count = 0. It counts the lines of the current run; 0 means none has started.
    3. Set prev = None. It will remember the value the current run is made of.
    4. Loop over lines in order.
    5. Test count > 0 and line == prev, with an else. Both must hold to continue a run.
    6. In the if branch, add 1 to count.
    7. In the else branch, test count > 1. A different line has ended the previous run. A run of length 1 wasn't repeated and is skipped.
    8. Append prev to result. One copy is enough, however long the run was.
    9. Set prev = line after the inner if, still in the else: the line that ended the old run starts the new one.
    10. Set count = 1.
    11. After the loop, test count > 1 again. The last run is still open.
    12. Append prev if it passed, as in the loop.
    13. Return "\n".join(result).

    The solution in Python

    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)
    

    The code never stores the whole run, only its length, so the memory stays small. The value is appended as soon as the run ends and passes the length test.

    The test count > 0 and line == prev is what separates "this line continues the run" from "this line starts a new one". At the first line count is 0, so the condition is false even though prev is None, and the else branch only sets up the first run.

    Here is the state after each line of ["a", "a", "b", "c", "c", "c"], taken from running the solution with a print added:

    linecountprevresult so far
    "a"1"a"[]
    "a"2"a"[]
    "b"1"b"["a"]
    "c"1"c"["a"]
    "c"2"c"["a"]
    "c"3"c"["a"]

    When "b" arrives, the run of "a"s has length 2, so "a" is appended. When the first "c" arrives, the run of "b" has length 1 and is skipped. The run of "c"s is still open when the loop ends, with a count of 3, so the final if appends "c" and the result becomes ["a", "c"].

    One detail is easy to get wrong: what to append. Inside the else branch, line is the new line that ended the run, while prev is the value of the run that just finished. The code appends prev. Appending line would add the wrong value, for example "b" instead of "a" in the trace above. The order of the two statements matters for the same reason: prev = line comes after the append, because it overwrites the value you still need.

    The decision for a run is made exactly once, at the moment it ends, because that is the first time its length is final. The same pattern, with a different test, produces the previous version's counted output; this version only changes what is written and when.

    Complexity

    Time is O(n) in the number of lines, one pass with constant work per line. Extra space is O(d) for the d repeated values in the result.

    Edge cases and common mistakes

    • Forgetting the last run. A repeated line at the end of the list, like the c run above, would be lost without the final if.
    • Using count > 0 instead of count > 1. That would print every run, including the single lines.
    • Appending the line once per repeat. Appending inside the if branch would print "a" again for every extra repetition.
    • No repeats. ["a", "b"] returns "", and so does an empty list.
    • Separate runs of the same value. They each count on their own: ["a", "a", "b", "a", "a"] gives "a\na", and a value that appears twice but never back to back, such as ["a", "b", "a"], isn't a repeat here.

    Testing

    linesresult
    ["a", "a", "b", "c", "c", "c"]"a\nc"
    ["a", "b"]""
    ["a", "b", "b"]"b"
    ["a", "a", "b", "a", "a"]"a\na"
    []""
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free