Merge Two 2D Arrays by Summing Values

🏠 ⬅️ ➡️

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 its value in that array is considered to be 0.

Return the resulting array. The returned array must be sorted in ascending order by id.

Example 1:

Input: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] Output: [[1,6],[2,3],[3,2],[4,6]] Explanation: The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6.

Example 2:

Input: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] Output: [[1,3],[2,4],[3,6],[4,3],[5,5]] Explanation: There are no common ids, so we just include each id with its value in the resulting list.

Constraints:

  • 1 <= nums1.length, nums2.length <= 200
  • nums1[i].length == nums2[j].length == 2
  • 1 <= idi, vali <= 1000
  • Both arrays contain unique ids.
  • Both arrays are in strictly ascending order by id.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    integer, parameter :: n = 3
    integer, dimension(n) :: nums1 = reshape([1, 2, 4], shape(nums1))
    integer, dimension(n) :: nums2 = reshape([1, 3, 4], shape(nums2))
    integer, dimension(:), allocatable :: result

    allocate(result(size(nums1) + size(nums2)))

    call merge_sorted_arrays(nums1, nums2, result)

    write(*,*) 'Result: ', result

contains

subroutine merge_sorted_arrays(nums1, nums2, result)
    implicit none
    integer, dimension(:, :), intent(in) :: nums1
    integer, dimension(:, :), intent(in) :: nums2
    integer, dimension(:), intent(out) :: result

    integer :: i, j, k

    i = 1
    j = 1
    k = 1

    do while (i <= ubound(nums1, dim=1) .and. j <= ubound(nums2, dim=1))
        if (nums1(i, 1) < nums2(j, 1)) then
            result(k) = nums1(i, 1)
            result(k+1) = nums1(i, 2)
            i = i + 1
        else if (nums1(i, 1) > nums2(j, 1)) then
            result(k) = nums2(j, 1)
            result(k+1) = nums2(j, 2)
            j = j + 1
        else
            result(k) = nums1(i, 1)
            result(k+1) = nums1(i, 2) + nums2(j, 2)
            i = i + 1
            j = j + 1
        end if
        k = k + 2
    end do

    do while (i <= ubound(nums1, dim=1))
        result(k) = nums1(i, 1)
        result(k+1) = nums1(i, 2)
        i = i + 1
        k = k + 2
    end do

    do while (j <= ubound(nums2, dim=1))
        result(k) = nums2(j, 1)
        result(k+1) = nums2(j, 2)
        j = j + 1
        k = k + 2
    end do
end subroutine merge_sorted_arrays

end program main
Compiled
Executed
Correct
module merge_sorted_arrays
    implicit none
    private
    public :: merge_sorted_arrays
contains
    subroutine merge_sorted_arrays(nums1, nums2, result)
        implicit none
        integer, intent(in) :: nums1(:, :)
        integer, intent(in) :: nums2(:, :)
        integer, allocatable, intent(out) :: result(:, :)
        integer :: i, j, k
        integer :: id1, id2, val1, val2
        allocate(result(size(nums1, 1) + size(nums2, 1), 2))
        i = 1
        j = 1
        k = 1
        do while (i <= size(nums1, 1) .and. j <= size(nums2, 1))
            id1 = nums1(i, 1)
            val1 = nums1(i, 2)
            id2 = nums2(j, 1)
            val2 = nums2(j, 2)
            if (id1 < id2) then
                result(k, 1) = id1
                result(k, 2) = val1
                i = i + 1
            else if (id1 > id2) then
                result(k, 1) = id2
                result(k, 2) = val2
                j = j + 1
            else
                result(k, 1) = id1
                result(k, 2) = val1 + val2
                i = i + 1
                j = j + 1
            end if
            k = k + 1
        end do
        do while (i <= size(nums1, 1))
            result(k, 1) = nums1(i, 1)
            result(k, 2) = nums1(i, 2)
            i = i + 1
            k = k + 1
        end do
        do while (j <= size(nums2, 1))
            result(k, 1) = nums2(j, 1)
            result(k, 2) = nums2(j, 2)
            j = j + 1
            k = k + 1
        end do
    end subroutine merge_sorted_arrays
end module merge_sorted_arrays

program test_merge_sorted_arrays
    use merge_sorted_arrays
    implicit none
    integer, allocatable :: nums1(:, :)
    integer, allocatable :: nums2(:, :)
    integer, allocatable :: result(:, :)
    allocate(nums1(3, 2))
    nums1 = reshape([1, 2, 2, 3, 4, 5], shape(nums1))
    allocate(nums2(3, 2))
    nums2 = reshape([1, 4, 3, 2, 4, 1], shape(nums2))
    call merge_sorted_arrays(nums1, nums2, result)
    write(*, "(2(A, I0), A, I0)") "Result: ", result(1, 1), " ", result(1, 2), &
        " "
    write(*, "(2(A, I0), A, I0)") "Result: ", result(2, 1), " ", result(2, 2), &
        " "
    write(*, "(2(A, I0), A, I0)") "Result: ", result(3, 1), " ", result(3, 2), &
        " "
    write(*, "(2(A, I0), A, I0)") "Result: ", result(4, 1), " ", result(4, 2), &
        " "
    write(*, "(2(A, I0), A, I0)") "Result: ", result(5, 1), " ", result(5, 2), &
        " "
    deallocate(nums1, nums2, result)
    allocate(nums1(2, 2))
    nums1 = reshape([2, 4, 3, 6], shape(nums1))
    allocate(nums2(2,
🌐 Data from online sources
def merge_nums(nums1, nums2):
    merged_map = {}
    merged = []

    for id_val_pair in nums1:
        id_, val_ = id_val_pair
        if id_ not in merged_map:
            merged_map[id_] = val_
        else:
            merged_map[id_] += val_

    for id_val_pair in nums2:
        id_, val_ = id_val_pair
        if id_ not in merged_map:
            merged_map[id_] = val_
        else:
            merged_map[id_] += val_

    for id_, val_ in merged_map.items():
        merged.append([id_, val_])

    return merged
  1. Create an empty map merged_map and an empty list merged that will store the final result.
  2. Iterate through both nums1 and nums2, and for each id and value pair: i. Check if the id exists in merged_map. If it does, add the value to the existing value in merged_map. ii. If the id does not exist in merged_map, insert the id into the map and set its value to the current value.
  3. After both arrays have been processed, iterate through merged_map and append each id-value pair as a list to the merged list.
  4. Return the merged list.
🌐 Data from online sources
#include <vector>
#include <map>

std::vector<std::vector<int>> merge_nums(std::vector<std::vector<int>>& nums1, std::vector<std::vector<int>>& nums2) {
    std::map<int, int> merged_map;
    std::vector<std::vector<int>> merged;

    for (const auto& p : nums1) {
        merged_map[p[0]] += p[1];
    }

    for (const auto& p : nums2) {
        merged_map[p[0]] += p[1];
    }

    for (const auto& p : merged_map) {
        merged.push_back({p.first, p.second});
    }

    return merged;
}
  1. Create an empty map merged_map and an empty list merged that will store the final result.
  2. Iterate through both nums1 and nums2, and for each id and value pair: i. Check if the id exists in merged_map. If it does, add the value to the existing value in merged_map. ii. If the id does not exist in merged_map, insert the id into the map and set its value to the current value.
  3. After both arrays have been processed, iterate through merged_map and append each id-value pair as a list to the merged list.
  4. Return the merged list.