Start learning free

LESSON 618 OF 673 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Python: Counting Adjacent Runs of Lines

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as f"{count:>7} {value}": a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track two pieces of state as you walk the input: prev (the value of the current run) and count (its length). When you see a NEW value or reach the end, "flush" the previous run by appending f"{count:>7} {prev}" and reset.

Don't forget to flush the LAST run after the loop ends — it doesn't get triggered by the "new value" branch.
if count > 0:
    result.append(f"{count:>7} {prev}")


The full solution:
class Solution:
    def uniqCount(self, lines):
        result = []
        count = 0
        prev = None
        for line in lines:
            if count > 0 and line == prev:
                count += 1
            else:
                if count > 0:
                    result.append(f"{count:>7} {prev}")
                prev = line
                count = 1
        if count > 0:
            result.append(f"{count:>7} {prev}")
        return "\n".join(result)

STEP 1 OF 13
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Python, explained

    Problem overview

    This version adds the -c flag of uniq. The method uniqCount(self, lines) collapses each run of equal adjacent lines into one output line made of the run's length and the value. Each output line is f"{count:>7} {value}": the count right-aligned in 7 characters, one space, then the line. The output lines are joined with \n.

    For ["a", "a", "b", "c", "c", "c"] there are three runs, so the result, printed, is:

          2 a
          1 b
          3 c
    

    Only adjacent lines form a run. With ["a", "a", "b", "c", "c", "c", "a"] the last "a" starts a new run of length 1, and the output ends with 1 a.

    Approach: track the current run

    Walk through the lines while remembering the run you are in: its value, prev, and its length so far, count. For each line there are two cases:

    • it equals prev, so the run grows and count goes up by one;
    • it differs, so the previous run just ended. Write its output line, then start a new run with this line and a count of 1.

    A run is only written when a different line arrives. The last run never meets a different line, so the loop leaves it unwritten, and it has to be written after the loop. Forgetting that is the classic mistake of this problem.

    Before the first line no run exists. count = 0 means "no run yet", and prev starts as None, Python's value for "nothing". The test count > 0 keeps the code from writing a run that never existed.

    Step by step

    1. Create the empty list result for the output lines, one per run.
    2. Set count = 0. It counts the lines of the current run, and 0 means that no run has started.
    3. Set prev = None. It will hold the value of the current run.
    4. Loop over lines in order.
    5. Test count > 0 and line == prev, with an else below. Both parts are needed to continue a run: one exists, and this line repeats it.
    6. In the if branch, add 1 to count. The run got one line longer.
    7. In the else branch, check count > 0. A different line ended the previous run, but at the very first line there is no run yet, and nothing should be written.
    8. Append the finished run as f"{count:>7} {prev}". In an f-string, :>7 pads the number with spaces on its left up to width 7.
    9. Still in the else, set prev = line. The line that ended the old run is the first line of the new one.
    10. Set count = 1. The new run has one line so far.
    11. After the loop, test count > 0 again. The last run is still open.
    12. Append its output line, built the same way as in the loop.
    13. Return "\n".join(result).

    The solution in Python

    class Solution:
        def uniqCount(self, lines):
            result = []
            count = 0
            prev = None
            for line in lines:
                if count > 0 and line == prev:
                    count += 1
                else:
                    if count > 0:
                        result.append(f"{count:>7} {prev}")
                    prev = line
                    count = 1
            if count > 0:
                result.append(f"{count:>7} {prev}")
            return "\n".join(result)
    

    The format spec >7 means right-aligned in a field of width 7. A count of 5 becomes six spaces and a 5. The width is a minimum: a count with more than 7 digits would simply use all its digits. Combined with the literal space after the field, each output line has the count in its first 7 characters, then a space, then the value.

    The same output line is built twice, once in the loop and once after it, because the last run needs its own flush. The two lines must stay identical.

    For example, uniqCount(["a", "a", "b", "c", "c", "c", "a"]) returns four lines, 2 a, 1 b, 3 c and 1 a, and uniqCount(["x"] * 12) returns " 12 x", with five spaces before the 12.

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

    linecountprevlines written so far
    "a"1"a"none
    "a"2"a"none
    "b"1"b" 2 a
    "c"1"c" 2 a, 1 b
    "c"2"c"same
    "c"3"c"same

    The run of "c"s is still open when the loop ends, with a count of 3 and nothing written for it. The if after the loop writes 3 c, and only then is the output complete. Notice that a run is written at the moment the next different line shows up, and that the line which ends a run is not lost: it becomes prev with a count of 1 on the same pass.

    Tracking prev and count by hand is the general pattern for reading a list in runs. It needs only two variables however long the input is, and it never looks back at earlier lines.

    Complexity

    Time is O(n) in the number of lines, with constant work per line. Extra space is O(r) for the r runs.

    Edge cases and common mistakes

    • Forgetting the last run. Without the if after the loop, the final run is missing from the output.
    • Empty input. The loop never runs and count is 0, so the final if is skipped and the result is "". That is why count > 0 guards both writes.
    • A single line. ["x"] goes through the else branch once (setting prev and count), and the final if writes 1 x.
    • Not resetting count to 1. Setting it to 0 would lose the line that started the new run.
    • Wrong padding. The count is padded to 7 characters before the single space, not after it.

    Testing

    linesresult, printed
    ["a", "a", "b", "c", "c", "c"] 2 a, 1 b, 3 c
    []empty string
    ["x"] * 12 12 x
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free