Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).
Function signature:
def uniq(self, lines: List[str]) -> str:
Example:
Input: lines = ["a", "a", "b", "c", "c", "c", "a"] Output: "a\nb\nc\na" When printed: a b c a
Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.
Walk the input list and append a line to the result only if it differs from the previous one you appended. Don't compare against ALL previous lines — only the most recent one in your output.
Use
result[-1] to peek at the last appended line. Always append when the result is empty:
if not result or line != result[-1]:
result.append(line)
The full solution:
class Solution:
def uniq(self, lines):
result = []
for line in lines:
if not result or line != result[-1]:
result.append(line)
return "\n".join(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
