oneby7

Binary Search Searching a matrix

257. Find a Peak Element II

Medium

You are given a grid of integers mat with m rows and n columns. Return the position of any peak in it as [row, col]. Rows and columns are counted from 0.

A cell is a peak when it is larger than each of its neighbours: the cells directly above, below, left and right of it. Diagonal cells are not neighbours. Every position outside the grid counts as −∞, so a cell on the edge only has to be larger than the neighbours it has.

A grid can have several peaks, and any of them is a correct answer. The result shows a peak when the cell you return is one. Otherwise it says what is wrong, such as [1,2] is not a peak or [0,5] is outside the grid.

Aim for O(m log n) or O(n log m) time.

Example 1

493862751111012

Input: mat = [[4, 9, 3, 8], [6, 2, 7, 5], [1, 11, 10, 12]]

Output: [1,0]

Explanation: 6 is larger than 4 above it, 1 below it and 2 on its right, and the left side is outside the grid. The cells holding 9, 8, 11 and 12 are peaks too, and any of the five is correct.

Example 2

-7-3-12-5

Input: mat = [[-7], [-3], [-12], [-5]]

Output: [1,0]

Explanation: Every value is negative. −3 is larger than −7 above it and −12 below it. −5 at the bottom is a peak too: it is larger than −12, and the position below it is outside the grid.

Example 3

−10⁹

Input: mat = [[-1000000000]]

Output: [0,0]

Explanation: A grid of one cell has no neighbours, so that cell is a peak, even though it holds the smallest value allowed.

Check your understanding

Work out the answer for this input before you write any code.

mat = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

Constraints

  • m == mat.length, n == mat[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • -109 ≤ mat[i][j] ≤ 109
  • No two neighbouring cells hold equal values.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.