Problem overview
This lesson builds a tiny uniq. The method uniq(self, lines) receives a list of strings, drops the lines that repeat the line right before them, and returns the surviving lines joined with newline characters. In each run of equal consecutive lines, only the first one is kept.
For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The final "a" survives because it isn't next to the first run of "a"s. Only consecutive duplicates are removed, so this is not the same as removing every repeated value.
Approach: compare with the last kept line
You don't need to look ahead or remember every line seen. A line is a duplicate exactly when it equals the line just before it, and since duplicates are dropped, the line before it is always the last one kept. So the rule is: keep a line if nothing has been kept yet, or if it differs from the last kept line.
The kept lines go in a list, result. Python writes the last item of a list as result[-1]: a negative index counts from the end.
result = ["a", "b", "c"]
print(result[-1])
print(result[-2])
c
b
On an empty list, result[-1] raises an IndexError, so the check for emptiness has to come first.
Step by step
- Create the empty list
result. The lines arrive one at a time and none has been kept yet. - Loop over
lineswithfor line in lines, in order. - Test
not result or line != result[-1]. The first line has nothing before it, and an emptyresulthas no last item to compare with. That is whynot resultgoes first: when it is true,orstops and never evaluatesresult[-1]. - Append
lineinside theif. A line equal to the one kept just before it never gets here. - Return
"\n".join(result). The text before.joinis the separator, placed between lines only, so the result has no newline after the last line.
The solution in Python
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)
An empty list is false in a condition, so not result is true exactly when nothing has been kept. The or operator is short-circuiting: if its left side is true, the right side is skipped. This is what protects result[-1] from running on an empty list.
The comparison line != result[-1] compares contents, not identity, so two separate strings with the same text count as equal. The empty string is a perfectly ordinary line: ["", "", "x"] gives "\nx", which is the single kept empty line, a newline and then "x".
Complexity
Time is O(n) in the number of lines (times the line length for each string comparison): one pass, with constant work per line. Extra space is O(k) for the k kept lines.
Edge cases and common mistakes
- Checking emptiness second. Writing
line != result[-1] or not resultraisesIndexErroron the first line. - Removing all duplicates. Using a set or
if line not in resultwould drop the last"a"in the example. The comparison is only with the previous line. - Empty input. An empty list returns
"". - A single line.
["a"]returns"a". - Comparing with the previous input line by index also works, but comparing with
result[-1]needs no index arithmetic.
Testing
| lines | result |
|---|---|
["a", "a", "b", "c", "c", "c", "a"] | "a\nb\nc\na" |
[] | "" |
["", "", "x"] | "\nx" |
["a"] | "a" |
The next version builds on this one.
