Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.
Function signature:
def uniqOnce(self, lines: List[str]) -> str:
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "b" When printed: b
The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.
Same scaffolding as
uniq -d, but the filter flips: flush prev only when count == 1 (a singleton run).
if count == 1:
result.append(prev)
Flush again AFTER the loop ends.
The full solution:
class Solution:
def uniqOnce(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
