Start learning free

LESSON 26 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in Scala: Translating Characters with a HashMap

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:

def tr(lines: List[String], set1: String, set2: String): String

Example:

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

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a HashMap[Char, Char] from each char in set1 to the matching char in set2. Then walk each line and use map.getOrElse(ch, ch) to translate.

val map = scala.collection.mutable.HashMap[Char, Char]()
for (i <- 0 until set1.length) {
    map(set1(i)) = set2(i)
}
// per char: map.getOrElse(ch, ch)


The full solution:
class Solution {
    def tr(lines: List[String], set1: String, set2: String): String = {
        val map = scala.collection.mutable.HashMap[Char, Char]()
        for (i <- 0 until set1.length) {
            map(set1(i)) = set2(i)
        }
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            val sb = new StringBuilder()
            for (ch <- line) {
                sb.append(map.getOrElse(ch, ch))
            }
            result += sb.toString()
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Scala, explained

    Problem overview

    Version 2 of the tr project translates a whole set of characters at once. The method tr(lines: List[String], set1: String, set2: String): String receives a list of lines and two strings of equal length. Every character of a line that appears in set1 at index i becomes set2(i). Other characters stay as they are, and the lines are joined by \n.

    The sets are ASCII, set1 has no repeated character, and characters are taken literally, with no ranges such as a-z. Lines may be empty. With ["banana", "cherry"], set1 = "abc" and set2 = "ABC", the answer is "BAnAnA\nCherry".

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

    Approach: build a lookup table, then translate each character once

    A tempting approach is to call replace once per pair. It breaks the swap case. Replacing a with b in "abba" gives "bbbb", and the following replacement of b with a then gives "aaaa", which is not the swap that was asked for. Every pair would see the output of the pairs before it.

    The reliable approach is to decide each character's fate from the original line. First build a map from each character of set1 to its partner in set2. Then walk through every line, look up each character in the map, and write either its replacement or the character itself into a new string. Each character is looked at exactly once, so nothing is replaced twice.

    Step by step

    1. Create map, a mutable HashMap[Char, Char], in a val. Keys are characters to look for, values are their replacements.
    2. Loop over every position i in 0 until set1.length. Both sets have the same length, so each position is valid in both.
    3. In the loop, store the pair with map(set1(i)) = set2(i): the character at position i of set1 maps to the character at position i of set2.
    4. Below the loop, create result, an empty ArrayBuffer[String], for the translated lines.
    5. Loop over each line in lines.
    6. For each line, create a fresh StringBuilder named sb, so that lines don't mix. It builds a string piece by piece, which is cheaper than gluing strings with + again and again.
    7. Write an inner loop over each character ch of line.
    8. In the inner loop, append map.getOrElse(ch, ch) to sb: the replacement if the map has one, otherwise ch itself.
    9. After the inner loop, add sb.toString() to result. This runs once per line, outside the inner loop.
    10. After the outer loop, return result.mkString("\n").

    The solution in Scala

    class Solution {
        def tr(lines: List[String], set1: String, set2: String): String = {
            val map = scala.collection.mutable.HashMap[Char, Char]()
            for (i <- 0 until set1.length) {
                map(set1(i)) = set2(i)
            }
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (line <- lines) {
                val sb = new StringBuilder()
                for (ch <- line) {
                    sb.append(map.getOrElse(ch, ch))
                }
                result += sb.toString()
            }
            return result.mkString("\n")
        }
    }
    

    Scala details that matter here:

    • map(set1(i)) = set2(i) is an update. Writing map(key) = value calls the map's update method, and it replaces any earlier value for the same key.
    • A string is indexed with parentheses, and set1(i) is a Char, which is why the map is typed HashMap[Char, Char].
    • getOrElse(key, default) never fails on a missing key. By contrast, map(key) on a missing key throws NoSuchElementException with the message key not found: b. Using getOrElse is what lets unchanged characters pass straight through.
    • for (ch <- line) hands out the characters of the string one at a time.
    • The map is a scala.collection.mutable.HashMap, spelled out in full. The default Map in Scala is immutable, and you could not fill it with an update like this.

    Tracing the swap

    With set1 = "ab" and set2 = "ba", the map holds a -> b and b -> a. For the line "abba", here is sb after each character:

    chsb after appending
    ab
    bba
    bbaa
    abaab

    Each character is looked up in the map exactly once, using the original line. The b that was written into sb for the first a is never looked up again, so it is never turned back into an a. That is the difference from chained replace calls.

    Notice where the map is built. It is filled once, before any line is read, and then shared by every line. Building it inside the line loop would give the same output but repeat the same work for each line. Notice too that the lookup table makes the cost of a line independent of how many pairs there are: a line of 1,000 characters needs 1,000 lookups whether set1 has 3 characters or 90.

    Scala also offers shorter ways to write the same idea. For example, "ab".zip("ba").toMap builds the map Map(a -> b, b -> a) in one expression, and "abba".map(c => m.getOrElse(c, c)) then gives baab. The lesson's loops show each step explicitly, which makes the logic easier to follow.

    Complexity

    Building the map takes O(k) for k characters in set1. Translating takes O(N) for N characters across all lines, since each lookup in a hash map takes constant time on average. The extra space is O(k) for the map plus O(N) for the output.

    Edge cases and common mistakes

    • Swaps. ["abba", "cab"] with "ab" and "ba" gives "baab\ncba". Chained replace calls give the wrong answer here, as shown above.
    • Characters outside set1. ["a-b c"] with " -" and "_+" gives "a+b_c": the letters are left alone, and the space and hyphen are translated.
    • Empty lines. ["", "xyz"] with "a" and "b" gives "\nxyz". The empty line stays.
    • Several matches. ["hello world"] with "lo" and "01" gives "he001 w1r0d".
    • Empty list. The result is "".
    • Using map(ch) directly. It throws for any character not in set1. Use getOrElse.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free