Start learning free

LESSON 28 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr -s in Kotlin: Squeezing Repeated Characters

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:

fun trSqueeze(lines: List<String>, chars: String): String

Example:

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

Output: "abbb\naba"

When printed:
abbb
aba

Turn chars into a HashSet with chars.toHashSet(). Walk each line tracking prev (the last char you kept); skip the current char only if it's in the set AND equals prev.

The full solution:
class Solution {
    fun trSqueeze(lines: List<String>, chars: String): String {
        val squeeze = chars.toHashSet()
        val result = mutableListOf<String>()
        for (line in lines) {
            val sb = StringBuilder()
            var prev = '\u0000'
            for (ch in line) {
                if (squeeze.contains(ch) && ch == prev) {
                    continue
                }
                sb.append(ch)
                prev = ch
            }
            result.add(sb.toString())
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Kotlin, explained

    Problem overview

    Version 4 of the tr project copies the -s flag. trSqueeze(lines: List<String>, chars: String): String collapses every run of the same character into one occurrence, but only for characters that appear in chars. Everything else is unchanged. The lines are returned joined with \n.

    Only runs of one repeated character are squeezed. Different characters next to each other aren't a run, and a run of a character that isn't in chars stays as it is. Case matters, and lines may be empty. For ["aaabbb", "abaa"] with chars = "a" the result is "abbb\naba": the a runs shrink, the b run stays.

    Approach

    While walking through a line, the code needs to know the character it handled last. If the current character is the same and is one of the squeeze characters, it is a repeat and gets skipped. Otherwise it is appended. This needs one variable, prev, holding the last character that was kept, and a set of the squeeze characters so the membership test is quick.

    Comparing with the last kept character is the same as comparing with the previous character, because a skipped character is by definition equal to the one before it.

    Step by step

    1. Build the set. val squeeze = chars.toHashSet() turns the string into a set of its characters in one call.
    2. Prepare the output. result is a val holding mutableListOf<String>().
    3. Loop over the lines with for (line in lines).
    4. Create a builder per line. val sb = StringBuilder() collects the characters this line keeps.
    5. Create prev. var prev = '\u0000', the null character, stands for "nothing came before". It is a var because it changes. It is reset for each line, since a run can't continue from one line into the next.
    6. Loop over the characters with for (ch in line).
    7. Test for a repeat. if (squeeze.contains(ch) && ch == prev) is true only when both hold: this character is one to squeeze, and it repeats the one before.
    8. Skip it. Inside the if, continue jumps to the next character, so this one is never appended.
    9. Keep the others. After the if, sb.append(ch) adds the character. The first character of a run always gets here, since its prev is something else.
    10. Update prev to ch, so the next character is compared with this one.
    11. Store the line. After the inner loop, result.add(sb.toString()), once per line.
    12. Join after the outer loop with joinToString("\n").

    The solution in Kotlin

    class Solution {
        fun trSqueeze(lines: List<String>, chars: String): String {
            val squeeze = chars.toHashSet()
            val result = mutableListOf<String>()
            for (line in lines) {
                val sb = StringBuilder()
                var prev = '\u0000'
                for (ch in line) {
                    if (squeeze.contains(ch) && ch == prev) {
                        continue
                    }
                    sb.append(ch)
                    prev = ch
                }
                result.add(sb.toString())
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • toHashSet() on a String produces a HashSet<Char>, with one member per distinct character. It replaces the loop that fills the set in the previous version.
    • '\u0000' is a Char literal. Single quotes make a Char, double quotes a String, and \u0000 is the Unicode escape for the character with code 0. Because prev is initialised with a Char, Kotlin infers its type as Char, so no ? or null is needed.
    • The placeholder never matches real text. It only matters for the first character of a line, where ch == prev must be false. A normal letter is never equal to the null character, so the first character is always kept.
    • continue ends the current round of the innermost loop, here the loop over characters, and moves to the next character. It skips both the append and the update of prev, which is fine because prev already equals ch.
    • && is short-circuit. The second test runs only if the first is true.

    Tracing the examples

    LinecharsResult
    "aaabbb""a"abbb
    "abaa""a"aba
    "aaabbb""ab"ab
    "aabbaa""ab"aba
    "aaAAaa""a"aAAa

    In the second row the lone a at the start and the pair at the end are separated by a b, so each is its own run: the first stays, the pair shrinks to one. In the third row both letters are in chars, so both runs shrink. The last row shows that case matters: AA isn't squeezed when only lowercase a is listed, and the two a runs around it don't join into one, so the output is aAAa.

    Complexity

    Each character is visited once, with a constant-time set lookup on average, so the time is O(total characters) plus O(m) to build the set from chars. The extra space is the set and the output.

    Edge cases and common mistakes

    • Squeezing every repeat. Only characters from chars are squeezed. In "aaabbb" with "a", the bbb stays.
    • Merging separated runs. Characters that come back after something else aren't repeats. "abaa" keeps its first a and its b and squeezes only the final pair.
    • Not resetting prev for each line. Declaring it outside the outer loop would let a line's last character affect the next line's first. It is declared inside the loop for that reason.
    • Empty lines. The inner loop never runs, the builder is empty, and the line stays in the output as an empty line. With ["aaabbb", "aabbaa", ""] and "ab" the result is ab, aba, then an empty line.
    • Comparing with the wrong character. Updating prev before the test, or not at all, makes the comparison meaningless.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free