Start learning free

LESSON 20 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Uniq -u in Go: Keep Only Lines That Don't Repeat

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

func uniqOnce(lines []string) string

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track a string named prev and an int named count. When the line changes (or after the loop), flush prev only if count == 1.

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


The full solution:
func uniqOnce(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 V4 in Go, explained

    Problem overview

    This version of the uniq tool mimics uniq -u. The function uniqOnce takes a slice of lines and returns one string holding only the lines that did not repeat back-to-back, joined by "\n" with no newline after the last one.

    The key word is adjacent. A line counts as repeated only when the same text sits right next to itself. For ["a", "a", "b", "c", "c", "c"] there are three runs: two "a"s, one "b" and three "c"s. Only the run of length one survives, so the result is "b". Note that a line is dropped as a whole run: both "a"s disappear, not just the second one.

    Approach: measure each run, keep the runs of length one

    Because only neighbours matter, there is no need for a map or for sorting. One pass is enough if the loop remembers two things about the run it is currently in: the text of the run (prev) and how many lines it has so far (count).

    For each new line there are two cases:

    • It equals prev and a run is going: the run grows, so count goes up by one.
    • It differs: the previous run just ended and its length is final. If that length is exactly 1, its text goes into the result. Then the new line starts a fresh run with count equal to 1.

    A run is only judged when something different arrives after it. The last run never meets a different line, so the loop cannot judge it, and the same test has to run once more after the loop.

    Step by step

    1. Create result as an empty slice of strings. Lines are appended to it one at a time, which suits a slice.
    2. Create count at 0. Zero means that no run has started yet.
    3. Create prev as the empty string. It stands for the text of the current run and means nothing until the first line sets it.
    4. Loop over the positions with i from 0 while i < len(lines).
    5. Test for a continuing run: count > 0 and lines[i] == prev. The first condition says outright that a run must exist before a line can continue it. Before any line, count is 0, so the first line always opens a run.
    6. In the if branch, add one to count.
    7. In the else branch, first check whether the run that just ended had length exactly 1.
    8. If so, append prev to result and store the slice that append returns back in result.
    9. Start the new run: set prev to lines[i].
    10. Set count to 1, since the new run has one line so far.
    11. After the loop, test count == 1 again. This handles the last run, which the loop left open.
    12. Append prev inside that test, the same way as before.
    13. Return strings.Join(result, "\n"), which puts the separator between lines only.

    The solution in Go

    func uniqOnce(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 worth knowing:

    • append returns a slice. It may have to allocate a bigger backing array, so you must assign its result: result = append(result, prev). Calling append without storing the answer is a compile error in Go.
    • := declares and infers the type. count := 0 is an int, prev := "" is a string, and []string{} is an empty, non-nil slice.
    • Strings compare with ==. It compares contents, so lines[i] == prev is exactly the "same text" test.
    • The loop is a three-part for. Go has no while; for covers every loop.
    • strings.Join of an empty slice returns the empty string, so no special case is needed when nothing survives.

    Complexity

    Time: O(n) for n lines. Each line is visited once and compared with prev. Joining the result at the end touches each surviving line once.

    Space: O(n) in the worst case, when no line repeats and every line goes into result. The counters use constant space.

    Edge cases and common mistakes

    • Forgetting the last run. Without the check after the loop, a lone line at the end of the input is never reported, because nothing different ever follows it.
    • Treating "unique" as "seen once overall". Only adjacent repeats count. ["a", "b", "a"] has three runs of length one, so all three stay: the result is "a\nb\na".
    • Dropping only the extra copies. That is plain uniq. Here a line that repeats disappears entirely, so ["a", "a", "a"] gives the empty string.
    • Empty lines are lines. ["", "a"] returns "\na": the empty line survives and the output begins with a newline.

    Testing

    Each pair below was produced by calling uniqOnce with the reference solution:

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