# 2363. Merge Similar Items

• Time: $O(n)$
• 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 class Solution { public: vector> mergeSimilarItems(vector>& items1, vector>& items2) { constexpr int kMax = 1000; vector> ans; vector count(kMax + 1); for (const vector& item : items1) count[item[0]] += item[1]; for (const vector& item : items2) count[item[0]] += item[1]; for (int i = 1; i <= kMax; ++i) if (count[i]) ans.push_back({i, count[i]}); return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public List> mergeSimilarItems(int[][] items1, int[][] items2) { final int kMax = 1000; List> ans = new ArrayList<>(); int[] count = new int[kMax + 1]; for (int[] item : items1) count[item[0]] += item[1]; for (int[] item : items2) count[item[0]] += item[1]; for (int i = 1; i <= kMax; ++i) if (count[i] > 0) ans.add(Arrays.asList(i, count[i])); return ans; } } 
 1 2 3 class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: return sorted((Counter(dict(items1)) + collections.Counter(dict(items2))).items())