Problem overview
This is the fourth version of the uniq project, the one that behaves like uniq -u. The method uniqOnce(lines: Array[String]): String receives an array of lines and returns the lines that have no identical neighbour, joined by \n.
The word that matters is adjacent. A line is dropped only when it repeats right next to itself. For ["a", "a", "b", "c", "c", "c"] the two "a" lines form a run of length 2 and the three "c" lines a run of length 3, so both runs disappear. The single "b" is a run of length 1, so the result is "b". The rule to implement is that a run survives only when its length is exactly 1.
Approach: measure each run as you walk
You don't need a map of counts. Counting occurrences over the whole array would give the wrong answer here: in ["a", "b", "a"] the line "a" appears twice, but never twice in a row, so both copies survive.
Instead, make one pass and remember two things about the run you are in: prev, the line the run is made of, and count, how many lines it has so far. When the next line equals prev, the run grows. When it differs, the run is over, and you know its final length, so you decide there whether to keep it. This is a single pass, so it takes time proportional to the number of lines.
Tracing the example
For ["a", "a", "b", "c", "c", "c"], here is the state after each pass through the loop body:
| i | line | prev | count | result |
|---|---|---|---|---|
| 0 | a | a | 1 | [] |
| 1 | a | a | 2 | [] |
| 2 | b | b | 1 | [] |
| 3 | c | c | 1 | [b] |
| 4 | c | c | 2 | [b] |
| 5 | c | c | 3 | [b] |
At i = 2 the run of a ends with count equal to 2, so it is not added. At i = 3 the run of b ends with count equal to 1, so b goes into result. After the loop, count is 3 for the final run of c, so the closing test adds nothing, and the joined result is "b". Notice that b is only added when c arrives. That delay is why the closing test is needed for the last run.
Step by step
- Create
result, a growablescala.collection.mutable.ArrayBuffer[String], in aval. You add to the buffer but never replace it, sovalis right. - Create
var count = 0. Zero means that no run has started yet. - Create
var prev: String = null. It isnulluntil the first line arrives, and it needsvarbecause it changes whenever a new run starts. - Loop over every position
iof the array. - Inside the loop, test whether a run is going and the current line continues it:
count > 0 && lines(i) == prev. If so, add 1 tocount. - Otherwise a different line has arrived, so the previous run just ended. If its
countwas exactly 1, addprevtoresult. At the very first linecountis 0, so nothing is added. - Still in the
elsebranch, start the new run: setprevtolines(i)andcountto 1. - After the loop, the last run is still open, because no later line ended it. Run the same
count == 1test once more and addprevif it passes. - Return
result.mkString("\n"), which puts a newline between lines but not after the last one.
The solution in Scala
class Solution {
def uniqOnce(lines: Array[String]): String = {
val result = scala.collection.mutable.ArrayBuffer[String]()
var count = 0
var prev: String = null
for (i <- 0 until lines.length) {
if (count > 0 && lines(i) == prev) {
count += 1
} else {
if (count == 1) {
result += prev
}
prev = lines(i)
count = 1
}
}
if (count == 1) {
result += prev
}
return result.mkString("\n")
}
}
A few Scala details are worth knowing:
lines(i)uses parentheses: indexing an array is a method call in Scala, not square brackets.==compares strings by content, solines(i) == prevdoes what you want. It is also safe whenprevisnull, although thecount > 0check means that case never reaches the comparison.i <- 0 until lines.lengthcovers positions 0 up to the last one.untilexcludes the end, whiletowould include it and run one position too far.result += prevappends to anArrayBuffer. The method returns the final expression, and the explicitreturnis allowed but not needed in Scala.
Complexity
Time is O(n) for n lines: each line is visited once, and each comparison is of two strings. Extra space is O(n) in the worst case, when no line repeats and every line goes into result.
Edge cases and common mistakes
- Forgetting the last run. Without the check after the loop,
["a", "b"]would lose"b", because nothing comes after it to end its run. The test after the loop is the fix. - Counting non-adjacent repeats. The lines
["a", "b", "a"]give"a\nb\na", since no run is longer than 1. - Long runs. A run of any length above 1 is dropped completely, not shortened to one copy. That would be plain
uniq, notuniq -u. - Empty input. An empty array never enters the loop and
countstays 0, so the result is the empty string.
Testing
Try these inputs in the editor above. The results were produced by this solution, shown with the newline written as \n:
| lines | result |
|---|---|
["a", "a", "b", "c", "c", "c"] | "b" |
["a", "b", "a"] | "a\nb\na" |
["a", "a", "b", "c"] | "b\nc" |
["x", "y", "y", "z", "z", "z", "w"] | "x\nw" |
["a", "a"] | "" |
["a", "a", "a", "b", "a", "a"] | "b" |
[] | "" |
