Given a 0-indexed n x m matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the array [i, j].A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbours to the left, right, top, and bottom.
Assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.
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 a peak element because all its neighbours are smaller or equal to it. Similarly, {2, 2} can also be picked as a peak.
Input: mat=[[10, 7], [11, 17]]
Output : [1, 1]
Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
Input: mat=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Helper function to find the index of the row
with the maximum element in a given column*/
int maxElement(vector<vector<int>>& arr, int col) {
int n = arr.size();
int max_val = INT_MIN;
int index = -1;
/* Iterate through each row to find the
maximum element in the specified column*/
for (int i = 0; i < n; i++) {
if (arr[i][col] > max_val) {
max_val = arr[i][col];
index = i;
}
}
// Return the index
return index;
}
/* Function to find a peak element in
the 2D matrix using binary search */
vector<int> findPeakGrid(vector<vector<int>>& arr) {
int n = arr.size();
int m = arr[0].size();
/* Initialize the lower bound for
and upper bound for binary search */
int low = 0;
int high = m - 1;
// Perform binary search on columns
while (low <= high) {
int mid = (low + high) / 2;
/* Find the index of the row with the
maximum element in the middle column*/
int row = maxElement(arr, mid);
/* Determine the elements to left and
right of middle element in the found row */
int left = mid - 1 >= 0 ? arr[row][mid - 1] : INT_MIN;
int right = mid + 1 < m ? arr[row][mid + 1] : INT_MIN;
/* Check if the middle element
is greater than its neighbors */
if (arr[row][mid] > left && arr[row][mid] > right) {
return {row, mid};
}
else if (left > arr[row][mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
// Return {-1, -1} if no peak element is found
return {-1, -1};
}
};
int main() {
// Example usage
vector<vector<int>> mat = {
{4, 2, 5, 1, 4, 5},
{2, 9, 3, 2, 3, 2},
{1, 7, 6, 0, 1, 3},
{3, 6, 2, 3, 7, 2}
};
// Create an instance of Solution class
Solution sol;
// Call findPeakGridfunction and print the result
vector<int> peak = sol.findPeakGrid(mat);
cout << "The row of peak element is " << peak[0] << " and column of the peak element is " << peak[1] << endl;
return 0;
}
import java.util.*;
class Solution {
/* Helper function to find the index of the row
with the maximum element in a given column*/
public int maxElement(int[][] arr, int col) {
int n = arr.length;
int max = Integer.MIN_VALUE;
int index = -1;
/* Iterate through each row to find the
maximum element in the specified column*/
for (int i = 0; i < n; i++) {
if (arr[i][col] > max) {
max = arr[i][col];
index = i;
}
}
//Return the index
return index;
}
/* Function to find a peak element in
the 2D matrix using binary search */
public int[] findPeakGrid(int[][] arr) {
int n = arr.length;
int m = arr[0].length;
/* Initialize the lower bound for
and upper bound for binary search */
int low = 0;
int high = m - 1;
// Perform binary search on columns
while (low <= high) {
int mid = (low + high) / 2;
/* Find the index of the row with the
maximum element in the middle column*/
int row = maxElement(arr, mid);
/* Determine the elements to left and
right of middle element in the found row */
int left = mid - 1 >= 0 ? arr[row][mid - 1] : Integer.MIN_VALUE;
int right = mid + 1 < m ? arr[row][mid + 1] : Integer.MIN_VALUE;
/* Check if the middle element
is greater than its neighbors */
if (arr[row][mid] > left && arr[row][mid] > right) {
return new int[]{row,mid};
}
else if (left > arr[row][mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
// Return -1 if no peak element is found
return new int[]{-1,-1};
}
public static void main(String[] args) {
// Example usage
int[][] mat = {
{4, 2, 5, 1, 4, 5},
{2, 9, 3, 2, 3, 2},
{1, 7, 6, 0, 1, 3},
{3, 6, 2, 3, 7, 2}
};
//Create an instance of Solution class
Solution sol = new Solution();
// Call findPeakGridfunction and print the result
System.out.println("The row of peak element is "+sol.findPeakGrid(mat)[0]+" and column of the peak element is "+sol.findPeakGrid(mat)[1]);
}
}
class Solution:
"""Helper function to find the index of the row
with the maximum element in a given column"""
def maxElement(self, arr, col):
n = len(arr)
max_val = float('-inf')
index = -1
"""Iterate through each row to find the
maximum element in the specified column"""
for i in range(n):
if arr[i][col] > max_val:
max_val = arr[i][col]
index = i
# Return the index
return index
"""Function to find a peak element in
the 2D matrix using binary search """
def findPeakGrid(self, arr):
n = len(arr)
m = len(arr[0])
"""Initialize the lower bound for
and upper bound for binary search"""
low = 0
high = m - 1
# Perform binary search on columns
while low <= high:
mid = (low + high) // 2
"""Find the index of the row with the
maximum element in the middle column"""
row = self.maxElement(arr, mid)
""" Determine the elements to left and
right of middle element in the found row """
left = arr[row][mid - 1] if mid - 1 >= 0 else float('-inf')
right = arr[row][mid + 1] if mid + 1 < m else float('-inf')
""" Check if the middle element
is greater than its neighbors """
if arr[row][mid] > left and arr[row][mid] > right:
return [row, mid]
elif left > arr[row][mid]:
high = mid - 1
else:
low = mid + 1
# Return [-1, -1] if no peak element is found
return [-1, -1]
mat = [
[4, 2, 5, 1, 4, 5],
[2, 9, 3, 2, 3, 2],
[1, 7, 6, 0, 1, 3],
[3, 6, 2, 3, 7, 2]
]
#Create an instance of Solution class
sol = Solution()
# Call findPeakGrid function and print the result
peak = sol.findPeakGrid(mat)
print(f"The row of peak element is {peak[0]} and column of the peak element is {peak[1]}")
class Solution {
/*Helper function to find the index of the row
with the maximum element in a given column*/
maxElement(arr, col) {
let n = arr.length;
let max_val = Number.MIN_SAFE_INTEGER;
let index = -1;
/*Iterate through each row to find the
maximum element in the specified column*/
for (let i = 0; i < n; i++) {
if (arr[i][col] > max_val) {
max_val = arr[i][col];
index = i;
}
}
// Return the index
return index;
}
/*Function to find a peak element in
the 2D matrix using binary search */
findPeakGrid(arr) {
let n = arr.length;
let m = arr[0].length;
/*Initialize the lower bound for
and upper bound for binary search */
let low = 0;
let high = m - 1;
// Perform binary search on columns
while (low <= high) {
let mid = Math.floor((low + high) / 2);
/*Find the index of the row with the
maximum element in the middle column*/
let row = this.maxElement(arr, mid);
/*Determine the elements to left and
right of middle element in the found row */
let left = mid - 1 >= 0 ? arr[row][mid - 1] : Number.MIN_SAFE_INTEGER;
let right = mid + 1 < m ? arr[row][mid + 1] : Number.MIN_SAFE_INTEGER;
/*Check if the middle element
is greater than its neighbors */
if (arr[row][mid] > left && arr[row][mid] > right) {
return [row, mid];
}
else if (left > arr[row][mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
// Return [-1, -1] if no peak element is found
return [-1, -1];
}
}
// Example usage
let mat = [
[4, 2, 5, 1, 4, 5],
[2, 9, 3, 2, 3, 2],
[1, 7, 6, 0, 1, 3],
[3, 6, 2, 3, 7, 2]
];
//Create an instance of Solution class
let sol = new Solution();
// Call findPeakElement function and print the result
let peak = sol.findPeakGrid(mat);
console.log(`The row of peak element is ${peak[0]} and column of the peak element is ${peak[1]}`);
Q: How is the global maximum in a column or row found efficiently?
A: Traverse the column or row once to find the index of the largest element (O(n) or O(m)), which is much faster than scanning the entire matrix.
Q: What if the peak lies at the boundary of the matrix?
A: The outer perimeter of −1 ensures that any element on the matrix boundary can be a peak if it is larger than its neighbors.
Q: How would you handle non-strict peaks (i.e., ≥ neighbors)?
A: Modify the comparison condition to include equality. The algorithm remains the same, but more elements may qualify as peaks.
Q: How would you find all peaks in the matrix?
A: A brute-force approach iterating over all elements is required. However, for large matrices, you can parallelize this computation or use divide-and-conquer techniques to find peaks in chunks.