Problem overview
uniqDups(lines: Array[String]): String is the uniq -d behaviour. It outputs only the values whose run of adjacent equal lines is longer than one, each printed once with no count, joined by \n.
For ["a", "a", "b", "c", "c", "c"] the a run has length 2 and the c run has length 3, so both are kept. The single b is dropped. The result is "a\nc".
Approach
The previous version tracked runs with a count and a prev variable and wrote an output line each time a run ended. This version uses the same machinery and changes only what happens when a run ends. Instead of always writing the run, write it only when its count is greater than 1, and write just the text, once.
The loop works like this. A line that equals prev (while count is above 0) extends the run. Any other line ends the old run: if count > 1 the run was repeated, so append prev to the result. Then the new line starts a run with count = 1.
The test count > 1 handles two situations at once. A run of one line fails it, which is the "unique line is dropped" rule. And at the very first line count is 0, which also fails it, so no phantom entry is written before any run exists, with no separate check needed.
As before, the last run never meets a line that ends it, so the test is repeated once after the loop.
For ["a", "a", "b", "a", "a"] the runs are a (2), b (1) and a (2). The first and last runs are repeated, so a appears twice in the result: "a\na". Equal values that belong to different runs are reported separately, because only adjacency matters.
Following the state
On ["a", "a", "b", "c", "c", "c"] the state after each line is:
| Line read | count | prev | Values kept so far |
|---|---|---|---|
a | 1 | a | none |
a | 2 | a | none |
b | 1 | b | a |
c | 1 | c | a |
c | 2 | c | a |
c | 3 | c | a |
The b run ended with a count of 1, so it was never added. After the loop, the open c run has a count of 3, so c is added and the kept values are a and c.
Step by step
- Create the buffer. A
valnamedresultholds an emptyscala.collection.mutable.ListBuffer[String], a growable list much likeArrayBuffer. - Create
countas avarstarting at 0. - Create
prevas avarstarting at"". - Loop over the positions with
for (i <- 0 until lines.length). - Branch on
count > 0 && lines(i) == prev, with anelse. - Continue the run with
count += 1in theifbranch. - Check the finished run. In the
elsebranch, an innerif (count > 1)asks whether the run just ended was repeated. - Keep one copy. Inside it,
result += prev. - Start the next run with
prev = lines(i). - Reset the count with
count = 1. - Check the last run after the loop with the same
count > 1test. - Add it with
result += prev. - Join and return with
result.mkString("\n").
The solution in Scala
class Solution {
def uniqDups(lines: Array[String]): String = {
val result = scala.collection.mutable.ListBuffer[String]()
var count = 0
var prev = ""
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
}
result.mkString("\n")
}
}
Language details:
0 until lines.lengthis a range that stops beforelines.length;1 to nwould includen. On an empty array the range is empty and the loop doesn't run.- The parameter is an
Array[String], solines(i)reads an element in constant time. - The
count > 0guard in the first test matters when the first line is"": it keeps that line from looking like a continuation of a run that hasn't started. - The last line of the method,
result.mkString("\n"), is the returned value, so noreturnis needed.
ListBuffer or ArrayBuffer
This version uses a ListBuffer, while the earlier ones used an ArrayBuffer. Here the choice makes no practical difference: the code only appends with += and joins at the end, and both buffers support exactly those operations. ListBuffer is built on a linked list, so appending is cheap, but indexing into it would be slow. This function never indexes into the buffer, which is why either type fits. Pick the buffer by what you do with it.
Complexity
The loop makes one pass with constant work per line, so the time is O(n) for n lines (array indexing takes constant time). The buffer holds at most one entry per run that repeats, so the extra space is O(n) in the worst case.
Edge cases and common mistakes
- Using
count > 0for the output test. That would also output the unique lines. It must becount > 1. - Forgetting the last run. A repeated run at the end of the input, such as the
crun above, is only written by the check after the loop. - Adding the text once per extra line. One copy per run is enough, however long it is.
- Merging separate runs.
["a", "b", "a"]has no repeated run, so the result is"", even thoughaappears twice. - Empty array. The range
0 until 0is empty, no run is ever started, and the result is"".
Testing
| lines | Result |
|---|---|
Array("a", "a", "b", "c", "c", "c") | "a\nc" |
Array("a", "b", "a") | "" |
Array() of strings | "" |
Array("a", "a", "b", "a", "a") | "a\na" |
Array("z", "z") | "z" |
