Start learning free

LESSON 28 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in TypeScript: 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:

trSqueeze(lines: string[], chars: string): string

Example:

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

Output: "abbb\naba"

When printed:
abbb
aba

Build a Set of squeeze characters. Walk each line tracking the previous emitted character. Skip the current char only if it's in the squeeze set AND it equals prev.

if (squeeze.has(ch) && ch === prev) continue;
out += ch;
prev = ch;


The full solution:
class Solution {
    trSqueeze(lines: string[], chars: string): string {
        let squeeze: Set<string> = new Set(chars);
        let result: string[] = [];
        for (let i = 0; i < lines.length; i++) {
            let out: string = "";
            let prev: string = "";
            for (let j = 0; j < lines[i].length; j++) {
                let ch: string = lines[i][j];
                if (squeeze.has(ch) && ch === prev) {
                    continue;
                }
                out += ch;
                prev = ch;
            }
            result.push(out);
        }
        return result.join("\n");
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in TypeScript, explained

    Problem overview

    The fourth version of the tr project imitates tr -s. The method trSqueeze(lines: string[], chars: string) collapses every run of the same character, when that character is in chars, into a single occurrence. All other characters stay as they are, including runs of characters that are not in chars. The lines are returned joined by \n.

    chars is non-empty ASCII, taken literally. Case matters, and lines may be empty. For ["aaabbb", "abaa"] with chars = "a" the result is "abbb\naba": the run of a in the first line shrinks to one, the bbb stays, and the two trailing as of the second line become one.

    Approach: skip a character that repeats the one just kept

    A repeat means "the same as the character right before it". So while building the output line, the code remembers the last character it added, in prev. A new character is dropped only when both things are true: it is in the set of characters to squeeze, and it equals prev. Everything else is added.

    The two conditions are both needed. Without the set test, every repeat would be squeezed and "bbb" would shrink even though b is not in chars. Without the prev test, every character from the set would be dropped, not only the repeats. Only runs of the same character count: with chars = "ab", "aabbaa" becomes "aba", because a and b are each squeezed within their own runs, and the three runs stay as three characters.

    The first character of a run always passes, since prev holds something else at that moment. At the start of each line prev is the empty string, which can't equal any character, so the first character of a line is always kept.

    Why compare with the last character kept rather than the last character read? Here the two are always equal, because the only characters dropped are repeats of prev. If a character is dropped, it equals prev, so prev would not change anyway. Keeping a single variable that always holds the last character of out makes the rule easy to state: a character is dropped when it would repeat the end of the output.

    Step by step

    1. Create the set of characters to squeeze: let squeeze: Set<string> = new Set(chars).
    2. Create result, an empty string[].
    3. Loop over the lines with i.
    4. Create out, an empty string for the squeezed line.
    5. Create prev, also an empty string. Nothing came before the line, so it starts as a value that no character equals.
    6. Loop over the characters of the line with j.
    7. Read the character into ch.
    8. Test for a repeat: squeeze.has(ch) && ch === prev.
    9. Skip it with continue, which jumps to the next character, so this one is never added.
    10. Append ch to out. Only the first character of each run, and every unsqueezed character, reaches this line.
    11. Update prev to ch. It is always the last character kept.
    12. Push out onto result after the inner loop. An empty out is kept as an empty line.
    13. Return result.join("\n") after the outer loop.

    The solution in TypeScript

    class Solution {
        trSqueeze(lines: string[], chars: string): string {
            let squeeze: Set<string> = new Set(chars);
            let result: string[] = [];
            for (let i = 0; i < lines.length; i++) {
                let out: string = "";
                let prev: string = "";
                for (let j = 0; j < lines[i].length; j++) {
                    let ch: string = lines[i][j];
                    if (squeeze.has(ch) && ch === prev) {
                        continue;
                    }
                    out += ch;
                    prev = ch;
                }
                result.push(out);
            }
            return result.join("\n");
        }
    }
    

    Language details

    • continue ends the current pass of the innermost loop and moves on to the next j. It skips both out += ch and prev = ch. Skipping the update of prev is harmless here, because prev already equals ch.
    • && short-circuits: if squeeze.has(ch) is false, the comparison with prev is never evaluated.
    • === compares two strings by content.
    • The annotations Set<string> and : string are checked by the compiler and erased when it produces JavaScript.

    Complexity

    Every character of every line is visited once, with an average O(1) set lookup, so the time is O(k + N) for k characters in chars and N characters in all the lines. The set uses O(k) space and the output O(N).

    Edge cases and common mistakes

    • Squeezing characters outside the set. ["bbb", "", "aaaa"] with "a" gives "bbb\n\na": the bs stay, the empty line stays, and the four as become one.
    • Runs of different set characters. ["aabbaa"] with "ab" gives "aba", not "a": each run shrinks, and the runs are kept.
    • Spaces as squeeze characters. ["aXXa b"] with "a " gives "aXXa b": the double space shrinks, while the XX does not because X is not in the set.
    • Mutating the input. The method builds new strings and never changes lines.
    • Case. ["aAaa"] with "a" gives "aAa". The capital A is a different character, so it breaks the run, and only the final aa is squeezed.
    • A line made only of squeezed characters. A line "aaaa" with "a" becomes "a", not an empty line: the first character of the run is always kept.
    • Forgetting to reset prev. If prev were declared outside the outer loop, a line starting with the character that ended the previous line would lose its first character.

    Testing

    InputResult
    ["aaabbb", "abaa"], "a""abbb\naba"
    ["aabbaa"], "ab""aba"
    ["aXXa b"], "a ""aXXa b"
    ["bbb", "", "aaaa"], "a""bbb\n\na"
    ["aAaa"], "a""aAa"
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free