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
- Write the function, taking a
[]stringnamedlinesand returning astring. - Create an empty
resultslice with[]string{}. It collects the lines to keep, and it grows as lines are appended. - Loop by position with
for i := 0; i < len(lines); i++. - Decide whether to keep the line. Keep it if
len(result) == 0orlines[i] != result[len(result)-1]. Go has noisEmpty, so emptiness islen(result) == 0, and the last element sits at indexlen(result) - 1. - Append the kept line and store what
appendreturns back inresult. - 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 evaluatesbonly whenais false. Whenresultis empty,len(result) == 0is true and the right side never runs, so the program never evaluatesresult[-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.
appendmay reallocate when the underlying array is full and returns the new slice, which is why the result is assigned back toresult.
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": bothbs 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) == 0panics 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"".
