Problem Description
Given a 0-indexed m x n matrix where no two adjacent cells are equal and the matrix is implicitly surrounded by an outer perimeter with the value -1, find any peak element. A peak element is defined as one that is strictly greater than its adjacent neighbors (up, down, left, and right). Return the coordinates [i, j] of any peak element. The solution must run in O(m log(n)) or O(n log(m)) time.
Key Insights
- The problem can be solved using a binary search approach along one of the dimensions (rows or columns).
- For a chosen mid row (or column), find the global maximum element in that row.
- By comparing the maximum element with its top and bottom neighbors, decide in which half to continue the search.
- Because no two adjacent cells are equal and considering the -1 border, a peak is guaranteed to be found.
Space and Time Complexity
Time Complexity: O(m log(n)) (if binary search is performed on rows) or O(n log(m)) (if binary search is performed on columns) Space Complexity: O(1) (in-place with only constant extra space)
Solution
We use a binary search based algorithm on rows. At each step, we choose a mid row and scan that row to find the maximum element (its column index). Then, we compare this element with its top and bottom neighbors (if available). If the element is greater than both, it's a peak. Otherwise, if the neighbor above or below is greater, we continue the search in that direction. This guarantees that we converge to a peak element. The main trick is performing a binary search on one dimension while scanning the other dimension completely to find a local maximum, thus reducing the overall search space.