1023. Merge Two Stockrooms
A hardware shop has two stockrooms. Each one keeps a tally that maps an item name to the number of units on its shelves; a describes the first room and b the second. The shop is closing one room, and everything must be recorded in a single combined tally.
Return a map that contains every item name found in a or b. If an item is in both rooms, its count is the sum of the two counts; otherwise it keeps the count from the only room that has it. Items with a count of 0 must still appear. The input maps are not modified, and the order of keys does not matter.
Aim for O(|a| + |b|) time.
Example 1
- Input:
- a = {"bolt":10,"nut":4}, b = {"nut":6,"washer":3}
- Output:
- {"bolt":10,"nut":10,"washer":3}
- Explanation:
Only nut is in both rooms, so its counts add up to 10 while bolt and washer are copied over.
Example 2
- Input:
- a = {}, b = {"gear":2}
- Output:
- {"gear":2}
- Explanation:
The first room is empty, so the result is just the second room's tally.
Example 3
- Input:
- a = {"cog":0}, b = {"cog":0,"pin":0}
- Output:
- {"cog":0,"pin":0}
- Explanation:
Zero counts are kept, so both cog and pin appear with count 0.
Constraints
0 ≤ number of items in each map ≤ 105.
Item names are non-empty strings of at most 20 lowercase letters.
0 ≤ each count ≤ 109, so every merged count fits in a 32-bit signed integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(|a| + |b|)
- Space
- O(|a| + |b|)