← DiffPush

Peak element in matrix

Baseline Binary Search · 2D Arrays O(n log m) · O(1)

Ridge Detection on a Grid Elevation Model

A terrain model stores one elevation per cell, with no two adjacent cells equal, and surveyors need a summit - a cell higher than its four direct neighbours. Cells past the border count as a drop to -1. Binary searching the rows and comparing each row's best cell against its vertical neighbours finds a summit without scanning the whole grid.

Input: An m x n matrix mat with no two adjacent cells equal.

Output: A two-element array [row, col] of any peak cell, where the cell is strictly greater than its existing left, right, top and bottom neighbours.

Constraints

Examples

Example 1

Input: {"mat":[[1,4],[3,2]]}
Output: [0,1]
Both 4 and 3 exceed all their neighbours; this profile reports the position of 4.

Example 2

Input: {"mat":[[10,20,15],[21,30,14],[7,16,32]]}
Output: [1,1]
The cell 30 beats 20, 21, 14 and 16, so it is a valid summit.

Solve this in your browser →

Also on LeetCode ↗