Problem overview
The third version of the tr project imitates tr -d. The method trDelete(lines: string[], chars: string) removes from every line each character that appears in chars, then returns the lines joined by \n.
chars is a non-empty ASCII string and its characters are literal, with no ranges. Upper and lower case are different characters. A line can become empty after the deletion, and then it stays in the output as an empty line. For ["banana", "apple"] with chars = "aeiou" the result is "bnn\nppl".
Approach: keep a character only if it is not in the set
The previous version translated characters through a map. Deleting is simpler: for every character of a line, ask "is it one of the characters to delete?" and keep it only when the answer is no. The question is a membership test, which is what a Set is for. new Set(chars) turns the string into a set with one member per character, and set.has(c) answers in constant time on average.
Notice that deleting is done by not appending. The code builds a new string for each line and appends only the characters that survive; nothing is removed from an existing string, which couldn't be done anyway because strings are immutable.
The same idea also works with chars.includes(c), which scans the string every time. The set is a better fit when chars could be long, and it expresses the intent: a collection of characters to look up.
TypeScript offers a shorter spelling of the same idea: [...line].filter(c => !set.has(c)).join("") spreads the line into an array of characters, keeps those not in the set and glues them back. For "banana" with the vowels as the set it gives "bnn". The loop in the lesson does the same work without the temporary array, and it shows each step: look at a character, decide, append.
The lesson's structure is the same as in the earlier versions: an outer loop over the lines, an inner loop over the characters of one line, a fresh out per line, and one join("\n") at the end. Only the decision inside the inner loop changes from version to version, here it is "append unless the set contains it".
Step by step
- Create the set:
let set = new Set(chars). Iterating a string produces its characters, so each one becomes a member. - Create
result, an emptystring[]for the cleaned lines. - Loop over the lines with
i. - Create
out, an empty string, inside the loop, so every line starts fresh. - Loop over the characters of
lines[i]withj. - Test that
lines[i][j]is not in the set:!set.has(...). The!flips the answer, so the body runs only for characters that are kept. - Append that character to
outwith+=. Characters in the set are skipped, which is the deletion. - Push
outontoresultafter the inner loop. An emptyoutis pushed too, so the empty line is kept. - Return
result.join("\n")after the outer loop.
The solution in TypeScript
class Solution {
trDelete(lines: string[], chars: string): string {
let set = new Set(chars);
let result: string[] = [];
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");
}
}
Language details
new Set(chars)accepts any iterable, and a string is iterable. The set's type is inferred asSet<string>. For example,[...new Set("hello")]is["h", "e", "l", "o"]: duplicates collapse into one member.- Iterating a string yields code points, while
lines[i][j]reads one UTF-16 code unit. For the ASCII text this lesson promises, the two are the same. - Case matters, because the set compares strings exactly:
"A"and"a"are different members.
Complexity
Building the set takes O(k) for k characters in chars. Each of the N characters in the lines is checked once, with an average O(1) lookup, so the time is O(k + N). The set needs O(k) space, and the output at most O(N).
Edge cases and common mistakes
- Lines that become empty.
["aaa", "b", ""]with"a"gives"\nb\n": the first and last lines are empty but still present. Skipping empty results would shift the lines and change the text. - Case.
["Banana"]with"a"gives"Bnn", and with"A"it gives"Banana", because there is no capital A to delete. - Repeated characters in
chars. They cost nothing: a set stores each character once, so"aeiouaeiou"behaves like"aeiou". - Deleting everything. If a line contains only characters from
chars, itsoutstays empty and the line becomes an empty line. The number of lines in the output always equals the number of lines in the input. - Declaring
outoutside the loop. The deleted text of one line would be carried into the next. - Mutating the input. The method builds new strings and leaves
linesexactly as it received it, so the caller can reuse the array afterwards. - Using
replaceper character. A string argument replaces only the first match, so it would leave later copies behind.
Testing
| Input | Result |
|---|---|
["banana", "apple"], "aeiou" | "bnn\nppl" |
["aaa", "b", ""], "a" | "\nb\n" |
["Banana"], "a" | "Bnn" |
["Banana"], "A" | "Banana" |
