Start learning free

LESSON 18 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Go: Counting Adjacent Runs with fmt.Sprintf

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 fmt.Sprintf("%7d ", count) + value: a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

func uniqCount(lines []string) string

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 prev and count. When a NEW value arrives (or you reach the end), flush the previous run. Use fmt.Sprintf("%7d ", count) to right-align the count, then concat the line.

if count > 0 {
    result = append(result, fmt.Sprintf("%7d ", count)+prev)
}
Don't forget to flush after the loop ends. The strings package provides strings.Join(result, "\n").

The full solution:
func uniqCount(lines []string) string {
    result := []string{}
    count := 0
    prev := ""
    for i := 0; i < len(lines); i++ {
        if count > 0 && lines[i] == prev {
            count++
        } else {
            if count > 0 {
                result = append(result, fmt.Sprintf("%7d ", count)+prev)
            }
            prev = lines[i]
            count = 1
        }
    }
    if count > 0 {
        result = append(result, fmt.Sprintf("%7d ", count)+prev)
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 13
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Go, explained

    Problem overview

    The function uniqCount(lines []string) string builds the -c flag of Unix uniq. Instead of dropping repeated lines, it collapses each run of adjacent equal lines into one output line that shows the run length followed by the text. Each output line is fmt.Sprintf("%7d ", count) + 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: two as, one b and three cs. The printed result is:

          2 a
          1 b
          3 c

    Approach

    The previous version could decide about a line by looking at the last kept line. Counting needs more: while a run is going on, its length keeps growing, and the output line can only be written when the run ends. So the loop carries two pieces of state that describe the current run: prev, the text of the run, and count, how many lines it has so far.

    For each line there are two cases:

    • The line continues the run. A run exists (count > 0) and the line equals prev. Add 1 to count.
    • The line starts a new run. The run before it, if any, is over, so write its output line. Then prev becomes the new line and count becomes 1.

    The last run never meets a different line after it, so the loop never writes it. After the loop, one more check writes it.

    Note that count, not prev, tells whether a run exists. prev starts as "", and an empty string is also a perfectly valid input line, so comparing against prev alone couldn't distinguish "no run yet" from "a run of empty lines". Keeping the two apart is what makes the loop correct for every input.

    Tracing the example

    For ["a", "a", "b", "c", "c", "c"], the state after each line is:

    LineprevcountOutput lines written so far
    "a""a"1none
    "a""a"2none
    "b""b"1" 2 a"
    "c""c"1" 2 a", " 1 b"
    "c""c"2same two
    "c""c"3same two

    After the loop, prev is "c" and count is 3, and the final check adds " 3 c" as the third output line.

    Step by step

    1. Create the empty result slice, which will hold one output line per run.
    2. Start count at 0. The value 0 means no run has started.
    3. Start prev as "". It is meaningful only while count is above 0.
    4. Loop by position with for i := 0; i < len(lines); i++.
    5. Check for a continuing run: count > 0 && lines[i] == prev, with an else for the other case.
    6. Continue the run in the if branch with count++.
    7. Close the old run in the else branch, but only if count > 0. Before the first line there is nothing to close.
    8. Format and append the finished run: fmt.Sprintf("%7d ", count) pads the number on the left to width 7 and the trailing space in the format is part of the output. Add prev with +.
    9. Start the new run: set prev = lines[i],
    10. and set count = 1.
    11. After the loop, test count > 0 again for the run still open,
    12. and append its output line in the same way.
    13. Join with "\n" and return.

    The solution in Go

    func uniqCount(lines []string) string {
        result := []string{}
        count := 0
        prev := ""
        for i := 0; i < len(lines); i++ {
            if count > 0 && lines[i] == prev {
                count++
            } else {
                if count > 0 {
                    result = append(result, fmt.Sprintf("%7d ", count)+prev)
                }
                prev = lines[i]
                count = 1
            }
        }
        if count > 0 {
            result = append(result, fmt.Sprintf("%7d ", count)+prev)
        }
        return strings.Join(result, "\n")
    }
    

    Go details to notice:

    • Format verbs. %7d prints an integer in a field at least 7 characters wide, padded with spaces on the left. fmt.Sprintf("%7d ", 2) is " 2 ". A count with more than 7 digits isn't cut: 1234567890 gives "1234567890 ", which is longer than 7 plus the space.
    • Sprintf returns a string instead of printing, so it can be joined to prev with +.
    • The repeated line. The same formatting appears twice: once in the loop and once after it. That duplication is what the steps build.
    • count++ is a statement. It can't be used as a value in an expression.

    Complexity

    Time: O(n), where n is the total size of the lines. Each line is compared once with prev, and each run is formatted once. Space: O(r), where r is the size of the output: one string per run, and then the joined result.

    Edge cases and common mistakes

    • Empty list. The loop doesn't run and count is 0, so nothing is written: the result is "".
    • Forgetting the final run. Without the check after the loop, the last run is lost. In the example the output would end after " 1 b" and miss the c line.
    • Empty lines. An empty string is a legitimate line, so count and not prev says whether a run exists. For ["", "", "a"] the result is " 2 \n 1 a": the first output line is the count 2, a space, and an empty value.
    • Closing a run that never started. Without the count > 0 test in the else branch, the first line would add an output line with a count of 0.
    • Repeats that aren't adjacent. ["a", "b", "a"] gives three lines, each with count 1: only neighbours merge.
    • Long runs. A run of 1,234,567 equal lines gives "1234567 z" for the value z, since the seven-character field is exactly filled.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives " 2 a\n 1 b\n 3 c".
    • ["", "", "a"] gives " 2 \n 1 a".
    • ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a".
    • ["x"] gives " 1 x".
    • [] gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free