Skip to main content
Back to problems
#2363
Easy Algorithms

Merge similar items

Array Hash Table Sorting Ordered Set
77.4% acceptance
Feb 25, 2026
607
32
You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei. Note: ret should be returned in ascending order by value.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
use std::collections::BTreeMap;


impl Solution {
  pub fn merge_similar_items(items1: Vec<Vec<i32>>, items2: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let mut map: BTreeMap<i32, i32> = BTreeMap::new();
    for item in items1.iter().chain(items2.iter()) {
      *map.entry(item[0]).or_insert(0) += item[1];
    }
    map.into_iter().map(|(v, w)| vec![v, w]).collect()
  }
}