Problem overview
The function uniqCount(lines []string) string builds the -c flag of Unix uniq. Instead of dropping repeated lines, it collapses each run of adjacent equal lines into one output line that shows the run length followed by the text. Each output line is fmt.Sprintf("%7d ", count) + value: the count right-aligned in 7 characters, one space, then the line. The output lines are joined with \n.
For ["a", "a", "b", "c", "c", "c"] there are three runs: two as, one b and three cs. The printed result is:
2 a
1 b
3 c
Approach
The previous version could decide about a line by looking at the last kept line. Counting needs more: while a run is going on, its length keeps growing, and the output line can only be written when the run ends. So the loop carries two pieces of state that describe the current run: prev, the text of the run, and count, how many lines it has so far.
For each line there are two cases:
- The line continues the run. A run exists (
count > 0) and the line equalsprev. Add 1 tocount. - The line starts a new run. The run before it, if any, is over, so write its output line. Then
prevbecomes the new line andcountbecomes 1.
The last run never meets a different line after it, so the loop never writes it. After the loop, one more check writes it.
Note that count, not prev, tells whether a run exists. prev starts as "", and an empty string is also a perfectly valid input line, so comparing against prev alone couldn't distinguish "no run yet" from "a run of empty lines". Keeping the two apart is what makes the loop correct for every input.
Tracing the example
For ["a", "a", "b", "c", "c", "c"], the state after each line is:
| Line | prev | count | Output lines written so far |
|---|---|---|---|
"a" | "a" | 1 | none |
"a" | "a" | 2 | none |
"b" | "b" | 1 | " 2 a" |
"c" | "c" | 1 | " 2 a", " 1 b" |
"c" | "c" | 2 | same two |
"c" | "c" | 3 | same two |
After the loop, prev is "c" and count is 3, and the final check adds " 3 c" as the third output line.
Step by step
- Create the empty
resultslice, which will hold one output line per run. - Start
countat 0. The value 0 means no run has started. - Start
prevas"". It is meaningful only whilecountis above 0. - Loop by position with
for i := 0; i < len(lines); i++. - Check for a continuing run:
count > 0 && lines[i] == prev, with anelsefor the other case. - Continue the run in the
ifbranch withcount++. - Close the old run in the
elsebranch, but only ifcount > 0. Before the first line there is nothing to close. - Format and append the finished run:
fmt.Sprintf("%7d ", count)pads the number on the left to width 7 and the trailing space in the format is part of the output. Addprevwith+. - Start the new run: set
prev = lines[i], - and set
count = 1. - After the loop, test
count > 0again for the run still open, - and append its output line in the same way.
- Join with
"\n"and return.
The solution in Go
func uniqCount(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 > 0 {
result = append(result, fmt.Sprintf("%7d ", count)+prev)
}
prev = lines[i]
count = 1
}
}
if count > 0 {
result = append(result, fmt.Sprintf("%7d ", count)+prev)
}
return strings.Join(result, "\n")
}
Go details to notice:
- Format verbs.
%7dprints an integer in a field at least 7 characters wide, padded with spaces on the left.fmt.Sprintf("%7d ", 2)is" 2 ". A count with more than 7 digits isn't cut: 1234567890 gives"1234567890 ", which is longer than 7 plus the space. Sprintfreturns a string instead of printing, so it can be joined toprevwith+.- The repeated line. The same formatting appears twice: once in the loop and once after it. That duplication is what the steps build.
count++is a statement. It can't be used as a value in an expression.
Complexity
Time: O(n), where n is the total size of the lines. Each line is compared once with prev, and each run is formatted once. Space: O(r), where r is the size of the output: one string per run, and then the joined result.
Edge cases and common mistakes
- Empty list. The loop doesn't run and
countis 0, so nothing is written: the result is"". - Forgetting the final run. Without the check after the loop, the last run is lost. In the example the output would end after
" 1 b"and miss thecline. - Empty lines. An empty string is a legitimate line, so
countand notprevsays whether a run exists. For["", "", "a"]the result is" 2 \n 1 a": the first output line is the count 2, a space, and an empty value. - Closing a run that never started. Without the
count > 0test in theelsebranch, the first line would add an output line with a count of 0. - Repeats that aren't adjacent.
["a", "b", "a"]gives three lines, each with count 1: only neighbours merge. - Long runs. A run of 1,234,567 equal lines gives
"1234567 z"for the valuez, since the seven-character field is exactly filled.
Testing
["a", "a", "b", "c", "c", "c"]gives" 2 a\n 1 b\n 3 c".["", "", "a"]gives" 2 \n 1 a".["a", "b", "a"]gives" 1 a\n 1 b\n 1 a".["x"]gives" 1 x".[]gives"".
