Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.
Each output line is formatted as f"{count:>7} {value}": a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.
Function signature:
def uniqCount(self, lines: List[str]) -> str:
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"]
Output (when printed):
2 a
1 b
3 c
The first run is two "a"s, then a single "b", then three "c"s — three output lines.
Track two pieces of state as you walk the input:
prev (the value of the current run) and count (its length). When you see a NEW value or reach the end, "flush" the previous run by appending f"{count:>7} {prev}" and reset.
Don't forget to flush the LAST run after the loop ends — it doesn't get triggered by the "new value" branch.
if count > 0:
result.append(f"{count:>7} {prev}")
The full solution:
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)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
