LeetCode in Kotlin

2570. Merge Two 2D Arrays by Summing Values

Easy

You are given two 2D integer arrays nums1 and nums2.

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:

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:

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:

Solution

class Solution {
    fun mergeArrays(nums1: Array<IntArray>, nums2: Array<IntArray>): Array<IntArray> {
        var p1 = 0
        var p2 = 0
        val result = mutableListOf<IntArray>()
        while (p1 < nums1.size) {
            if (p2 == nums2.size || nums1[p1][0] < nums2[p2][0]) {
                result.add(intArrayOf(nums1[p1][0], nums1[p1][1]))
                p1++
            } else if (nums1[p1][0] > nums2[p2][0]) {
                result.add(intArrayOf(nums2[p2][0], nums2[p2][1]))
                p2++
            } else {
                result.add(intArrayOf(nums1[p1][0], nums1[p1][1] + nums2[p2][1]))
                p1++
                p2++
            }
        }
        // Merge leftovers from nums2
        while (p2 < nums2.size) {
            result.add(intArrayOf(nums2[p2][0], nums2[p2][1]))
            p2++
        }
        return result.toTypedArray()
    }
}