Skip to content

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<vector<int>> mergeSimilarItems(vector<vector<int>>& items1,
                                        vector<vector<int>>& items2) {
    constexpr int kMax = 1000;
    vector<vector<int>> ans;
    vector<int> count(kMax + 1);

    for (const vector<int>& item : items1)
      count[item[0]] += item[1];

    for (const vector<int>& 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<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
    final int kMax = 1000;
    List<List<Integer>> 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)) + Counter(dict(items2))).items())