Skip to content
Related Articles

Related Articles

Find a peak element in a 2D array

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 25 Nov, 2022
Improve Article
Save Article

An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. For example neighbors for A[i][j] are A[i-1][j], A[i+1][j], A[i][j-1] and A[i][j+1]. For corner elements, missing neighbors are considered of negative infinite value. The task is to find the index of the peak element.

Examples: 

Input: 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 neighbors are smaller or equal to it. Similarly, {2, 2} can also be picked as a peak.

Input: 10 7
          11 17
Output : 1, 1

Below are some facts about this problem: 

  1.  A Diagonal adjacent is not considered a neighbour. 
  2. A peak element is not necessarily the maximal element. 
  3. More than one such element can exist. 
  4. There is always a peak element. We can see this property by creating some matrices using pen and paper.

Method 1: (Brute Force) :

Iterate through all the elements of Matrix and check if it is greater/equal to all its neighbours. If yes, return the element.
Time Complexity: O(rows * columns) 
Auxiliary Space: O(1)

Method 2 : (Efficient):

This problem is mainly an extension of Find a peak element in 1D array. We apply similar Binary Search based solution here. 

  1. Consider mid column and find maximum element in it.
  2. Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’ and maximum element be at ‘mat[max_index][mid]’. 
  3. If max >= A[index][mid-1] & max >= A[index][mid+1], max is a peak, return max.
  4. If max < mat[max_index][mid-1], recur for left half of matrix.
  5. If max < mat[max_index][mid+1], recur for right half of matrix.

Below is the implementation of the above algorithm: 

C++




// Finding peak element in a 2D Array.
#include <bits/stdc++.h>
using namespace std;
 
// Finding peak element in a 2D Array.
#include <bits/stdc++.h>
using namespace std;
 
vector<int> findPeakGrid(vector<vector<int> >& mat)
{
 
    int stcol = 0,
        endcol
        = mat[0].size()
          - 1; // Starting point & end point of Search Space
 
    while (stcol <= endcol) { // Bin Search Condition
 
        int midcol = stcol + (endcol - stcol) / 2,
            ansrow = 0;
        // "ansrow" To keep the row number of global Peak
        // element of a column
 
        // Finding the row number of Global Peak element in
        // Mid Column.
        for (int r = 0; r < mat.size(); r++) {
            ansrow = mat[r][midcol] >= mat[ansrow][midcol]
                         ? r
                         : ansrow;
        }
 
        // Finding next Search space will be left or right
        bool valid_left = midcol - 1 >= stcol
                          && mat[ansrow][midcol - 1]
                                 > mat[ansrow][midcol];
        bool valid_right = midcol + 1 <= endcol
                           && mat[ansrow][midcol + 1]
                                  > mat[ansrow][midcol];
 
        // if we're at Peak Element
        if (!valid_left && !valid_right) {
            return { ansrow, midcol };
        }
 
        else if (valid_right)
            stcol = midcol
                    + 1; // move the search space in right
        else
            endcol = midcol
                     - 1; // move the search space in left
    }
 
    return { -1, -1 };
}
 
 
// Driver Code
int main()
{
    vector<vector<int> > arr = {{9, 8}, {2 ,6}};
 
    vector<int> result = findPeakGrid(arr);
 
    cout << "Peak element found at index: " << result[0] << "," << result[1] << endl;
    return 0;
}

Python3




# Finding peak element in a 2D Array.
def findPeakGrid(mat):
    stcol = 0
    endcol = len(mat[0]) - 1; # Starting po  end po of Search Space
 
    while (stcol <= endcol):  # Bin Search Condition
 
        midcol = stcol + int((endcol - stcol) / 2)
        ansrow = 0;
        # "ansrow" To keep the row number of global Peak
        # element of a column
 
        # Finding the row number of Global Peak element in
        # Mid Column.
        for r in range(len(mat)):
            ansrow = r if mat[r][midcol] >= mat[ansrow][midcol] else ansrow;
         
 
        # Finding next Search space will be left or right
        valid_left =  midcol - 1 >= stcol and mat[ansrow][midcol - 1] > mat[ansrow][midcol];
        valid_right = midcol + 1 <= endcol and mat[ansrow][midcol + 1] > mat[ansrow][midcol];
 
        # if we're at Peak Element
        if (not valid_left and not valid_right) :
            return [ ansrow, midcol ];
         
 
        elif (valid_right):
            stcol = midcol  + 1; # move the search space in right
        else:
            endcol = midcol  - 1; # move the search space in left
     
    return [ -1, -1 ];
 
# Driver Code
arr = [[9, 8], [2 ,6]];
result = findPeakGrid(arr);
print("Peak element found at index:", result)
 
# This code is contributed by phasing17.

Javascript




// Finding peak element in a 2D Array.
 
function findPeakGrid(mat)
{
 
    let stcol = 0,  endcol = mat[0].length - 1; // Starting po  end po of Search Space
 
    while (stcol <= endcol) { // Bin Search Condition
 
        let midcol = stcol + Math.floor((endcol - stcol) / 2), ansrow = 0;
        // "ansrow" To keep the row number of global Peak
        // element of a column
 
        // Finding the row number of Global Peak element in
        // Mid Column.
        for (let r = 0; r < mat.length; r++) {
            ansrow = mat[r][midcol] >= mat[ansrow][midcol] ? r : ansrow;
        }
 
        // Finding next Search space will be left or right
        let valid_left =  midcol - 1 >= stcol && mat[ansrow][midcol - 1] > mat[ansrow][midcol];
        let valid_right = midcol + 1 <= endcol && mat[ansrow][midcol + 1] > mat[ansrow][midcol];
 
        // if we're at Peak Element
        if (!valid_left && !valid_right) {
            return [ ansrow, midcol ];
        }
 
        else if (valid_right)
            stcol = midcol  + 1; // move the search space in right
        else
            endcol = midcol  - 1; // move the search space in left
    }
 
    return [ -1, -1 ];
}
 
 
// Driver Code
let arr = [[9, 8], [2 ,6]];
 
let result = findPeakGrid(arr);
 
console.log("Peak element found at index: " + result[0] + "," + result[1])
 
// This code is contributed by phasing14.

Output

Peak element found at index: 0,0

Time Complexity : O(rows * log(columns)). We recur for half the number of columns. In every recursive call, we linearly search for the maximum in the current mid column.
Auxiliary Space: O(columns/2) for Recursion Call Stack 

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!