Merge Keyed 2D Arrays
Problem statement
Merge the two integer arrays first and second.
For this exercise, each row is a pair [key, value]. Each input is sorted by strictly increasing key, so a key appears at most once in each input.
- If a key appears in both arrays, add its values.
- If it appears in just one array, keep its value.
- Return one row for every distinct key, in increasing key order.
Either input may be empty.
Function
merge2DArrays(first: int[][], second: int[][]) → int[][]Examples
Example 1
first = [[1,4],[3,2]]second = [[2,7],[3,5]]return = [[1,4],[2,7],[3,7]]Key 3 appears in both arrays, so its values sum to 7. Other keys retain their values.
Example 2
first = []second = [[5,9]]return = [[5,9]]An empty first array leaves the second array unchanged.
Example 3
first = [[1,2]]second = [[1,3]]return = [[1,5]]Equal keys produce one merged row, rather than two rows.
Constraints
- For this exercise, assume
0 <= first.length, second.length <= 100. - Each row contains exactly two integers.
- Keys are between
1and1000; input values are between1and10000. - Keys are strictly increasing within each input.