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")
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
