The Wayback Machine - https://web.archive.org/web/20240814193852/https://www.geeksforgeeks.org/find-peak-element-2d-array/
Open In App

Find the Peak Element in a 2D Array/Matrix

Last Updated : 09 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a 2D Array/Matrix, the task is to find the Peak element.

An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. 

  • A Diagonal adjacent is not considered a neighbour. 
  • A peak element is not necessarily the maximal element. 
  • More than one such element can exist. 
  • There is always a peak element. 
  • For corner elements, missing neighbors are considered of negative infinite value. 

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

Naive Approach to Find Peak Element in Matrix

Iterate through all the elements of the Matrix and check if it is greater/equal to all its neighbors. If yes, return the element.

C++




// Finding peak element in a 2D Array.
#include <bits/stdc++.h>
using namespace std;
 
vector<int> findPeakGrid(vector<vector<int> > arr)
{
    vector<int> result;
    int row = arr.size();
    int column = arr[0].size();
 
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            // checking with top element
            if (i > 0)
                if (arr[i][j] < arr[i - 1][j])
                    continue;
            // checking with right element
            if (j < column - 1)
                if (arr[i][j] < arr[i][j + 1])
                    continue;
            // checking with bottom element
            if (i < row - 1)
                if (arr[i][j] < arr[i + 1][j])
                    continue;
            // checking with left element
            if (j > 0)
                if (arr[i][j] < arr[i][j - 1])
                    continue;
 
            result.push_back(i);
            result.push_back(j);
            break;
        }
    }
    return result;
}
 
// 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;
}
 
// This code is contributed by Yash
// Agarwal(yashagarwal2852002)


Java




import java.util.*;
 
public class Main {
    public static List<Integer> findPeakGrid(int[][] arr)
    {
        List<Integer> result = new ArrayList<>();
        int row = arr.length;
        int column = arr[0].length;
 
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                // checking with top element
                if (i > 0)
                    if (arr[i][j] < arr[i - 1][j])
                        continue;
                // checking with right element
                if (j < column - 1)
                    if (arr[i][j] < arr[i][j + 1])
                        continue;
                // checking with bottom element
                if (i < row - 1)
                    if (arr[i][j] < arr[i + 1][j])
                        continue;
                // checking with left element
                if (j > 0)
                    if (arr[i][j] < arr[i][j - 1])
                        continue;
 
                result.add(i);
                result.add(j);
                break;
            }
        }
        return result;
    }
 
    public static void main(String[] args)
    {
        int[][] arr = { { 9, 8 }, { 2, 6 } };
        List<Integer> result = findPeakGrid(arr);
        System.out.println("Peak element found at index: "
                           + result.get(0) + ", "
                           + result.get(1));
    }
}


Python3




# Finding a peak element in 2D array
def findPeakGrid(arr):
    result = []
    row = len(arr)
    column = len(arr[0])
 
    for i in range(row):
        for j in range(column):
 
            # checking with top element
            if i > 0:
                if arr[i][j] < arr[i-1][j]:
                    continue
            # checking with right element
            if j < column-1:
                if arr[i][j] < arr[i][j+1]:
                    continue
            # checking with bottom element
            if i < row-1:
                if arr[i][j] < arr[i+1][j]:
                    continue
            # checking with left element
            if j > 0:
                if arr[i][j] < arr[i][j-1]:
                    continue
 
            result.append(i)
            result.append(j)
            break
 
    return result
 
 
# driver code
arr = [[9, 8], [2, 6]]
result = findPeakGrid(arr)
print("Peak element found at index:", result)
 
# This code is constributed by phasing17


C#




