Start learning free

LESSON 19 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq v3 in Scala: Printing Only Repeated Lines

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

def uniqDups(lines: Array[String]): String

Example:

Input: lines = ["a", "a", "b", "c", "c", "c"]

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


Track prev and count. When the line changes (or after the loop), flush prev only if count > 1. Compare strings with ==, then join the survivors with mkString("\n").

if (count > 1) {
    result += prev
}


The full solution:
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")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Scala, explained

    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 readcountprevValues kept so far
    a1anone
    a2anone
    b1ba
    c1ca
    c2ca
    c3ca

    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

    1. Create the buffer. A val named result holds an empty scala.collection.mutable.ListBuffer[String], a growable list much like ArrayBuffer.
    2. Create count as a var starting at 0.
    3. Create prev as a var starting at "".
    4. Loop over the positions with for (i <- 0 until lines.length).
    5. Branch on count > 0 && lines(i) == prev, with an else.
    6. Continue the run with count += 1 in the if branch.
    7. Check the finished run. In the else branch, an inner if (count > 1) asks whether the run just ended was repeated.
    8. Keep one copy. Inside it, result += prev.
    9. Start the next run with prev = lines(i).
    10. Reset the count with count = 1.
    11. Check the last run after the loop with the same count > 1 test.
    12. Add it with result += prev.
    13. 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.length is a range that stops before lines.length; 1 to n would include n. On an empty array the range is empty and the loop doesn't run.
    • The parameter is an Array[String], so lines(i) reads an element in constant time.
    • The count > 0 guard 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 no return is 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 > 0 for the output test. That would also output the unique lines. It must be count > 1.
    • Forgetting the last run. A repeated run at the end of the input, such as the c run 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 though a appears twice.
    • Empty array. The range 0 until 0 is empty, no run is ever started, and the result is "".

    Testing

    linesResult
    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"
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free