Search a 2D Matrix

Medium · Binary Search · Array · Binary Search · Matrix

Problem

You are given an m x n integer matrix with two properties: each row is sorted in non-decreasing order, and the first value of every row is greater than the last value of the row above it. Read row by row, the matrix is one sorted list.

Given an integer target, return True if it occurs in the matrix, otherwise False. Your solution must run in O(log(m · n)) time.

Examples

Input: matrix = [[2,4,7],[10,11,15],[20,26,31]], target = 11
Output: true

11 is the middle element of the flattened list.

Input: matrix = [[2,4,7],[10,11,15],[20,26,31]], target = 8
Output: false

8 would fall between 7 and 10 but is not present.

Input: matrix = [[1,3,5,7,9]], target = 7
Output: true

A single row is just a sorted list.

Constraints

Approaches

Follow-up

If rows are sorted and columns are sorted but a row may start below the end of the previous one, the matrix is no longer one sorted list. Then start at the top-right corner: each comparison discards a row or a column, for O(m + n).

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…