// C# code to find peak element in a 2D array
using System;
using System.Collections.Generic;
class GFG {
    static int[] findPeakGrid(int[][] arr)
    {
        int[] result = new int[2];
        int row = arr.Length;
        int column = arr[0].Length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
 
                // checking with top element
                if (i > 0)
                    if (arr[i][j] < arr[i - 1][j])
                        continue;
 
                // checking with right element
                if (j < column - 1)
                    if (arr[i][j] < arr[i][j + 1])
                        continue;
 
                // checking with bottom element
                if (i < row - 1)
                    if (arr[i][j] < arr[i + 1][j])
                        continue;
 
                // checking with left element
                if (j > 0)
                    if (arr[i][j] < arr[i][j - 1])
                        continue;
                result[0] = i;
                result[1] = j;
                break;
            }
        }
        return result;
    }
 
    // driver code to test above function
    public static void Main()
    {
        int[][] arr = { new[] { 9, 8 }, new[] { 2, 6 } };
        int[] result = findPeakGrid(arr);
        Console.WriteLine("Peak element found at index: "
                          + result[0] + "," + result[1]);
    }
}
 
// THIS CODE IS CONTRIBUTED BY YASH
// AGARWAL(YASHAGAWRAL2852002)


Javascript




// Finding a peak element in 2D array
function findPeakGrid(arr){
    let result = [];
    let row = arr.length;
    let column = arr[0].length;
     
    for(let i = 0; i<row; i++){
        for(let j = 0; j<column; j++){
            // checking with top element
            if(i > 0)
                if(arr[i][j] < arr[i-1][j]) continue;
            // checking with right element
            if(j < column-1)
                if(arr[i][j] < arr[i][j+1]) continue;
            // checking with bottom element
            if(i < row-1)
                if(arr[i][j] < arr[i+1][j]) continue;
            // checking with left element
            if(j > 0)
                if(arr[i][j] < arr[i][j-1])  continue;
             
            result.push(i);
            result.push(j);
            break;
        }
    }
    return result;
}
 
// 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 KIRTI AGARWAL(KIRTIAGARWAL23121999)


Output

Peak element found at index: 0, 0

Time Complexity: O(rows * columns) 
Auxiliary Space: O(1)

Efficient Approach to Find Peak Element in Matrix

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

  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;
}


Java




// Finding peak element in a 2D Array.
import java.util.*;
 
public class GFG {
 
