Start learning free

LESSON 26 OF 68 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in Java: Translate a Set of 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:

public String tr(List<String> lines, String set1, String set2)

Example:

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

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a Map<Character, Character> from each char in set1 to the matching char in set2. Then walk each line and use map.getOrDefault(ch, ch) to translate.

Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < set1.length(); i++) {
    map.put(set1.charAt(i), set2.charAt(i));
}
// per char: map.getOrDefault(ch, ch)


The full solution:
class Solution {
    public String tr(List<String> lines, String set1, String set2) {
        Map<Character, Character> map = new HashMap<>();
        for (int i = 0; i < set1.length(); i++) {
            map.put(set1.charAt(i), set2.charAt(i));
        }
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < line.length(); j++) {
                char ch = line.charAt(j);
                sb.append(map.getOrDefault(ch, ch));
            }
            result.add(sb.toString());
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Java, explained

    Problem overview

    The second version of the tr tool translates a whole set of characters at once. The method tr(List<String> lines, String set1, String set2) receives two strings of equal length. In each line, a character found in set1 at index i becomes set2.charAt(i). Characters that aren't in set1 stay as they are. The lines are joined by \n.

    The strings are ASCII and have the same length, set1 has no repeated character, and characters are literal (no ranges such as a-z). All replacements happen at once, so set1 = "ab" with set2 = "ba" swaps the two letters. Lines may be empty.

    For ["banana", "cherry"], set1 = "abc" and set2 = "ABC", the answer is "BAnAnA\nCherry".

    The previous version swapped a single character. This one needs a lookup from each character to its replacement.

    Approach: build a lookup, then translate character by character

    A Map<Character, Character> stores the pairs: the key is a character to look for, the value is its replacement. Build it once from the two sets, then walk through every line and look up each character.

    The "all at once" rule is the reason not to chain String.replace calls, one per pair. Replacing a with b and then b with a would turn the second step's input into a string that already contains the first step's output. For "abba" the chained replaces give aaaa. A character-by-character pass looks every character up in the original line, so each one is translated exactly once, and "abba" with "ab" and "ba" becomes baab.

    Another way to translate a character is to search set1 with indexOf and read set2 at the position found. It works, but it scans set1 for every character of every line. The map does that work once, up front, and then each lookup takes constant time on average. With the short sets of this lesson the difference is small, but the map also reads more clearly: it says which character becomes which.

    Per line, a StringBuilder collects the translated characters. append adds to its end, which is cheaper than gluing strings together with + over and over.

    Tracing one line

    With set1 = "abc" and set2 = "ABC" the map holds three pairs: a=A, b=B and c=C. Here is the builder after each character of "cherry":

    j=0 ch=c sb=C
    j=1 ch=h sb=Ch
    j=2 ch=e sb=Che
    j=3 ch=r sb=Cher
    j=4 ch=r sb=Cherr
    j=5 ch=y sb=Cherry
    

    Only c has an entry in the map. Every other character falls back to itself, so the line comes out as Cherry.

    Step by step

    1. Create map, a Map<Character, Character> set to a new HashMap.
    2. Loop over the positions of set1 with i from 0 to set1.length() - 1. The same position is valid in set2, since the lengths are equal.
    3. Store each pair with map.put(set1.charAt(i), set2.charAt(i)).
    4. Create result, an empty list of strings for the translated lines.
    5. Loop over the lines with a for-each loop that names each element line.
    6. Create a fresh StringBuilder named sb for each line, so lines don't mix.
    7. Loop over the positions of line with j from 0 to line.length() - 1.
    8. Read the character at position j into a char named ch.
    9. Append the translation. map.getOrDefault(ch, ch) returns the replacement, or ch itself when the map has none, and sb.append adds it.
    10. After the inner loop, add sb.toString() to result. It runs once per line, so it sits outside the inner loop's braces.
    11. After the outer loop, return String.join("\n", result).

    The solution in Java

    class Solution {
        public String tr(List<String> lines, String set1, String set2) {
            Map<Character, Character> map = new HashMap<>();
            for (int i = 0; i < set1.length(); i++) {
                map.put(set1.charAt(i), set2.charAt(i));
            }
            List<String> result = new ArrayList<>();
            for (String line : lines) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < line.length(); j++) {
                    char ch = line.charAt(j);
                    sb.append(map.getOrDefault(ch, ch));
                }
                result.add(sb.toString());
            }
            return String.join("\n", result);
        }
    }
    

    Details worth knowing:

    • Maps hold objects, not primitives. The type is Character, the wrapper of char. Java converts between the two automatically (autoboxing), so map.put(set1.charAt(i), ...) and getOrDefault(ch, ch) work with plain char values.
    • get versus getOrDefault. map.get('z') returns null for a missing key, and appending null would add the text null to the line. getOrDefault(ch, ch) gives the unchanged character instead.
    • put replaces an existing key. If set1 repeated a character, the later pair would silently overwrite the earlier one. The lesson rules repeats out, so each character has exactly one replacement and the loop needs no check for it.
    • charAt returns a char. It reads the character at a 0-based position.
    • Imports. List, ArrayList, Map and HashMap are in java.util.

    Complexity

    Time: O(m + t), where m is the length of set1 and t is the total number of characters in all lines. Building the map takes m insertions, and each character of the text costs one lookup, which takes constant time on average.

    Space: O(m + t). The map holds at most m pairs, and the builders and the result hold the translated text.

    Edge cases and common mistakes

    • Swaps. ["abba"] with "ab" and "ba" gives "baab". Chained replace calls give aaaa.
    • Characters outside the set. ["hello world", ""] with "lo" and "01" gives "he001 w1r0d\n". The space is untouched, and the empty line stays as an empty line after the last \n.
    • Reusing one StringBuilder. Creating it outside the line loop would glue all the lines into one.
    • Using get without a default. Missing keys give null.
    • Empty sets. With set1 and set2 both empty, the map is empty and every line comes back unchanged, so ["abc"] gives "abc".

    Testing

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