DevPath

← All problems

Search a Sorted Matrix

Medium matrix · binary-search

Description

Rows and columns are sorted ascending. Return true if target is present.

Constraints

1 <= rows, cols <= 300

Examples

Input: matrix = [[1,4,7],[2,5,8],[3,6,9]], target = 5

Output: true

Hints (1)
  • Start at the top-right corner and move left or down.

Solutions

Staircase from top-right. · Time O(rows+cols) · Space O(1)

func searchMatrix(matrix [][]int, target int) bool {
    r, c := 0, len(matrix[0])-1
    for r < len(matrix) && c >= 0 {
        if matrix[r][c] == target {
            return true
        }
        if matrix[r][c] > target {
            c--
        } else {
            r++
        }
    }
    return false
}

Create a free account to submit solutions, track progress and save problems.

Create account