Problem overview
The method toDictionary receives an array of strings, names, and an array of integers, scores, of the same length. It returns a HashMap<String, Integer> in which each names[i] is a key and scores[i] is its value.
For ["Ana", "Ben", "Cara"] and [90, 75, 88] the map is {Cara=88, Ana=90, Ben=75}: "Ana" sits at index 0 and so does 90, and the same goes for the other two. The names are all different, but two names may share a score, so ["Zoe", "Adam"] with [60, 60] gives two entries, {Adam=60, Zoe=60}. Two empty arrays give an empty map, {}. The order of the entries doesn't matter, and the order you see when printing is chosen by the HashMap.
Approach: one index reaches both arrays
The arrays are parallel: position i in one belongs with position i in the other. A single loop over the indices can therefore read both values and store them as one entry. The loop runs once per name, and each pass adds exactly one entry.
Step by step
- Create the empty map.
HashMap<String, Integer> result = new HashMap<>();will get one entry per name. - Loop over the indices. You need the index itself, so the enhanced
forloop isn't enough here. Usefor (int i = 0; i < names.length; i++). Arrays use the fieldlength, without parentheses. - Store the pair.
result.put(names[i], scores[i])uses the name as the key and the score at the same index as the value. Theintis boxed into anIntegerautomatically. - Return the map after the loop.
The solution in Java
class Solution {
public HashMap<String, Integer> toDictionary(String[] names, int[] scores) {
HashMap<String, Integer> result = new HashMap<>();
for (int i = 0; i < names.length; i++) {
result.put(names[i], scores[i]);
}
return result;
}
}
Java details worth knowing:
- Empty input. With two empty arrays the loop condition
0 < 0is false at once, so the method returns an empty map with no special case. putreplaces. If a key is stored twice, the later value overwrites the earlier one and the map keeps one entry. With names that are all different, as promised, that can't happen. With["Ana", "Ana"]and[1, 2]the result would be{Ana=2}.- Two arrays, two lengths. The loop uses
names.length. Ifscoreswere shorter,scores[i]would throw anArrayIndexOutOfBoundsException. The lesson guarantees equal lengths. - The printed form. A map prints as
{key=value, ...}with no quotes around the strings, in an order theHashMapdecides.
What the map is for
The two arrays can only be matched by position, so finding Ben's score means searching the names for "Ben" and then reading the same index in scores. The map removes that step. For the first example, get("Ben") is 75, containsKey("Cara") is true, size() is 3, and get("Dan") is null, because "Dan" was never added.
Complexity
Time: O(n) for n names, since each put costs a constant amount on average. Space: O(n), because the map holds one entry per name.
Edge cases and common mistakes
- Looping with
names.length(). That doesn't compile: arrays have alengthfield, not a method. - Swapping key and value.
result.put(scores[i], names[i])would not match the return type, and scores can repeat, so entries would be lost. - Returning inside the loop. The map would hold only the first pair.
- Expecting the map to keep the input order. A
HashMapdoesn't. Use aLinkedHashMapif you need the order of insertion.
Testing
["Ana", "Ben", "Cara"]and[90, 75, 88]give{Cara=88, Ana=90, Ben=75}.["Zoe", "Adam"]and[60, 60]give{Adam=60, Zoe=60}.["Max"]and[100]give{Max=100}.- Two empty arrays give
{}.
