Start learning free

LESSON 19 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Go: 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:

func uniqDups(lines []string) string

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.


Track prev and count. When the line changes (or after the loop), flush prev only if count > 1. After collecting the survivors, join them with "\n" using strings.Join.

if count > 1 {
    result = append(result, prev)
}


The full solution:
func uniqDups(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 > 1 {
                result = append(result, prev)
            }
            prev = lines[i]
            count = 1
        }
    }
    if count > 1 {
        result = append(result, prev)
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 13
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Go, explained

    Problem overview

    The function uniqDups(lines []string) string is the -d flag of Unix uniq. It outputs only the lines that repeat back to back: a value is printed, once, if its run of adjacent equal lines is longer than one. The output lines are joined by \n, with no counts.

    For ["a", "a", "b", "c", "c", "c"], the run of as has length 2 and the run of cs has length 3, so both are printed once, while the single b is dropped. The result is "a\nc".

    Approach

    The structure comes from the run-counting version: prev holds the text of the current run and count its length so far. The difference is what happens when a run ends. Instead of formatting a line with its count, the loop asks one question: was the run repeated, that is, is count above 1? If so, prev is appended once, however long the run was.

    A run can only be judged when it is over, and the last run has no line after it to end it. So the same test is repeated after the loop for the run that is still open.

    Tracing a longer input

    Take ["a", "b", "b", "b", "c", "c", "d"]. The loop holds prev and count for the current run and appends a value when the next different line arrives:

    Lineprev aftercount afterresult after
    "a""a"1empty
    "b""b"1empty (the run of a had length 1)
    "b""b"2empty
    "b""b"3empty
    "c""c"1["b"]
    "c""c"2["b"]
    "d""d"1["b", "c"]

    After the loop the open run is d with count 1, which is not above 1, so nothing more is added. The result is "b\nc".

    Step by step

    1. Create the empty result slice for one copy of each repeated value.
    2. Start count at 0, meaning no run has started,
    3. and prev as "", the text of the current run.
    4. Loop by position with for i := 0; i < len(lines); i++.
    5. Check for a continuing run with count > 0 && lines[i] == prev, and write the else branch.
    6. Extend the run in the if branch: count++.
    7. In the else branch, test the run that just ended: count > 1 means it repeated. At the first line, count is 0, so the test fails and nothing is written for a run that doesn't exist.
    8. Append prev once inside that test.
    9. Start the new run: prev = lines[i]
    10. and count = 1.
    11. After the loop, test count > 1 for the run left open,
    12. and append prev if it passes.
    13. Join with "\n" and return.

    The solution in Go

    func uniqDups(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 > 1 {
                    result = append(result, prev)
                }
                prev = lines[i]
                count = 1
            }
        }
        if count > 1 {
            result = append(result, prev)
        }
        return strings.Join(result, "\n")
    }
    

    Go details to notice:

    • The test is count > 1, not count > 0. Using 0 would print every run, which is the behaviour of the first version. The number 1 is what separates a single line from a repeat.
    • One copy per run. The code appends prev only when the run ends, not each time count grows, so a run of 3 appears once.
    • Variables set by := live through the whole function. count and prev are declared before the loop, which is why the check after the loop can still read them.
    • Empty slice. strings.Join of an empty slice is "", so a result without duplicates needs no special case.

    The same loop can answer related questions by changing only the test on count. With count > 0 every run is written, and with count > 1 only repeated runs are. The loop keeps track of run boundaries, and the test decides which runs matter. Whichever test is used, it has to be written twice, once for the run that a different line ends and once for the run that the end of the input ends, and the two copies must agree.

    Complexity

    Time: O(n), where n is the total size of the input: one comparison per line. Space: O(d), where d is the size of the output: one string per repeated run, and the joined result.

    Edge cases and common mistakes

    • No repeats. ["x", "y"] returns "".
    • Empty list. The result is "".
    • Repeats that are not adjacent. For ["a", "b", "a", "a"], the first a is a run of one, and only the last two as form a run of two, so the result is "a". A run is printed once per run, so a value that repeats in several separate places is printed once for each: ["a", "a", "b", "b", "a", "a"] gives "a\nb\na".
    • Forgetting the run at the end. For ["q", "q"] the loop never sees a different line, so without the final test the result would be "" instead of "q".
    • Empty lines. They repeat like any other text. In ["", "", "a"] the run of two empty lines is a repeat, so an empty string is appended, and joining a slice with one empty string gives "", the same as when nothing repeats.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives "a\nc".
    • ["a", "b", "a", "a"] gives "a".
    • ["a", "a", "b", "b", "a", "a"] gives "a\nb\na".
    • ["q", "q"] gives "q".
    • ["x", "y"] gives "".
    • ["a", "b", "b", "b", "c", "c", "d"] gives "b\nc".
    • [] 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