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
- Create the set.
let set = new Set(chars)turns each character ofcharsinto a member. - Create
result, an empty array for the cleaned lines. - Loop over the lines with
ifrom 0 whilei < lines.length. - Create
out, an empty string for the current line. Each line gets its own, so lines don't mix. - Loop over the characters of
lines[i]withj. - Test the character.
!set.has(lines[i][j])is true when the character is not in the set, which means it is kept. - Append it to
outwith+=. Characters in the set are skipped, which is how they are deleted. - Push
outontoresultafter the inner loop, once per line. An emptied line is pushed too. - 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
Setcompares strings by value. The one-character stringlines[i][j]matches a member with the same text. - The variable name.
setis an ordinary variable name here. A more descriptive name such asdeleteSetwould 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:
| j | character | kept? | 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
outoutside the outer loop. The deleted text of one line would carry into the next. - Pushing inside the inner loop. Pushing
outfor 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".
