Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.
Function signature:
def uniqDups(self, lines: List[str]) -> str:
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "a\nc" When printed: a c
The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.
Same scaffolding as
uniq -c: track prev and count, flush when the value changes (or you reach the end). The only difference is the FILTER: only flush if count > 1, and emit just the value (no count).
if count > 1:
result.append(prev)
Don't forget to flush after the loop too.
The full solution:
class Solution:
def uniqDups(self, lines):
result = []
count = 0
prev = None
for line in lines:
if count > 0 and line == prev:
count += 1
else:
if count > 1:
result.append(prev)
prev = line
count = 1
if count > 1:
result.append(prev)
return "\n".join(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
