Start learning free

LESSON 17 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq v1 in Scala: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

def uniq(lines: List[String]): String

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build an ArrayBuffer[String] result and append the current line only if result is empty or the line differs from result(result.length - 1). Then join the survivors with result.mkString("\n").

if (result.isEmpty || lines(i) != result(result.length - 1)) {
    result += lines(i)
}


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

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Scala, explained

    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

    1. Create the buffer. A val named result holds an empty scala.collection.mutable.ArrayBuffer[String], the lines to keep.
    2. Loop over the positions. for (i <- lines.indices) gives i from 0 to the last position, and lines(i) is the line at that position. Scala indexes with parentheses.
    3. Decide whether to keep the line. The if is true when result.isEmpty or when lines(i) differs from the last item, result(result.length - 1).
    4. Keep it. Inside the if, result += lines(i) adds the line to the end of the buffer.
    5. 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.indices is the range 0 until lines.length. On a List, lines(i) walks the list from its head each time, so it takes time proportional to i. For long lists, a for (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 why result.isEmpty comes 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 mkString add the separators.

    Testing

    linesResult
    List("a", "a", "b", "c", "c", "c", "a")"a\nb\nc\na"
    List("a", "b", "a")"a\nb\na"
    Nil""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free