Problem · Array
K Smallest Elements from Sorted Arrays
Learn this problemProblem statement
You are given an array of integer arrays arrays. Each inner array is sorted in nondecreasing order. Return the k smallest values across all inner arrays in nondecreasing order.
Duplicate values occupy separate positions and must be retained. An empty inner array contributes no values. When k is zero, return an empty array.
Do not insert every input value into a heap. Maintain at most one current candidate from each nonempty inner array.
Function
kSmallestElements(arrays: int[][], k: int) → int[]Examples
Example 1
arrays = [[1,4,7],[2,5],[3,6,9]]k = 5return = [1,2,3,4,5]The first five values in the merged order are 1, 2, 3, 4, 5.
Example 2
arrays = [[],[-3,-1,2],[-3,4]]k = 4return = [-3,-3,-1,2]Both occurrences of -3 are retained, and the empty array is ignored.
Constraints
1 <= arrays.length <= 100000 <= arrays[i].length- The total number of values across all arrays is at most
200000. - Each inner array is sorted in nondecreasing order.
-2147483648 <= arrays[i][j] <= 21474836470 <= k <=the total number of values.