Start learning free

LESSON 28 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in Scala: Squeezing Repeated Characters (tr -s)

Practice Read the full explanation

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

def trSqueeze(lines: List[String], chars: String): String

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Build a Set of the squeeze characters with chars.toSet. Walk each line tracking prev (the last char you kept); keep the current char unless it's in the set AND equals prev.

The full solution:
class Solution {
    def trSqueeze(lines: List[String], chars: String): String = {
        val squeeze = chars.toSet
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            val sb = new StringBuilder()
            var prev = '\u0000'
            for (ch <- line) {
                if (!squeeze.contains(ch) || ch != prev) {
                    sb.append(ch)
                    prev = ch
                }
            }
            result += sb.toString()
        }
        result.mkString("\n")
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Scala, explained

    Problem overview

    Version 4 of the tr project behaves like tr -s. The method trSqueeze(lines: List[String], chars: String): String collapses each run of the same character into a single occurrence, but only for characters that appear in chars. Other characters, including repeats of them, are unchanged. The lines are joined by \n.

    With ["aaabbb", "abaa"] and chars = "a", the answer is "abbb\naba". The run of three a characters becomes one, the run of bbb stays, and the two a characters at the end of "abaa" become one. A run collapses only when it is made of one and the same character: with chars = "ab", the line "abab" has no run at all, so it stays "abab". Case matters, and lines may be empty.

    Approach

    Walk through each line once and decide, for each character, whether to keep it. A character is dropped only when two things hold: it is in chars, and it equals the character that was kept just before it. Everything else is kept.

    That requires remembering the last kept character, prev. Scala has no continue statement, so the code states the opposite condition: keep the character when it is not in the set, or when it differs from prev. These two statements are exact opposites by De Morgan's law: "drop when in the set and equal to prev" is the same as "keep when not in the set or different from prev".

    Step by step

    1. Create squeeze as chars.toSet, a set holding each character of the string once.
    2. Create result, an empty ArrayBuffer[String], for the squeezed lines.
    3. Loop over each line in lines.
    4. Create a fresh StringBuilder named sb for the characters this line keeps.
    5. Create var prev = '\u0000', the null character. It stands for "nothing kept yet" at the start of every line, and it is a var because it changes.
    6. Loop over each character ch of line.
    7. Write if (!squeeze.contains(ch) || ch != prev), the keep condition.
    8. Inside the if, append ch to sb.
    9. Still inside, set prev to ch. It is always the last character kept, so the next character is compared with it.
    10. After the inner loop, add sb.toString() to result, even if it is empty.
    11. After the outer loop, return result.mkString("\n"). As the last line of the method it needs no return.

    The solution in Scala

    class Solution {
        def trSqueeze(lines: List[String], chars: String): String = {
            val squeeze = chars.toSet
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (line <- lines) {
                val sb = new StringBuilder()
                var prev = '\u0000'
                for (ch <- line) {
                    if (!squeeze.contains(ch) || ch != prev) {
                        sb.append(ch)
                        prev = ch
                    }
                }
                result += sb.toString()
            }
            result.mkString("\n")
        }
    }
    

    Details worth understanding:

    • chars.toSet turns a string into a Set[Char]. For "banana" it holds three members, b, a and n, and contains('n') is true. Here the set is immutable, which is fine because it is never changed.
    • prev only changes inside the if, that is, when a character is kept. A dropped character does not alter it, and it would be the same character anyway, so a long run is still compared against its own first member.
    • '\u0000' is a Char literal for the character with code 0. The solution relies on lines not containing the null character: such a character at the start of a line, when it is also in chars, would be taken for a repeat and dropped. For ordinary text, the first character of a line is always compared against something different.
    • Characters not in chars are always kept and still update prev. That is why "abab" with chars = "ab" is untouched: each character differs from the one before it.
    • != compares characters by value.

    Tracing the example

    For the line "aaabbb" with chars = "a", the set holds only a. Here is the inner loop, character by character:

    chkeptsb afterwards
    ayes (first of its run)a
    ano (in the set, same as prev)a
    anoa
    byes (not in the set)ab
    byesabb
    byesabbb

    The result is "abbb": the run of a characters collapses, and the run of b characters stays whole because b is not in chars.

    You might wonder whether prev should hold the last character kept or the last character seen. Here the two agree. A dropped character always equals prev, so recording it would change nothing, and every other character is kept and recorded. The lesson's wording, "the last character that went into sb", is the simplest to reason about.

    Complexity

    Building the set takes O(k) for k characters in chars. Processing takes O(N) for N characters over all lines, with one constant-time set check and one comparison per character. Extra space is O(k) for the set plus O(N) for the output.

    Edge cases and common mistakes

    • Several characters in chars. ["aabbaa", "abab", "aabb"] with "ab" gives "aba\nabab\nab". Each run collapses on its own, and "abab" has no runs.
    • Squeezing spaces. ["hello world"] with " " gives "hello world".
    • Only listed characters collapse. The same line with "l" gives "helo world": the two l characters merge and the spaces remain.
    • Case. ["AAaa"] with "a" gives "AAa". The capitals are not in the set, and the two lowercase letters merge.
    • Empty lines. ["", "zzz"] with "z" gives "\nz". The empty line stays.
    • Carrying prev across lines. Declaring prev outside the line loop would let a line's last character affect the next line's first. It is created inside the loop for that reason.
    • Empty list. The result is "".
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free