Start learning free

LESSON 20 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in Scala: Keeping Only Lines That Don't Repeat

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

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

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track prev and count. When the line changes (or after the loop), flush prev only if count == 1.

if (count == 1) {
    result += prev
}
In Scala, == compares string values directly.

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

STEP 1 OF 13
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in Scala, explained

    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:

    ilineprevcountresult
    0aa1[]
    1aa2[]
    2bb1[]
    3cc1[b]
    4cc2[b]
    5cc3[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

    1. Create result, a growable scala.collection.mutable.ArrayBuffer[String], in a val. You add to the buffer but never replace it, so val is right.
    2. Create var count = 0. Zero means that no run has started yet.
    3. Create var prev: String = null. It is null until the first line arrives, and it needs var because it changes whenever a new run starts.
    4. Loop over every position i of the array.
    5. Inside the loop, test whether a run is going and the current line continues it: count > 0 && lines(i) == prev. If so, add 1 to count.
    6. Otherwise a different line has arrived, so the previous run just ended. If its count was exactly 1, add prev to result. At the very first line count is 0, so nothing is added.
    7. Still in the else branch, start the new run: set prev to lines(i) and count to 1.
    8. After the loop, the last run is still open, because no later line ended it. Run the same count == 1 test once more and add prev if it passes.
    9. 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, so lines(i) == prev does what you want. It is also safe when prev is null, although the count > 0 check means that case never reaches the comparison.
    • i <- 0 until lines.length covers positions 0 up to the last one. until excludes the end, while to would include it and run one position too far.
    • result += prev appends to an ArrayBuffer. The method returns the final expression, and the explicit return is 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, not uniq -u.
    • Empty input. An empty array never enters the loop and count stays 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:

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