Problem overview
This version adds the -c flag of uniq. The method uniqCount(self, lines) collapses each run of equal adjacent lines into one output line made of the run's length and the value. Each output line is f"{count:>7} {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, so the result, printed, is:
2 a
1 b
3 c
Only adjacent lines form a run. With ["a", "a", "b", "c", "c", "c", "a"] the last "a" starts a new run of length 1, and the output ends with 1 a.
Approach: track the current run
Walk through the lines while remembering the run you are in: its value, prev, and its length so far, count. For each line there are two cases:
- it equals
prev, so the run grows andcountgoes up by one; - it differs, so the previous run just ended. Write its output line, then start a new run with this line and a count of 1.
A run is only written when a different line arrives. The last run never meets a different line, so the loop leaves it unwritten, and it has to be written after the loop. Forgetting that is the classic mistake of this problem.
Before the first line no run exists. count = 0 means "no run yet", and prev starts as None, Python's value for "nothing". The test count > 0 keeps the code from writing a run that never existed.
Step by step
- Create the empty list
resultfor the output lines, one per run. - Set
count = 0. It counts the lines of the current run, and 0 means that no run has started. - Set
prev = None. It will hold the value of the current run. - Loop over
linesin order. - Test
count > 0 and line == prev, with anelsebelow. Both parts are needed to continue a run: one exists, and this line repeats it. - In the
ifbranch, add 1 tocount. The run got one line longer. - In the
elsebranch, checkcount > 0. A different line ended the previous run, but at the very first line there is no run yet, and nothing should be written. - Append the finished run as
f"{count:>7} {prev}". In an f-string,:>7pads the number with spaces on its left up to width 7. - Still in the
else, setprev = line. The line that ended the old run is the first line of the new one. - Set
count = 1. The new run has one line so far. - After the loop, test
count > 0again. The last run is still open. - Append its output line, built the same way as in the loop.
- Return
"\n".join(result).
The solution in Python
class Solution:
def uniqCount(self, lines):
result = []
count = 0
prev = None
for line in lines:
if count > 0 and line == prev:
count += 1
else:
if count > 0:
result.append(f"{count:>7} {prev}")
prev = line
count = 1
if count > 0:
result.append(f"{count:>7} {prev}")
return "\n".join(result)
The format spec >7 means right-aligned in a field of width 7. A count of 5 becomes six spaces and a 5. The width is a minimum: a count with more than 7 digits would simply use all its digits. Combined with the literal space after the field, each output line has the count in its first 7 characters, then a space, then the value.
The same output line is built twice, once in the loop and once after it, because the last run needs its own flush. The two lines must stay identical.
For example, uniqCount(["a", "a", "b", "c", "c", "c", "a"]) returns four lines, 2 a, 1 b, 3 c and 1 a, and uniqCount(["x"] * 12) returns " 12 x", with five spaces before the 12.
Here is the state after each line of ["a", "a", "b", "c", "c", "c"], taken from running the solution with a print added:
| line | count | prev | lines written so far |
|---|---|---|---|
"a" | 1 | "a" | none |
"a" | 2 | "a" | none |
"b" | 1 | "b" | 2 a |
"c" | 1 | "c" | 2 a, 1 b |
"c" | 2 | "c" | same |
"c" | 3 | "c" | same |
The run of "c"s is still open when the loop ends, with a count of 3 and nothing written for it. The if after the loop writes 3 c, and only then is the output complete. Notice that a run is written at the moment the next different line shows up, and that the line which ends a run is not lost: it becomes prev with a count of 1 on the same pass.
Tracking prev and count by hand is the general pattern for reading a list in runs. It needs only two variables however long the input is, and it never looks back at earlier lines.
Complexity
Time is O(n) in the number of lines, with constant work per line. Extra space is O(r) for the r runs.
Edge cases and common mistakes
- Forgetting the last run. Without the
ifafter the loop, the final run is missing from the output. - Empty input. The loop never runs and
countis 0, so the finalifis skipped and the result is"". That is whycount > 0guards both writes. - A single line.
["x"]goes through theelsebranch once (settingprevandcount), and the finalifwrites1 x. - Not resetting
countto 1. Setting it to 0 would lose the line that started the new run. - Wrong padding. The count is padded to 7 characters before the single space, not after it.
Testing
| lines | result, printed |
|---|---|
["a", "a", "b", "c", "c", "c"] | 2 a, 1 b, 3 c |
[] | empty string |
["x"] * 12 | 12 x |
