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
prevand a run is going: the run grows, socountgoes 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
countequal 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
- Create
resultas an empty slice of strings. Lines are appended to it one at a time, which suits a slice. - Create
countat 0. Zero means that no run has started yet. - Create
prevas the empty string. It stands for the text of the current run and means nothing until the first line sets it. - Loop over the positions with
ifrom 0 whilei < len(lines). - Test for a continuing run:
count > 0andlines[i] == prev. The first condition says outright that a run must exist before a line can continue it. Before any line,countis 0, so the first line always opens a run. - In the
ifbranch, add one tocount. - In the
elsebranch, first check whether the run that just ended had length exactly 1. - If so, append
prevtoresultand store the slice thatappendreturns back inresult. - Start the new run: set
prevtolines[i]. - Set
countto 1, since the new run has one line so far. - After the loop, test
count == 1again. This handles the last run, which the loop left open. - Append
previnside that test, the same way as before. - 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:
appendreturns a slice. It may have to allocate a bigger backing array, so you must assign its result:result = append(result, prev). Callingappendwithout storing the answer is a compile error in Go.:=declares and infers the type.count := 0is anint,prev := ""is astring, and[]string{}is an empty, non-nil slice.- Strings compare with
==. It compares contents, solines[i] == previs exactly the "same text" test. - The loop is a three-part
for. Go has nowhile;forcovers every loop. strings.Joinof 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
"".
