#2570

Merge Two 2D Arrays by Summing Values

Easy
ArrayHash TableTwo PointersHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using a hash map allows us to efficiently sum values for each id in a single pass through both arrays. This reduces the time complexity significantly by avoiding nested loops.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store the sum of values for each id.
  2. 2Step 2: Iterate through nums1 and add each id and its value to the hash map.
  3. 3Step 3: Iterate through nums2 and update the hash map by adding values for existing ids or creating new entries.
  4. 4Step 4: Convert the hash map to a list and sort it by id.
solution.py9 lines
1from collections import defaultdict
2
3def mergeArrays(nums1, nums2):
4    id_map = defaultdict(int)
5    for id1, val1 in nums1:
6        id_map[id1] += val1
7    for id2, val2 in nums2:
8        id_map[id2] += val2
9    return sorted(id_map.items())

Complexity note: The time complexity is O(n log n) due to the sorting step after inserting elements into the hash map, while the space complexity is O(n) for storing the sums.

  • 1Using a hash map allows for efficient summation of values without nested loops.
  • 2Sorting the final results is necessary to meet the output requirements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.