# 2570. Merge Two 2D Arrays by Summing Values

• Time: $O(|\texttt{nums1}| + |\texttt{nums2}|)$
• Space: $O(1000) = O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public: vector> mergeArrays(vector>& nums1, vector>& nums2) { constexpr int kMax = 1000; vector> ans; vector count(kMax + 1); addCount(nums1, count); addCount(nums2, count); for (int i = 1; i <= kMax; ++i) if (count[i] > 0) ans.push_back({i, count[i]}); return ans; } private: void addCount(const vector>& nums, vector& count) { for (const vector& idAndVal : nums) { const int id = idAndVal[0]; const int val = idAndVal[1]; count[id] += val; } } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution { public int[][] mergeArrays(int[][] nums1, int[][] nums2) { final int kMax = 1000; List ans = new ArrayList<>(); int[] count = new int[kMax + 1]; addCount(nums1, count); addCount(nums2, count); for (int i = 1; i <= kMax; ++i) if (count[i] > 0) ans.add(new int[] {i, count[i]}); return ans.stream().toArray(int[][] ::new); } private void addCount(int[][] nums, int[] count) { for (int[] idAndVal : nums) { final int id = idAndVal[0]; final int val = idAndVal[1]; count[id] += val; } } } 
  1 2 3 4 5 6 7 8 9 10 class Solution: def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]: count = [0] * (1001) self._addCount(nums1, count) self._addCount(nums2, count) return [[i, c] for i, c in enumerate(count) if c > 0] def _addCount(self, nums: List[List[int]], count: List[int]) -> None: for id_, val in nums: count[id_] += val