Skip to contentKEEP THE CRAFTTHE SANCTUARY

Search a Row-and-Column Sorted Matrix

Search a matrix whose rows and columns are each sorted, by walking from the top-right corner.

The problem

Implement Solution.searchMatrix(matrix, target). matrix has between 1 and 300 rows and between 1 and 300 columns. Every row increases from left to right and every column increases from top to bottom, but a row may start below the end of the row above it, so reading the rows one after another is not sorted. Return True if target is in matrix and False otherwise. Your solution must run in O(rows + cols) time.

Starter code

class Solution:
    def searchMatrix(self, matrix, target):
        pass

Public examples

  1. matrix = [[-5, -1, 3], [0, 2, 6], [4, 7, 9]], target = 7givesTrue
  2. matrix = [[-4], [0], [3]], target = 0givesTrue
  3. matrix = [[1, 4, 8], [2, 5, 9]], target = 6givesFalse

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.