    static int[] findPeakGrid(int[][] mat)
    {
 
        // Starting point & end point of Search Space
        int stcol = 0, endcol = mat[0].length - 1;
 
        // Bin Search Condition
        while (stcol <= endcol) {
 
            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.length; r++) {
                ansrow
                    = mat[r][midcol] >= mat[ansrow][midcol]
                          ? r
                          : ansrow;
            }
 
            // Finding next Search space will be left or
            // right
            boolean valid_left
                = midcol - 1 >= stcol
                  && mat[ansrow][midcol - 1]
                         > mat[ansrow][midcol];
            boolean valid_right
                = midcol + 1 <= endcol
                  && mat[ansrow][midcol + 1]
                         > mat[ansrow][midcol];
 
            // if we're at Peak Element
            if (!valid_left && !valid_right) {
                return new int[] { 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 new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[][] arr = { { 9, 8 }, { 2, 6 } };
 
        int[] result = findPeakGrid(arr);
 
        System.out.println("Peak element found at index: "
                           + result[0] + "," + result[1]);
    }
}
 
// This code is contributed by Karandeep1234


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.


C#




// Finding peak element in a 2D Array.
using System;
using System.Collections.Generic;
 
public class GFG {
 
    static int[] findPeakGrid(int[][] mat)
    {
 
        // Starting point & end point of Search Space
        int stcol = 0, endcol = mat[0].Length - 1;
 
        // Bin Search Condition
        while (stcol <= endcol) {
 
            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.Length; 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 new int[] { 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 new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[][] arr = { new[] { 9, 8 }, new[] { 2, 6 } };
 
        int[] result = findPeakGrid(arr);
 
        Console.WriteLine("Peak element found at index: "
                          + result[0] + "," + result[1]);
    }
}
 
// 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 

 



Previous Article
Next Article

Similar Reads

Find a peak element in Linked List
Given a Linked list of integers. The task is to find a peak element in it. An element in the list is said to be peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor. For example: If the input list is {5 -&gt; 10 -&gt; 20 -&gt; 15}, 20 is the only peak element.For input list {10 -&gt; 20 -&gt; 15 -
8 min read
Find a peak element which is not smaller than its neighbours
Given an array arr of n elements that is first strictly increasing and then maybe strictly decreasing, find the maximum element in the array. Note: If the array is increasing then just print the last element will be the maximum value. Example: Input: array[]= {5, 10, 20, 15}Output: 20Explanation: The element 20 has neighbors 10 and 15, both of them
15+ min read
Find subarray of Length K with Maximum Peak
Given an array arr[] of length n and a positive integer K, we have to find a subarray of length K which has maximum peak inside in it. Peaks of the segment [l, r] are those indexes such that l &lt; i &lt; r, a[i-1] &lt; a[i] and a[i+1] &lt; a[i]. Note: The boundary indexes l and r for the segment are not peaks. If there are many subarrays with maxi
8 min read
Find the peak index of a given array
Given an array arr[] consisting of N(&gt; 2) integers, the task is to find the peak index of the array. If the array doesn't contain any peak index, then print -1. The peak index, say idx, of the given array arr[] consisting of N integers is defined as: 0 &lt; idx &lt; N - 1arr[0] &lt; arr[1] &lt; arr[2] &lt; .... &lt; arr[idx] &lt; .... &lt; arr[N
8 min read
Illustrate the difference in peak memory consumption between DFS and BFS
To understand this let's take a binary tree If we conduct BFS in this tree: In level 0 there is one node in the memory In level 1 there are two nodes in the memory In level 2 there are four nodes in the memory In level 3 there are eight nodes in the memory But in the case of DFS in this tree, you'll never have more than 4 nodes in memory The differ
1 min read
Minimum peak elements from an array by their repeated removal at every iteration of the array
Given an array arr[] consisting of N distinct positive integers, the task is to repeatedly find the minimum peak element from the given array and remove that element until all the array elements are removed. Peak Element: Any element in the array is known as the peak element based on the following conditions: If arr[i - 1] &lt; arr[i] &gt; arr[i +
11 min read
Minimum distance between peak elements in a given array
Given an array arr[], the task is to find the minimum distance between the two peak elements in the given array. Examples: Input: arr[] = {2, 3, 1, 2, 4, 1, 2}Output: 2Explanation: The peak elements in the given array are {2, 3, 1, 2, 4, 1, 2}. Hence the distance between 4 and 2 is (6 - 4) = 2 which is the minimum possible. Input: arr[] = {1, 2}Out
6 min read
Minimum replacements in given Array to remove all strictly peak elements
Given an array arr[] of length N, the task is to find the minimum number of replacements required to remove all peak elements of the array. Note: An element is said to be a peak element if it is strictly greater than both of its neighbours. Corner elements cannot be peak elements, because they have only one neighbour. Examples: Input: arr = { 3, 2,
6 min read
Minimum value to be added to maximize peak count
Given an array A[] of size N. The task is to find the minimum value that should be added to the array elements to maximize the number of peaks in the array: Note: An element is called a peak when it has a higher value than both of its neighbours. Examples: Input: N = 6, A = {3, 1, 4, 5, 5, 2}Output: 3Explanation: Modified A = {3, 1, 6, 5, 6, 2}, So
9 min read
Convert a Linked List to Peak list
Given a linked list, rearrange the nodes so all the even nodes are peak. Peak nodes are those nodes that have greater value than the surrounding nodes. All the nodes of the Linked List have unique values. Examples: Input: 2-&gt;4-&gt;1-&gt;9-&gt;5-&gt;3Output: 1-&gt;3-&gt;2-&gt;5-&gt;4-&gt;9Explanation: All the node values at even positions 3 are g
11 min read
three90RightbarBannerImg