Proficient Level

Implement the smallestRangeFromListsWidth method that returns the width of the smallest range covering all sorted lists.

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

In this simplified version, each row contributes its first value as the representative value. Your task is to return the width between the smallest and largest representative values.

The width is calculated as maximum first value - minimum first value. For example, from first values 4, 0, and 5, the width is 5.

Example 1

Input
lists (int[][]) = [[4,10],[0,9],[5,18]]
rows (int) = 3
cols (int) = 2
Returns (int) 5

Example 2

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

Example 3

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

Check the first value of every available row.

Keep track of the smallest and largest first values. The required width is the difference between these two values.

If there are no rows or no columns, there is no valid range, so return 0.

Pseudocode:

function smallestRangeFromListsWidth(lists, rows, cols):
    if rows == 0 or cols == 0:
        return 0
    minValue = lists[0][0]
    maxValue = lists[0][0]
    for i from 1 to rows - 1:
        value = lists[i][0]
        if value < minValue:
            minValue = value
        if value > maxValue:
            maxValue = value
    return maxValue - minValue
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.