Search a 2D Matrix
Updated
Problem statement
You are given an m x n integer matrix matrix with two properties:
- Each row is sorted in non-decreasing order (left to right).
- The first value of each row is greater than the last value of the row above it.
Read row by row, the whole matrix is therefore one sorted list. Given an integer target, return true if target appears anywhere in matrix, and false otherwise.
Aim for O(log(m * n)) time.
Function
searchMatrix(matrix: int[][], target: int) → booleanExamples
Example 1
matrix = [[1,4,7,9],[12,15,18,20],[25,31,40,52]]target = 18return = true18 is in the middle row, at column 2.
Example 2
matrix = [[1,4,7,9],[12,15,18,20],[25,31,40,52]]target = 21return = falseThe middle row ends at 20 and the last row starts at 25, so 21 would have to sit between them. It is not in the matrix.
Example 3
matrix = [[-3,-3,0],[2,6,6]]target = 7return = falseValues may repeat inside a row. 7 is larger than every value, the largest being 6, so it is not there.
Example 4
matrix = [[2],[4],[8]]target = 4return = trueEach row has one value. 4 is the only value of the middle row.
Example 5
matrix = [[5]]target = 5return = trueThe single cell holds the target.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-104 <= matrix[i][j], target <= 104matrix[i][j] <= matrix[i][j + 1]matrix[i][0] > matrix[i - 1][n - 1]for everyi >= 1
More WhatNot Onsite Interview questions
- User Journey PathsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Detect Blocked Chat PhrasesPHONE SCREEN · ONSITE INTERVIEW · Seen Jun 2026
- Minimum Remove to Make Valid ParenthesesONSITE INTERVIEW · Seen Dec 2024
- Number of IslandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2024
- Merge Two Sorted ListsONSITE INTERVIEW · Seen Jul 2024
- Number of Submatrices That Sum to TargetONSITE INTERVIEW · Seen Jul 2024
- Parse and Store Log RecordsONSITE INTERVIEW · Seen Oct 2023
- Room Occupancy at Query TimesONSITE INTERVIEW · Seen Oct 2023
- K Smallest Values in a StreamPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2022
- Average Purchase PriceONSITE INTERVIEW · Seen Sep 2022
Similar questions at other companies
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- Row with Maximum OnesAmazon · ONSITE INTERVIEW
- Search a Row-Major Sorted MatrixMotive · ONSITE INTERVIEWMotive interview questions
- Search a 2D Matrix IIBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Grid Path With the Most ClearanceDocuSign · OADocuSign interview questions
- Largest Square Sub-Grid Within a Sum LimitC3.ai · OAC3.ai interview questions
- Server SelectionAirbnb · OAAirbnb interview questions
- Number of IslandsIntuit · ONSITE INTERVIEWIntuit interview questions
- Rotting OrangesSalesforce · ONSITE INTERVIEWSalesforce interview questions
- First and Last Target Position in a Mountain ArrayGoogle · ONSITE INTERVIEWGoogle interview questions