Start learning free

LESSON 626 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in JavaScript: 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, chars)

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, chars) {
        let squeeze = new Set(chars);
        let result = [];
        for (let i = 0; i < lines.length; i++) {
            let out = "";
            let prev = "";
            for (let j = 0; j < lines[i].length; j++) {
                let ch = 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

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in JavaScript, explained

    Problem overview

    This version of the tr tool squeezes repeats, like tr -s. The method trSqueeze(lines, chars) receives an array of lines and a non-empty string chars. In each line, a run of the same character that is listed in chars collapses into one occurrence. The result is the lines joined by \n.

    Only runs of a character from chars are touched. Runs of any other character stay as they are. Case matters, and lines may be empty.

    For ["aaabbb", "abaa"] with chars = "a", the result is "abbb\naba". The "aaa" becomes "a", the "bbb" is not in chars, and in "abaa" only the final pair of as is a run.

    Approach: skip a character that repeats the last kept one

    A character should be dropped when two things are true: it is in chars, and it equals the character just before it. So the loop only has to remember the previous character of the line.

    The lesson stores that memory in prev, the last character that went into the output. For each character ch: if chars contains it and ch === prev, skip it with continue. Otherwise append it to the output and make it the new prev. The first character of a run always passes, because prev is different, and the repeats after it are skipped.

    At the start of each line prev is the empty string, which no one-character string equals. That way the first character of a line is never mistaken for a repeat of the previous line's last character.

    Step by step

    1. Create the set. let squeeze = new Set(chars) makes each character of chars a member, so has answers "is this one to squeeze?" quickly.
    2. Create result, an empty array for the squeezed lines.
    3. Loop over the lines with i.
    4. Create out, an empty string holding the characters this line keeps.
    5. Create prev as an empty string. It remembers the last character added to out.
    6. Loop over the characters of lines[i] with j.
    7. Take the character at position j into ch.
    8. Test for a repeat: squeeze.has(ch) && ch === prev. Both parts must be true.
    9. Skip it with continue, which jumps to the next character, so this one is never added.
    10. Append ch to out after the if.
    11. Update prev to ch, so the next character is compared with the latest kept one.
    12. Push out onto result after the inner loop. A line can be empty and still gets pushed.
    13. Return result.join("\n") after the outer loop.

    Tracing the example

    For the line "aaabbb" with chars = "a", the inner loop proceeds as follows:

    chactionout afterwardsprev afterwards
    "a"keep"a""a"
    "a"skip"a""a"
    "a"skip"a""a"
    "b"keep"ab""b"
    "b"keep"abb""b"
    "b"keep"abbb""b"

    The repeated "b"s equal prev, but "b" is not in squeeze, so the first half of the test is false and they are kept. The line becomes "abbb".

    The second line, "abaa", shows why prev must be the last character kept. The first "a" is kept, the "b" is kept and becomes prev, so the next "a" is no longer a repeat and is kept too. Only the last "a" equals prev and is skipped, which gives "aba". The final join then returns "abbb\naba".

    The solution in JavaScript

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

    The JavaScript details:

    • continue affects the innermost loop. It ends the current pass of the j loop and moves on to the next character. The i loop is not affected.
    • && short-circuits. If squeeze.has(ch) is false, ch === prev is not evaluated, and the character is kept.
    • === on strings compares text. Two one-character strings are equal when they contain the same character, so "a" === "a" is true.
    • Skipped characters don't need to update prev. A skipped character equals prev, so updating it would change nothing.
    • Strings are immutable. out += ch creates a new string each time. This is fine at these sizes.

    Complexity

    Let k be the length of chars and N the total number of characters in all lines.

    Time: O(k + N). Building the set takes k steps, and each character costs one set lookup, one comparison and at most one append.

    Space: O(k + N) for the set and for the output, which is never longer than the input.

    Edge cases and common mistakes

    • Only listed characters collapse. ["aabb"] with "x" gives "aabb": neither letter is in chars.
    • Several characters. ["aaabbb"] with "ab" gives "ab", and ["a b c"] with a single space gives "a b c".
    • Alternating characters are not runs. ["abab"] with "ab" stays "abab", since no letter is next to an equal one.
    • Case matters. ["aAaA"] with "a" stays "aAaA", because "A" and "a" are different characters.
    • Empty lines. ["", "ee"] with "e" gives "\ne". The empty line stays empty.
    • Not resetting prev for each line. A line starting with a listed character could then lose it when the previous line ended with the same one. Declaring prev inside the outer loop prevents this.
    • Squeezing every repeat. Dropping any character equal to the previous one, listed or not, would also shorten "bbb", which must stay as it is.

    Testing

    • ["aaabbb", "abaa"], "a" gives "abbb\naba".
    • ["aaabbb"], "ab" gives "ab".
    • ["a b c"], " " gives "a b c".
    • ["abab"], "ab" gives "abab".
    • ["", "ee"], "e" gives "\ne".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free