Start learning free

LESSON 379 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v1 — Drop Adjacent Duplicates in Go

Practice

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

    Uniq V1 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free