Skip to main content
Back to problems
#2570
Easy Algorithms

Merge two 2d arrays by summing values

Array Hash Table Two Pointers
81.7% acceptance
Feb 25, 2026
832
38
You are given two 2D integer arrays nums1 and nums2. nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. Each array contains unique ids and is sorted in ascending order by id. Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions: Only ids that appear in at least one of the two arrays should be included in the resulting array. Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be 0. Return the resulting array. The returned array must be sorted in ascending order by id.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn merge_arrays(nums1: Vec<Vec<i32>>, nums2: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let mut result = Vec::new();
    let mut i = 0;
    let mut j = 0;
    while i < nums1.len() && j < nums2.len() {
      match nums1[i][0].cmp(&nums2[j][0]) {
        std::cmp::Ordering::Less => {
          result.push(nums1[i].clone());
          i += 1;
        }
        std::cmp::Ordering::Greater => {
          result.push(nums2[j].clone());
          j += 1;
        }
        std::cmp::Ordering::Equal => {
          result.push(vec![nums1[i][0], nums1[i][1] + nums2[j][1]]);
          i += 1;
          j += 1;
        }
      }
    }
    while i < nums1.len() { result.push(nums1[i].clone()); i += 1; }
    while j < nums2.len() { result.push(nums2[j].clone()); j += 1; }
    result
  }
}