Problem overview
The third version of tr behaves like tr -d. trDelete(_ lines: [String], _ chars: String) -> String removes every character that appears in chars from each line and returns the lines joined with "\n". chars is a non-empty ASCII string whose characters are literal, and case matters. A line that loses all its characters stays in the output as an empty line.
For ["banana", "apple"] and "aeiou" the result is "bnn\nppl".
Approach: a set of characters to delete
For each character of a line, the question is: is it one of the characters to delete? Answering that by scanning chars every time works, but a Set is built for this question. Checking whether a set contains a value takes constant time on average, however many values it holds.
So the plan has two parts. First, put every character of chars in a Set<Character>. Second, build each output line by copying only the characters that are not in the set. The line is never edited in place: a new string collects the survivors.
The previous version translated characters through a dictionary. This one needs only membership, with no replacement, so a set is the right tool. The next version builds on this shape.
Here is "banana" with chars = "aeiou", one character at a time:
| Character | Decision | Output so far |
|---|---|---|
b | kept | b |
a | deleted | b |
n | kept | bn |
a | deleted | bn |
n | kept | bnn |
a | deleted | bnn |
The answer for that line is "bnn". The order of the surviving characters never changes: deleting only removes characters, it never moves them.
A shorter way to write it
Swift strings have a filter method that keeps the characters for which a closure returns true and gives back a String. With the same set, "banana".filter { !set.contains($0) } is "bnn", and it replaces the inner loop and the out variable. The lesson spells the loop out so that each step is visible: create a fresh string, test each character, append the keepers. Once the loop is clear, filter says the same thing in one line.
Either way, the set is what makes the test cheap, and it is built once before any line is read.
Step by step
- Create
setas an emptySet<Character>withvar. - Loop over each
chinchars. Iterating a string yields characters one at a time. - Insert
chinto the set withset.insert(ch). A set holds each value once, so repeated characters incharsare harmless. - Create
result, an empty[String], for the cleaned lines. - Loop over each
lineinlines. - Create
out, an empty string, inside the loop, so each line starts clean. - Loop over each
chinline. - Test
!set.contains(ch). A character is kept only when it is not in the set. - Append
chtooutinside that test. Characters in the set are skipped, which deletes them. - Append
outtoresultafter the inner loop. This happens for every line, including one that ended up empty. - Return the joined lines after the outer loop.
The solution in Swift
func trDelete(_ lines: [String], _ chars: String) -> String {
var set = Set<Character>()
for ch in chars {
set.insert(ch)
}
var result = [String]()
for line in lines {
var out = ""
for ch in line {
if !set.contains(ch) {
out.append(ch)
}
}
result.append(out)
}
return result.joined(separator: "\n")
}
Details that matter:
Set<Character>(). It creates an empty set. The element type is written out because nothing in that line lets the compiler infer it.insertreturns a result you can ignore.insertreports whether the value was new, and Swift allows you to drop that value silently here.String.append(_:)with aCharacter.out.append(ch)adds one character to the end ofout. Becauseoutis avar, the string can change.!flips a Boolean.!set.contains(ch)reads as "the set does not containch".- Each line is judged alone. The set is filled once, before the line loop, and every line is cleaned against the same set. Nothing carries over from one line to the next.
- A variable named
set.setis not a reserved word in an ordinary function body, so it is a valid name here. It is easy to mistake for a type name, though; the type isSetwith a capital letter.
Complexity
Time: O(k + m), where k is the length of chars and m the total number of characters across all lines: building the set takes k insertions, and each line character costs one membership test. Space: O(k + m) for the set and the output lines.
Edge cases and common mistakes
- A line that becomes empty.
["aaa", "bob", "xyz"]with"ab"returns"\no\nxyz". The first line is empty but still counts as a line, so the result starts with a newline. - Case.
["Hello"]with"l"returns"Heo", while with"L"it returns"Hello". - Spaces are characters too.
["a b c"]with a single space ascharsreturns"abc". - Repeated characters in
chars.["abc"]with"aaa"returns"bc". The set holdsaonce. - Dropping empty lines. Only appending
outwhen it is not empty would lose lines and break the output. Every line must be appended. - Deleting nothing. A character in
charsthat never appears in the lines is simply never matched, and the lines pass through unchanged. - No lines. An empty list returns
"".
Testing
["banana", "apple"],"aeiou"gives"bnn\nppl".["aaa", "bob", "xyz"],"ab"gives"\no\nxyz".["Hello"],"l"gives"Heo".["Hello"],"L"gives"Hello".["abc"],"aaa"gives"bc".[],"a"gives"".
