Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq in Go: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

func uniq(lines []string) string

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build a []string result and append the current line only if result is empty or the line differs from result[len(result)-1]. Then join the survivors with strings.Join(result, "\n").

if len(result) == 0 || lines[i] != result[len(result)-1] {
    result = append(result, lines[i])
}


The full solution:
func uniq(lines []string) string {
    result := []string{}
    for i := 0; i < len(lines); i++ {
        if len(result) == 0 || lines[i] != result[len(result)-1] {
            result = append(result, lines[i])
        }
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 6
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Go, explained

    Problem overview

    The function uniq(lines []string) string is a small version of the Unix uniq command. It removes adjacent duplicate lines, keeping the first line of each consecutive run, and returns the surviving lines joined by newline characters (\n).

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The two as at the start collapse into one, as do the three cs. The final a stays, because it is not next to the first run of as: only neighbours are compared, so a value that comes back later survives.

    Approach

    The word "adjacent" simplifies the problem. A line is a duplicate only if it equals the line right before it, so there is no need to remember every line seen so far, as a set of seen values would do. The question for each line is whether it equals the previous kept line.

    The kept lines are being collected in result anyway, so the previous kept line is simply the last element of result. Comparing with the last kept line is the same as comparing with the previous input line, because a line that was dropped equals the line that was kept before it. For example, in ["x", "x", "x"], the second and third lines are both compared with the single "x" in result.

    The first line is a special case: result is empty, so there is no last element to compare with. The condition handles that by checking emptiness first.

    Step by step

    1. Write the function, taking a []string named lines and returning a string.
    2. Create an empty result slice with []string{}. It collects the lines to keep, and it grows as lines are appended.
    3. Loop by position with for i := 0; i < len(lines); i++.
    4. Decide whether to keep the line. Keep it if len(result) == 0 or lines[i] != result[len(result)-1]. Go has no isEmpty, so emptiness is len(result) == 0, and the last element sits at index len(result) - 1.
    5. Append the kept line and store what append returns back in result.
    6. Join and return. strings.Join(result, "\n") puts the separator between lines only, so the output has no trailing newline.

    The solution in Go

    func uniq(lines []string) string {
        result := []string{}
        for i := 0; i < len(lines); i++ {
            if len(result) == 0 || lines[i] != result[len(result)-1] {
                result = append(result, lines[i])
            }
        }
        return strings.Join(result, "\n")
    }
    

    Why the condition is written this way:

    • Short-circuit evaluation. In a || b, Go evaluates b only when a is false. When result is empty, len(result) == 0 is true and the right side never runs, so the program never evaluates result[-1]. Swapping the two operands would index an empty slice on the first line and panic at run time.
    • Strings compare by content. != on two strings compares their text, not their addresses.
    • Appending to a slice. append may reallocate when the underlying array is full and returns the new slice, which is why the result is assigned back to result.

    Complexity

    Time: O(n), where n is the total size of the input. Each line is compared with one other line, and appending is amortised constant time. Space: O(n) in the worst case, when no line repeats and result holds them all, plus the final joined string.

    Edge cases and common mistakes

    • Empty list. The loop doesn't run, and joining an empty slice gives "".
    • One line. ["x"] returns "x".
    • Non-adjacent repeats. ["b", "a", "b"] returns "b\na\nb": both bs stay. This command is not the same as removing every duplicate, which would need a set or a sort first.
    • Empty lines are lines. ["", "", "a"] returns "\na": the two empty lines collapse into one, which is kept, and it shows up as an empty first line in the output.
    • Case counts. ["a", "A"] returns "a\nA", because the strings differ.
    • Putting the checks in the wrong order. lines[i] != result[len(result)-1] || len(result) == 0 panics on the first line, as above.

    Testing

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