Problem overview
uniqCount(lines: List[String]): String collapses each run of adjacent equal lines into one output line showing the run's length and the text. Each output line is "%7d %s".format(count, value): the count right-aligned in 7 characters, one space, then the line. The output lines are joined by \n.
For ["a", "a", "b", "c", "c", "c"] there are three runs: two as, one b and three cs. Printed, the result is:
2 a
1 b
3 c
Version 1 only had to decide whether to keep a line. Now the function must also know how long each run is, so it tracks the run it is currently in.
Approach
Keep two pieces of state that describe the current run: prev, the line the run is made of, and count, how many lines it has so far. A count of 0 means no run has started yet. For each line there are two cases:
- The line equals
prevand a run is going: the run grows, so add 1 tocount. - Otherwise a different line has arrived. The old run is over, so write its output line (if there was a run), then start a new run with this line and a count of 1.
The test count > 0 && lines(i) == prev includes the count > 0 check for a reason. prev starts as the empty string, and without that check a first line that is itself "" would look like a continuation of a run that doesn't exist. With count at 0 the first line always goes to the else branch and starts a run.
A run is written only when the next, different line arrives. The last run has no next line, so the loop never writes it. That is why the same output step appears once more after the loop, again guarded by count > 0, which also keeps an empty list from producing a line.
Following the state
On the example, the state after each line is:
| Line read | count | prev | Output lines written so far |
|---|---|---|---|
a | 1 | a | 0 |
a | 2 | a | 0 |
b | 1 | b | 1 |
c | 1 | c | 2 |
c | 2 | c | 2 |
c | 3 | c | 2 |
After the loop two lines are written and the run of three cs is still open, with count at 3. The final step writes it as the third line.
Step by step
- Create the buffer
result, avalholding anArrayBuffer[String], one entry for each finished run. - Create
countas avarstarting at 0. - Create
prevas avarstarting at"". - Loop over the positions with
for (i <- lines.indices). - Branch on
count > 0 && lines(i) == prev, with anelse. - Continue the run. In the
ifbranch,count += 1. - Close the old run. In the
elsebranch, an innerif (count > 0)guards the first line, when no run exists yet. - Write the run. Inside it, append
"%7d %s".format(count, prev)toresult. - Start the new run. Still in the
else, setprev = lines(i). - Set
count = 1, because the new run has one line so far. - Flush the last run. After the loop, repeat the
count > 0test, since the loop has not written it. - Write it with the same
formatcall. - Join and return with
result.mkString("\n").
The solution in Scala
class Solution {
def uniqCount(lines: List[String]): String = {
val result = scala.collection.mutable.ArrayBuffer[String]()
var count = 0
var prev = ""
for (i <- lines.indices) {
if (count > 0 && lines(i) == prev) {
count += 1
} else {
if (count > 0) {
result += "%7d %s".format(count, prev)
}
prev = lines(i)
count = 1
}
}
if (count > 0) {
result += "%7d %s".format(count, prev)
}
return result.mkString("\n")
}
}
Language details:
"%7d %s".format(count, prev)is the string'sformatmethod.%7dwrites an integer padded with spaces on the left to a width of 7, and%sinserts the text. A count of 2 gives six spaces and the digit, then a space and the line.- The width is a minimum, not a limit:
"%7d %s".format(12345678, "big")gives"12345678 big", which is wider than 7 characters. countandprevchange as the loop runs, so they arevars;resultis avalbecause only its contents change.==compares string contents.
Complexity
Each line is compared once with prev. Indexing a List with lines(i) costs time proportional to i, so the loop takes O(n²) time in the worst case on a long list, though the lesson's inputs are small. The buffer holds one entry per run, so the extra space is O(n) in the worst case, when no two neighbours are equal.
Edge cases and common mistakes
- Forgetting the last run. It is written only when a different line follows, so the code after the loop is required. Without it the output would miss the final run.
- Writing a phantom run at the start. Without the
count > 0guard in theelsebranch, the first line would write a run of 0 lines. - Setting
countto 0 for a new run. The new run already has its first line, so it starts at 1. - Empty list. The loop doesn't run,
countstays 0, and the result is"". - Empty lines. A list of three
""lines gives one run:" 3 ", with a space after the count and nothing after it.
Testing
| lines | Result |
|---|---|
List("a", "a", "b", "c", "c", "c") | " 2 a\n 1 b\n 3 c" |
Nil | "" |
List("", "", "") | " 3 " |
ten "x" lines followed by one "y" | " 10 x\n 1 y" |
