Problem overview
This version of Tr takes a List<string> of lines and two strings of equal length, set1 and set2. Every character of a line that appears in set1 at index i becomes set2[i]. All other characters stay as they are. The lines are returned joined with "\n". Characters are literal (no ranges such as a-z), set1 has no repeated character, and lines may be empty.
For ["banana", "cherry"] with set1 = "abc" and set2 = "ABC", a becomes A, b becomes B and c becomes C. The result is "BAnAnA\nCherry".
Approach: build a lookup table, then translate character by character
With many pairs of characters, calling Replace once per pair goes wrong, and the statement explains why: all replacements happen at once. With set1 = "ab" and set2 = "ba" the letters must swap. Chained replacements would turn "abab" into "bbbb" with the first call and then into "aaaa" with the second, undoing the first.
The fix is to look at each character once and decide its replacement from the original character. A Dictionary<char, char> is the right lookup table: its keys are the characters in set1 and each value is the partner in set2. Then the method walks each line, and every character is either replaced through the map or copied as it is.
Here is the table for the example. The loop over set1 = "abc" and set2 = "ABC" stores three pairs: 'a' maps to 'A', 'b' to 'B' and 'c' to 'C'. Now the word "cherry": c is a key, so C is appended. h, e, r, r and y are not keys, so each is appended unchanged. The builder ends up holding "Cherry".
A map is not the only possible table. You could call set1.IndexOf(ch) for every character and use that position in set2. It works, but it scans set1 on every character. The dictionary answers in constant time on average, however long set1 is, and it states the idea directly: a character maps to a character.
The swap case shows why one pass is safe. With "ab" and "ba" the map holds 'a' to 'b' and 'b' to 'a'. The method reads each character from the original line and appends its partner to a different object, the builder. A character that was just produced is never looked up again, so nothing is translated twice. The line "abab" becomes "baba".
Step by step
- Create
map, an emptyDictionary<char, char>. - Loop over the positions of
set1withifrom 0 whilei < set1.Length. The sets have equal length, soiis a valid position in both. - Store a pair:
map[set1[i]] = set2[i]. Characters at the same position are partners. - Create
result, an emptyList<string>, for the translated lines. - Write a
foreachloop overlineswith the variableline. - Create a
StringBuilder sbinside the loop, a fresh one per line. It builds a string piece by piece withAppend, which is cheaper than gluing strings together with+again and again. - Loop over the characters of
linewithjwhilej < line.Length. - Read the character at position
jintochar ch. - Append the replacement or the character itself.
map.ContainsKey(ch) ? map[ch] : chpicksmap[ch]whenchis a key andchotherwise. - After the inner loop, add
sb.ToString()toresult. This runs once per line, outside the inner loop. - After the outer loop, return
string.Join("\n", result).
The solution in C#
class Solution {
public string Tr(List<string> lines, string set1, string set2) {
Dictionary<char, char> map = new Dictionary<char, char>();
for (int i = 0; i < set1.Length; i++) {
map[set1[i]] = set2[i];
}
List<string> result = new List<string>();
foreach (string line in lines) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < line.Length; j++) {
char ch = line[j];
sb.Append(map.ContainsKey(ch) ? map[ch] : ch);
}
result.Add(sb.ToString());
}
return string.Join("\n", result);
}
}
The C# details:
- The indexer both adds and overwrites.
map[key] = valueinserts the pair when the key is new and replaces the value when it exists.map.Add(key, value)throws anArgumentExceptionfor a duplicate key, but the lesson guarantees there are none. - Reading a missing key throws.
map['z']on a map without'z'raises aKeyNotFoundException, soContainsKeycomes first.TryGetValueis an alternative that does the check and the read in one call. - Both sides of the
?:arechar. The conditional operator needs compatible types, andAppend(char)then adds a single character. line[j]is achar. Strings can be indexed for reading, but not assigned to, since they are immutable. That is why the translated text goes into aStringBuilder.StringBuilderlives inSystem.Text.
Complexity
Let k be the length of set1 and L the total characters in all lines. Time: O(k + L), since building the map takes k steps and each character does two dictionary lookups, which take constant time on average. Space: O(k + L) for the map, the builders and the result.
Edge cases and common mistakes
- Swapping.
["abba", "cab"]with"ab"and"ba"gives"baab\ncba". This is what the one-pass approach is for. - Chained
Replacecalls. They break swaps, as shown above, because a replaced character can be replaced again. - Empty lines and empty sets.
["hello", ""]with empty sets gives"hello\n": the map is empty and nothing changes. - Partial coverage.
["hello"]with"lo"and"01"gives"he001". Characters not inset1pass through. - Case.
'a'and'A'are different keys. - Reading
map[ch]without checking. It throws for every character not inset1.
Testing
["banana", "cherry"],"abc","ABC"gives"BAnAnA\nCherry".["abba", "cab"],"ab","ba"gives"baab\ncba".["hello"],"lo","01"gives"he001".
