Start learning free

LESSON 27 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in Swift: 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:

func trDelete(_ lines: [String], _ chars: String) -> String

Example:

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

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into a Set<Character> for O(1) lookup. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
    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")
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Swift, explained

    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:

    CharacterDecisionOutput so far
    bkeptb
    adeletedb
    nkeptbn
    adeletedbn
    nkeptbnn
    adeletedbnn

    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

    1. Create set as an empty Set<Character> with var.
    2. Loop over each ch in chars. Iterating a string yields characters one at a time.
    3. Insert ch into the set with set.insert(ch). A set holds each value once, so repeated characters in chars are harmless.
    4. Create result, an empty [String], for the cleaned lines.
    5. Loop over each line in lines.
    6. Create out, an empty string, inside the loop, so each line starts clean.
    7. Loop over each ch in line.
    8. Test !set.contains(ch). A character is kept only when it is not in the set.
    9. Append ch to out inside that test. Characters in the set are skipped, which deletes them.
    10. Append out to result after the inner loop. This happens for every line, including one that ended up empty.
    11. 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.
    • insert returns a result you can ignore. insert reports whether the value was new, and Swift allows you to drop that value silently here.
    • String.append(_:) with a Character. out.append(ch) adds one character to the end of out. Because out is a var, the string can change.
    • ! flips a Boolean. !set.contains(ch) reads as "the set does not contain ch".
    • 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. set is 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 is Set with 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 as chars returns "abc".
    • Repeated characters in chars. ["abc"] with "aaa" returns "bc". The set holds a once.
    • Dropping empty lines. Only appending out when it is not empty would lose lines and break the output. Every line must be appended.
    • Deleting nothing. A character in chars that 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 "".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free