Start learning free

LESSON 625 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in JavaScript: Deleting Characters with a Set

Practice Read the full explanation

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

trDelete(lines, chars)

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Build a Set from chars (passing a string to the Set constructor iterates char-by-char). For each line, walk char-by-char and keep characters NOT in the set.

let set = new Set(chars);
// per char: if (!set.has(ch)) out += ch;


The full solution:
class Solution {
    trDelete(lines, chars) {
        let set = new Set(chars);
        let result = [];
        for (let i = 0; i < lines.length; i++) {
            let out = "";
            for (let j = 0; j < lines[i].length; j++) {
                if (!set.has(lines[i][j])) {
                    out += lines[i][j];
                }
            }
            result.push(out);
        }
        return result.join("\n");
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in JavaScript, explained

    Problem overview

    This version of the tr tool deletes characters, like tr -d. The method trDelete(lines, chars) receives an array of lines and a non-empty string chars. It removes from each line every character that appears in chars, and returns the lines joined by \n.

    The characters are ASCII and literal, with no ranges, and upper and lower case are different characters. A line can become empty after the deletion. It then stays in the output as an empty line, so the number of lines never changes.

    For ["banana", "apple"] with chars = "aeiou", the vowels disappear and the result is "bnn\nppl".

    Approach: keep a character only if it is not in the set

    Deleting characters from a string is easier to see as building a new string from the characters that survive. For each character of a line, ask one question: is it one of the characters to delete? If not, append it to the output line.

    That question is asked once per character of the input, so it should be fast. A JavaScript Set answers "is this a member?" with has in constant time on average. new Set(chars) iterates over the string and makes each character a member, so a set of the characters to delete takes one line to build. Searching the string chars with includes would also work, but the set makes the intent clear and keeps each check cheap.

    The same idea can be written in one expression, [...line].filter((ch) => !set.has(ch)).join(""), which spreads the line into an array of characters, keeps the ones outside the set and glues them back together. The lesson uses explicit loops, which make each step visible and are easy to follow with a debugger or with console.log.

    Step by step

    1. Create the set. let set = new Set(chars) turns each character of chars into a member.
    2. Create result, an empty array for the cleaned lines.
    3. Loop over the lines with i from 0 while i < lines.length.
    4. Create out, an empty string for the current line. Each line gets its own, so lines don't mix.
    5. Loop over the characters of lines[i] with j.
    6. Test the character. !set.has(lines[i][j]) is true when the character is not in the set, which means it is kept.
    7. Append it to out with +=. Characters in the set are skipped, which is how they are deleted.
    8. Push out onto result after the inner loop, once per line. An emptied line is pushed too.
    9. Return result.join("\n") after the outer loop.

    The solution in JavaScript

    class Solution {
        trDelete(lines, chars) {
            let set = new Set(chars);
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                let out = "";
                for (let j = 0; j < lines[i].length; j++) {
                    if (!set.has(lines[i][j])) {
                        out += lines[i][j];
                    }
                }
                result.push(out);
            }
            return result.join("\n");
        }
    }
    

    Notes on the JavaScript:

    • A string is iterable. new Set("banana") contains "b", "a" and "n": repeated characters collapse into one member, which is harmless here because a character only needs to be listed once.
    • A Set compares strings by value. The one-character string lines[i][j] matches a member with the same text.
    • The variable name. set is an ordinary variable name here. A more descriptive name such as deleteSet would work just as well.
    • Nothing is mutated. The input array and its strings are untouched, since the method only reads them and builds new strings.
    • ! flips the test. The condition says "not a member", so the body runs for characters to keep.

    Tracing one line

    For the first line, "banana", with chars = "aeiou", the inner loop goes through the characters like this:

    jcharacterkept?out afterwards
    0"b"yes"b"
    1"a"no"b"
    2"n"yes"bn"
    3"a"no"bn"
    4"n"yes"bnn"
    5"a"no"bnn"

    When the inner loop ends, "bnn" is pushed onto result. The outer loop then starts again with a fresh, empty out for "apple", which becomes "ppl". The final join gives "bnn\nppl".

    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 visits k characters, and each input character costs one set lookup and at most one append.

    Space: O(k + N): the set has at most k members, and the output is at most as long as the input.

    Edge cases and common mistakes

    • A line that disappears completely. ["aaa", "x"] with "a" gives "\nx": the first line is empty but still there. Skipping empty results would shift the later lines up.
    • Case matters. ["Apple"] with "a" gives "Apple", because "A" is not "a".
    • Several characters. ["Hello, World!"] with "lo," gives "He Wrd!". The comma is deleted but the space stays.
    • Nothing to delete. ["aaa", "bab"] with "a" gives "\nbb", and a line with none of the characters is returned as it was.
    • Declaring out outside the outer loop. The deleted text of one line would carry into the next.
    • Pushing inside the inner loop. Pushing out for every character would add a growing partial line each time.
    • Forgetting the !. The method would then keep only the characters it was supposed to delete.

    Testing

    • ["banana", "apple"], "aeiou" gives "bnn\nppl".
    • ["aaa", "bab"], "a" gives "\nbb".
    • ["Hello, World!"], "lo," gives "He Wrd!".
    • ["Apple"], "a" gives "Apple".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free