Problem overview
uniq(lines: List[String]): String removes adjacent duplicate lines: in each run of equal consecutive lines only the first is kept. The surviving lines are returned joined by newline characters (\n).
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 repeats are removed, so a line can appear more than once in the output.
Approach
Because only neighbours matter, the function doesn't need a set of lines seen so far. It needs one fact for each line: is it the same as the line that was just kept? The kept lines are collected in order, so "the line before" is simply the last item of the result buffer.
A line is kept when either of these is true:
- the buffer is empty, so this is the first line and has nothing before it;
- the line differs from the last item of the buffer.
The order of the two tests matters. The empty check comes first, and the comparison with the last item is only evaluated when the buffer has one. Scala's || stops at the first true operand, so with an empty buffer the expression result(result.length - 1), which would fail on an empty buffer, never runs.
Comparing against the last kept line works because a kept line is always the first of its run. Within a run, every later line equals it, so each one is rejected.
Tracing ["a", "a", "b", "c", "c", "c", "a"]: the first a is kept because the buffer is empty. The second a equals the last kept line and is dropped. b differs from a and is kept. The first c is kept, the next two are dropped. The last a differs from c and is kept. The buffer ends as a, b, c, a.
Step by step
- Create the buffer. A
valnamedresultholds an emptyscala.collection.mutable.ArrayBuffer[String], the lines to keep. - Loop over the positions.
for (i <- lines.indices)givesifrom 0 to the last position, andlines(i)is the line at that position. Scala indexes with parentheses. - Decide whether to keep the line. The
ifis true whenresult.isEmptyor whenlines(i)differs from the last item,result(result.length - 1). - Keep it. Inside the
if,result += lines(i)adds the line to the end of the buffer. - Join and return with
result.mkString("\n"). The separator goes between lines only, so there is no trailing newline.
The solution in Scala
class Solution {
def uniq(lines: List[String]): String = {
val result = scala.collection.mutable.ArrayBuffer[String]()
for (i <- lines.indices) {
if (result.isEmpty || lines(i) != result(result.length - 1)) {
result += lines(i)
}
}
return result.mkString("\n")
}
}
Details to notice:
lines.indicesis the range0 until lines.length. On aList,lines(i)walks the list from its head each time, so it takes time proportional toi. For long lists, afor (line <- lines)loop that compares with the last kept line would avoid that cost.!=compares string contents in Scala, not references.result(result.length - 1)reads the last item of the buffer. It would throw on an empty buffer, which is whyresult.isEmptycomes first.mkString("\n")returns""for an empty buffer, so an empty list gives an empty string.
Complexity
Every line is compared once with the last kept line, and reading the last item of a buffer takes constant time. The cost of lines(i) on a List grows with i, so this version takes O(n²) time in the worst case for a list of n lines, though the lesson's inputs are small. The buffer holds at most n lines, so the extra space is O(n).
Edge cases and common mistakes
- Removing every duplicate. Only adjacent repeats go.
["a", "b", "a"]stays"a\nb\na". - Swapping the two conditions. Evaluating
result(result.length - 1)on an empty buffer throws an exception. - Empty list. The loop doesn't run and the result is
"". - Trailing newline. Let
mkStringadd the separators.
Testing
| lines | Result |
|---|---|
List("a", "a", "b", "c", "c", "c", "a") | "a\nb\nc\na" |
List("a", "b", "a") | "a\nb\na" |
Nil | "" |
