Problem overview
This version builds the -c flag of uniq. The function uniqCount(lines: List<String>): String collapses each run of adjacent equal lines into one output line that shows the run's length and then the value. Each output line is "%7d %s".format(count, value): the count right-aligned in 7 characters, one space, then the text. The output lines are joined by \n.
For lines = ["a", "a", "b", "c", "c", "c"] the output, when printed, is:
2 a
1 b
3 c
There are three runs, so there are three output lines. The previous version only dropped duplicates. This one also has to remember how long each run was.
Approach: track the current run
Two variables describe the run the loop is in: prev, the text of the run, and count, how many lines it has so far. For each line there are two cases:
- The line equals
prevand a run exists: the run continues, socountgrows by 1. - Otherwise a different line has arrived: the old run is over, so you write its output line (if there was one), then start a new run with this line and a count of 1.
A run is only written when the next, different line arrives, so the last run has no line after it to trigger the write. After the loop you have to write it yourself. Forgetting this is the classic bug in this kind of code: everything works except the final group is silently missing.
Step by step
- Create the result list in a
valnamedresult. It gets one output line for each run. - Start the count at 0. A
varnamedcountholds the length of the current run, and 0 means that no run has started. - Start
prevas nothing. Avarnamedprev, typedString?and set tonull, remembers the text of the current run. The?lets it hold text or nothing yet. - Loop by position with
for (i in lines.indices), and close the brace right away. - Continue or end the run. An
ifcheckscount > 0 && lines[i] == prev, with anelsebeside it. Both conditions must hold for a run to continue: one exists, and this line repeats it. - Extend the run. In the
ifbranch,count++adds 1. - Close the old run. In the
elsebranch, a nestedifcheckscount > 0. Before the first line no run exists, so nothing is written for it. - Write its output line. Inside the nested
if,result.add("%7d %s".format(count, prev)). The%7dpads the number with spaces on the left up to width 7, and%sinserts the text. - Start the next run. Still in the
elsebranch, setprev = lines[i]. The line that ended the old run begins the new one. - Give it a count of 1.
count = 1, because the new run has one line so far. - Test for an open run after the loop. Repeat the
count > 0check outside the loop. The last run is still open. - Write the last run with the same
result.addcall as inside the loop. - Join and return with
result.joinToString("\n").
The solution in Kotlin
class Solution {
fun uniqCount(lines: List<String>): String {
val result = mutableListOf<String>()
var count = 0
var prev: String? = null
for (i in lines.indices) {
if (count > 0 && lines[i] == prev) {
count++
} else {
if (count > 0) {
result.add("%7d %s".format(count, prev))
}
prev = lines[i]
count = 1
}
}
if (count > 0) {
result.add("%7d %s".format(count, prev))
}
return result.joinToString("\n")
}
}
Kotlin details to know:
String?is a nullable type, andprevstarts asnull. Comparing with==is safe for nullable values:lines[i] == previs justfalsewhenprevisnull. That is whycount > 0is checked as well, so the meaning is clear."%7d %s".format(count, prev)uses Java-style format specifiers.%7dpads with spaces to width 7, so3becomes six spaces and3. If the count needs more than 7 digits, the number simply prints in full and the line gets longer. Printing"%7d|".format(12345678)gives12345678|.%saccepts aString?. Ifprevwere stillnull, it would print the wordnull. In this code the format calls only run whencount > 0, which meansprevhas been set.count++is a statement here. It adds 1 to avar.
Complexity
One pass visits each line once, so the time is O(n) string comparisons, and the result list holds one string per run, which is at most n, so the space is O(n).
Edge cases and common mistakes
- Forgetting the last run. Without the block after the loop,
["a", "a", "b"]would lose itsb. - Empty input. The loop never runs,
countstays 0, nothing is added, and the result is the empty string. - Writing a run before the first line. The
count > 0test in theelsebranch prevents an output line for a run that doesn't exist yet. - Empty lines are values.
["", "", "x"]gives a count of 2 for the empty line, followed by the empty text, so that line ends with the separating space. The next line is1 x. - Non-adjacent repeats.
["a", "b", "a"]gives three runs of 1, since the twoalines aren't neighbours. - Forgetting to reset
countto 1. A new run would continue the old number.
Testing
These results come from running the reference solution. The count is padded to width 7:
lines = ["a", "b", "a"]
1 a
1 b
1 a
lines = ["", "", "x"]
2
1 x
A list of twelve "z" lines gives one output line, 12 z, and an empty list gives the empty string.
