Start learning free

LESSON 26 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in Swift: Translating a Set of Characters with a Dictionary

Practice Read the full explanation

Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).

Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.

Function signature:

func tr(_ lines: [String], _ set1: String, _ set2: String) -> String

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a [Character: Character] dictionary from each char in set1 to the matching char in set2. Then walk each line and use map[ch] ?? ch to translate.

var map = [Character: Character]()
for (a, b) in zip(set1, set2) {
    map[a] = b
}
// per char: map[ch] ?? ch


The full solution:
class Solution {
    func tr(_ lines: [String], _ set1: String, _ set2: String) -> String {
        var map = [Character: Character]()
        for (a, b) in zip(set1, set2) {
            map[a] = b
        }
        var result = [String]()
        for line in lines {
            var out = ""
            for ch in line {
                out += String(map[ch] ?? ch)
            }
            result.append(out)
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Swift, explained

    Problem overview

    The second version of tr translates a whole set of characters at once. tr(_ lines: [String], _ set1: String, _ set2: String) -> String receives two ASCII strings of equal length. Every character of a line found at index i of set1 becomes set2[i]; every other character stays. The lines are joined with "\n". Characters are literal, there are no ranges, and set1 has no repeats.

    For ["banana", "cherry"], "abc" and "ABC" the result is "BAnAnA\nCherry".

    The replacements happen all at once. With set1 = "ab" and set2 = "ba", the line "abba" becomes "baab": the letters swap places.

    Approach: build a lookup table, then translate character by character

    The previous version called one string method per line. That can't work for a set. Calling replacingOccurrences once per pair is wrong for a swap: "abba" with a to b first becomes "bbbb", and the second replacement then turns every b into a, giving "aaaa". The pairs interfere with each other.

    The fix is to decide each character's fate in a single look. Build a dictionary from each character of set1 to its partner in set2. Then walk through the line once. For each character, ask the dictionary: if it has an entry, use the replacement, otherwise keep the character. Every character is judged from its original value, so there is no chain reaction.

    A dictionary also keeps the work small. The alternative is to search set1 for every character of every line, which repeats the same scan again and again. Building the table once means each character costs a single lookup, however long the sets are.

    Tracing one line

    Take "banana" with set1 = "abc" and set2 = "ABC". The dictionary holds a to A, b to B and c to C. The loop over the line extends out one character at a time:

    Characterout afterwards
    bB
    aBA
    nBAn
    aBAnA
    nBAnAn
    aBAnAnA

    The letter n has no entry in the dictionary, so it is copied as it is. Every other letter is looked up in the original table, never in the text built so far, which is why a translation can't be translated twice.

    Step by step

    1. Create the dictionary map, typed [Character: Character], with var. Keys are the characters to look for, values the replacements.
    2. Loop over zip(set1, set2) with a and b naming each pair. zip pairs up the characters at the same position.
    3. Store map[a] = b inside the loop.
    4. Create result, an empty [String], for the translated lines.
    5. Loop over line in lines.
    6. Create out, an empty string, inside the loop. A fresh one per line keeps lines from mixing.
    7. Loop over ch in line. Iterating a string yields its characters one at a time.
    8. Add the replacement String(map[ch] ?? ch) to out.
    9. Append out to result after the inner loop, once per line.
    10. Return the joined lines after the outer loop.

    The solution in Swift

        func tr(_ lines: [String], _ set1: String, _ set2: String) -> String {
            var map = [Character: Character]()
            for (a, b) in zip(set1, set2) {
                map[a] = b
            }
            var result = [String]()
            for line in lines {
                var out = ""
                for ch in line {
                    out += String(map[ch] ?? ch)
                }
                result.append(out)
            }
            return result.joined(separator: "\n")
        }
    

    Details that matter:

    • Character versus String. Looping over a string gives Character values, so the dictionary is keyed by Character. The final String(...) turns a character into a string so that += can append it to out.
    • Dictionary lookups are optional. map[ch] has type Character?: it is nil when ch is not a key. For example, with ["a": "b"], map["a"] is Optional("b") and map["z"] is nil.
    • The ?? operator. x ?? y gives the unwrapped x when it has a value, otherwise y. Here it falls back to the original character, so unlisted characters stay put.
    • zip and unequal lengths. zip stops at the shorter sequence. The lesson guarantees equal lengths, so no pair is lost.
    • Repeated keys. Assigning map[a] = b for a key that already exists overwrites the old value. The lesson promises that set1 has no repeats, so this never happens in its tests. If it did, the pair that comes last would win: with "aa" and "XY", map["a"] ends up as Optional("Y").
    • What a Character is. Swift's Character is one user-visible character, which can be made of several Unicode scalars. The text "e" followed by a combining accent has count 1 and two Unicode scalars. The lesson's input is plain ASCII, where each character is a single scalar, so the distinction doesn't show up.
    • Tuple destructuring. for (a, b) in zip(...) unpacks each pair into two names.

    Complexity

    Time: O(k + m), where k is the length of set1 and m the total number of characters in all lines. Building the table takes k steps, and each character of a line costs one average-constant-time dictionary lookup. Space: O(k + m) for the table and the translated output.

    Edge cases and common mistakes

    • Swaps. ["abba"] with "ab" and "ba" returns "baab". Chaining one replacement after another would turn it into "aaaa".
    • Characters outside set1. They are kept as they are: ["hello world"] with "lo" and "01" returns "he001 w1r0d", and the space stays.
    • Empty lines. ["", "xyz"] with "abc" and "ABC" returns "\nxyz". The empty line stays in place.
    • Case. "a" and "A" are different keys.
    • Forgetting String(...). Adding a Character to a String with += doesn't compile. The conversion is required.

    Testing

    • ["banana", "cherry"], "abc", "ABC" gives "BAnAnA\nCherry".
    • ["abba"], "ab", "ba" gives "baab".
    • ["hello world"], "lo", "01" gives "he001 w1r0d".
    • ["", "xyz"], "abc", "ABC" gives "\nxyz".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free