Intermediate Level

Implement the searchSortedMatrix method that checks whether the target exists in a sorted matrix.

The input contains a sorted matrix, its rows and cols, and a target value.

Each row is sorted in ascending order, and the matrix can be searched like one sorted list when rows continue in increasing order.

Your task is to return true if the target exists in the matrix, otherwise return false.

Example 1

Input
matrix (int[][]) = [[1,3,5],[7,9,11]]
rows (int) = 2
cols (int) = 3
target (int) = 9
Returns (boolean) true

Example 2

Input
matrix (int[][]) = [[1,3,5],[7,9,11]]
rows (int) = 2
cols (int) = 3
target (int) = 4
Returns (boolean) false

Example 3

Input
matrix (int[][]) = [[1]]
rows (int) = 1
cols (int) = 1
target (int) = 1
Returns (boolean) true

Use binary search by treating the matrix as a flattened sorted array.

The virtual array has rows * cols positions. For any middle index, convert it back to matrix coordinates using row = mid / cols and col = mid % cols.

Compare the middle value with the target and move the search range just like normal binary search.

Pseudocode:

function searchSortedMatrix(matrix, rows, cols, target):
    left = 0
    right = rows * cols - 1
    while left <= right:
        mid = (left + right) / 2
        row = mid / cols
        col = mid % cols
        value = matrix[row][col]
        if value == target:
            return true
        else if value < target:
            left = mid + 1
        else:
            right = mid - 1
    return false
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.