Problem overview
The method InvertDictionary receives a Dictionary<string, string> named d and returns a new dictionary with keys and values swapped. Every value of d becomes a key, and it maps to the key it belonged to. The order of the entries doesn't matter.
For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {"red": "apple", "yellow": "banana", "purple": "plum"}. For {"cat": "dog"} it is {"dog": "cat"}. The case {"a": "b", "b": "c"} gives {"b": "a", "c": "b"}: the string "b" is a value in one entry and a key in another, and each entry turns around on its own, so there is no clash.
The lesson guarantees that all values are different, so the result has exactly as many entries as d.
Approach: turn each entry around
Each entry is a pair: a key and its value. Swapping means writing the pair into a new dictionary the other way round. Go through every entry of d once, read the value, and store result[value] = key.
The swapped pairs go into a new dictionary instead of changing d in place. Adding an entry to a dictionary while a loop goes over it throws an InvalidOperationException, and building a fresh result avoids the problem.
On the first example, the loop reads "apple" with the value "red" and stores "red" with the value "apple". Then it does the same for "banana" and "plum". After three rounds the new dictionary has three entries, and d is exactly as it was.
Step by step
- Create an empty
Dictionary<string, string>namedresult. Both key and value types arestring. - Write a
foreachloop with astringnamedkeyoverd.Keys, the collection of the dictionary's keys. - Read the value stored under the key,
d[key], into astringnamedvalue. Turning an entry around needs both halves. - Store the swapped pair with
result[value] = key. The old value is now the key. Because the values are all different, no two entries land on the same key. - Return
resultafter the loop.
The solution in C#
class Solution {
public Dictionary<string, string> InvertDictionary(Dictionary<string, string> d) {
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (string key in d.Keys) {
string value = d[key];
result[value] = key;
}
return result;
}
}
Details worth knowing:
d.Keysis a view of the keys, andd[key]is always safe inside this loop, because every key in it exists ind.- Assigning to a key that doesn't exist yet adds an entry, so
result[value] = keyneeds noContainsKeycheck. - A
foreach (var pair in d)loop over the entries would also work, withpair.Keyandpair.Value. The lesson's loop overd.Keysdoes the same job.
Edge cases and common mistakes
- Repeated values. If two keys shared a value, the later assignment would overwrite the earlier one and an entry would be lost. For
{"a": "x", "b": "x"}the result is the single entry{"x": "b"}. The lesson rules this case out. - Changing
din the loop. Adding entries todwhile looping over its keys throws an exception. Use a separateresult. - A value that is also a key. The example
{"a": "b", "b": "c"}works becausedis never modified: the answer is built in another dictionary. - Swapped assignment.
result[key] = valuewould just copyd.
Testing
| d | Result |
|---|---|
{"apple": "red", "banana": "yellow", "plum": "purple"} | {"red": "apple", "yellow": "banana", "purple": "plum"} |
{"cat": "dog"} | {"dog": "cat"} |
{"a": "b", "b": "c"} | {"b": "a", "c": "b"} |
