![]() |
VOOZH | about |
Given a 2D matrix mat[][], identify any peak element within the matrix. An element is considered a peak if it is greater than or equal to its four immediate neighbors: top, bottom, left, and right. For corner and edge elements, any missing neighbors are treated as having a value of negative infinity.
A peak element is not necessarily the global maximum, it only needs to satisfy the condition relative to its adjacent elements. Multiple peak elements may exist, and the algorithm may return any one of them.
Examples:
Input: mat[][] = [[10, 20, 15],
[21, 30, 14],
[7, 16, 32]]
Output: [1, 1]
Explanation: The value at index {1, 1} is 30, which is greater than or equal to all its valid neighbors: Left = 21, Right = 14, Top = 20, Bottom = 16. So, it satisfies the peak condition. Alternatively, {2, 2} with value 32 also qualifies as a peak.Input: mat[][] = [[17, 7],
[11, 10]]
Output:[0, 0]
Explanation: The value at index {0 0} is 17. Its neighbors are: Right= 7, Bottom = 11. Since 17 is greater than or equal to both (and top and left are out of bounds), it qualifies as a peak element.
Table of Content
The idea is to iterate through each element in the matrix and check whether it is greater than or equal to all its valid neighbors (top, bottom, left, and right). The first such element found is returned as a peak.
1 1
This approach uses binary search on the columns of the matrix to efficiently find a peak element. In each iteration, it selects the middle column and identifies the row that contains the maximum element in that column. This element is then compared with its left and right neighbors.
If the current element is greater than or equal to both neighbors, it qualifies as a peak and its position is returned. Otherwise, the search continues in the direction of the larger neighbor (left or right), ensuring movement toward a region that must contain a peak. This process continues until a peak is found.
Step by Step Implementation:
1 1
Time Complexity: O(n × log m), for each of the log m iterations (binary search on columns), we scan all n rows to find the maximum in the current column.
Auxiliary Space: O(1), only a constant number of variables are used for tracking indices and comparisons.