Intermediate Level

Implement the mergeKSortedArraysLength method that returns the total length after merging k sorted arrays.

The input arrays represents multiple sorted arrays stored as a two-dimensional matrix, along with rows and cols.

Your task is to return the length of the final merged array after all sorted arrays are combined.

The method does not need to return the merged values. It only returns how many elements the merged result would contain. For example, three arrays with two values each produce a merged length of 6.

Example 1

Input
arrays (int[][]) = [[1,4],[2,5],[3,6]]
rows (int) = 3
cols (int) = 2
Returns (int) 6

Example 2

Input
arrays (int[][]) = [[1],[2],[3]]
rows (int) = 3
cols (int) = 1
Returns (int) 3

Example 3

Input
arrays (int[][]) = []
rows (int) = 0
cols (int) = 0
Returns (int) 0

Since all elements from every row remain present after merging, the merged length is simply the total number of elements.

If there are no rows or no columns, the merged length is 0. Otherwise, multiply rows by cols.

Actual k-way merging would be needed if the problem asked for the merged array, but for length only, counting the available values is enough.

Pseudocode:

function mergeKSortedArraysLength(arrays, rows, cols):
    if rows == 0 or cols == 0:
        return 0
    return rows * cols
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.