Start learning free

LESSON 18 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq v2 in Scala: Counting Adjacent Runs with format

Practice Read the full explanation

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as "%7d %s".format(count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track var prev and var count. When a NEW value comes in (or you reach end), flush the previous run with "%7d %s".format(count, prev) and reset.

Don't forget to flush AFTER the loop too. Use == for the string comparison.
if (count > 0 && lines(i) == prev) {
    count += 1
} else {
    if (count > 0) {
        result += "%7d %s".format(count, prev)
    }
    prev = lines(i)
    count = 1
}


The full solution:
class Solution {
    def uniqCount(lines: List[String]): String = {
        val result = scala.collection.mutable.ArrayBuffer[String]()
        var count = 0
        var prev = ""
        for (i <- lines.indices) {
            if (count > 0 && lines(i) == prev) {
                count += 1
            } else {
                if (count > 0) {
                    result += "%7d %s".format(count, prev)
                }
                prev = lines(i)
                count = 1
            }
        }
        if (count > 0) {
            result += "%7d %s".format(count, prev)
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Scala, explained

    Problem overview

    uniqCount(lines: List[String]): String collapses each run of adjacent equal lines into one output line showing the run's length and the text. Each output line is "%7d %s".format(count, value): the count right-aligned in 7 characters, one space, then the line. The output lines are joined by \n.

    For ["a", "a", "b", "c", "c", "c"] there are three runs: two as, one b and three cs. Printed, the result is:

          2 a
          1 b
          3 c
    

    Version 1 only had to decide whether to keep a line. Now the function must also know how long each run is, so it tracks the run it is currently in.

    Approach

    Keep two pieces of state that describe the current run: prev, the line the run is made of, and count, how many lines it has so far. A count of 0 means no run has started yet. For each line there are two cases:

    • The line equals prev and a run is going: the run grows, so add 1 to count.
    • Otherwise a different line has arrived. The old run is over, so write its output line (if there was a run), then start a new run with this line and a count of 1.

    The test count > 0 && lines(i) == prev includes the count > 0 check for a reason. prev starts as the empty string, and without that check a first line that is itself "" would look like a continuation of a run that doesn't exist. With count at 0 the first line always goes to the else branch and starts a run.

    A run is written only when the next, different line arrives. The last run has no next line, so the loop never writes it. That is why the same output step appears once more after the loop, again guarded by count > 0, which also keeps an empty list from producing a line.

    Following the state

    On the example, the state after each line is:

    Line readcountprevOutput lines written so far
    a1a0
    a2a0
    b1b1
    c1c2
    c2c2
    c3c2

    After the loop two lines are written and the run of three cs is still open, with count at 3. The final step writes it as the third line.

    Step by step

    1. Create the buffer result, a val holding an ArrayBuffer[String], one entry for each finished run.
    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 <- lines.indices).
    5. Branch on count > 0 && lines(i) == prev, with an else.
    6. Continue the run. In the if branch, count += 1.
    7. Close the old run. In the else branch, an inner if (count > 0) guards the first line, when no run exists yet.
    8. Write the run. Inside it, append "%7d %s".format(count, prev) to result.
    9. Start the new run. Still in the else, set prev = lines(i).
    10. Set count = 1, because the new run has one line so far.
    11. Flush the last run. After the loop, repeat the count > 0 test, since the loop has not written it.
    12. Write it with the same format call.
    13. Join and return with result.mkString("\n").

    The solution in Scala

    class Solution {
        def uniqCount(lines: List[String]): String = {
            val result = scala.collection.mutable.ArrayBuffer[String]()
            var count = 0
            var prev = ""
            for (i <- lines.indices) {
                if (count > 0 && lines(i) == prev) {
                    count += 1
                } else {
                    if (count > 0) {
                        result += "%7d %s".format(count, prev)
                    }
                    prev = lines(i)
                    count = 1
                }
            }
            if (count > 0) {
                result += "%7d %s".format(count, prev)
            }
            return result.mkString("\n")
        }
    }
    

    Language details:

    • "%7d %s".format(count, prev) is the string's format method. %7d writes an integer padded with spaces on the left to a width of 7, and %s inserts the text. A count of 2 gives six spaces and the digit, then a space and the line.
    • The width is a minimum, not a limit: "%7d %s".format(12345678, "big") gives "12345678 big", which is wider than 7 characters.
    • count and prev change as the loop runs, so they are vars; result is a val because only its contents change.
    • == compares string contents.

    Complexity

    Each line is compared once with prev. Indexing a List with lines(i) costs time proportional to i, so the loop takes O(n²) time in the worst case on a long list, though the lesson's inputs are small. The buffer holds one entry per run, so the extra space is O(n) in the worst case, when no two neighbours are equal.

    Edge cases and common mistakes

    • Forgetting the last run. It is written only when a different line follows, so the code after the loop is required. Without it the output would miss the final run.
    • Writing a phantom run at the start. Without the count > 0 guard in the else branch, the first line would write a run of 0 lines.
    • Setting count to 0 for a new run. The new run already has its first line, so it starts at 1.
    • Empty list. The loop doesn't run, count stays 0, and the result is "".
    • Empty lines. A list of three "" lines gives one run: " 3 ", with a space after the count and nothing after it.

    Testing

    linesResult
    List("a", "a", "b", "c", "c", "c")" 2 a\n 1 b\n 3 c"
    Nil""
    List("", "", "")" 3 "
    ten "x" lines followed by one "y"" 10 x\n 1 y"
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free