Find the Peak Element in a 2D Array/Matrix
Last Updated :
11 Sep, 2024
Given a 2D Array/Matrix mat[][], 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 peak element is not necessarily the overall maximal element. It only needs to be greater than existing adjacent
- More than one such element can exist. We need to return any of them
- 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));
}
}
Python
# 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)
OutputPeak 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:
- Consider mid column and find maximum element in it.
- 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]'.
- If max >= mat[index][mid-1] & max >= mat[index][mid+1], max is a peak, return max.
- If max < mat[max_index][mid-1], recur for left half of matrix.
- 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;
vector<int> findPeakGrid(vector<vector<int> >& mat)
{
// Starting point & end point of Search Space
int stcol = 0, endcol = mat[0].size() - 1;
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
Python
# 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.
OutputPeak 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
Similar Reads
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
What is Binary Search Algorithm? Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Example of binary searchProperties of Binary Search:Binary search is performed o
1 min read
Time and Space Complexity Analysis of Binary Search Algorithm Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. Example of Binary Search AlgorithmAspectComplexityTime ComplexityO(log n)Space ComplexityO(1)
3 min read
How to calculate "mid" or Middle Element Index in Binary Search? The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Finding the middle index "mid" in Binary Search AlgorithmIs this method
6 min read
Variants of Binary Search
Variants of Binary SearchBinary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False)Â 2) Index of first occurrence
15+ min read
Meta Binary Search | One-Sided Binary SearchMeta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
9 min read
The Ubiquitous Binary Search | Set 1We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
15+ min read
Uniform Binary SearchUniform Binary Search is an optimization of Binary Search algorithm when many searches are made on same array or many arrays of same size. In normal binary search, we do arithmetic operations to find the mid points. Here we precompute mid points and fills them in lookup table. The array look-up gene
7 min read
Randomized Binary Search AlgorithmWe are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a ran
13 min read
Abstraction of Binary SearchWhat is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begi
7 min read
N-Base modified Binary Search algorithmN-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output:
10 min read
Implementation of Binary Search in different languages
C Program for Binary SearchIn this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
C++ Program For Binary SearchBinary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the pro
5 min read
C Program for Binary SearchIn this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data.There are the 3 binary search function in C++ STL:Table of Contentbinary_sea
3 min read
Binary Search in JavaBinary search is a highly efficient searching algorithm used when the input is sorted. It works by repeatedly dividing the search range in half, reducing the number of comparisons needed compared to a linear search. Here, we are focusing on finding the middle element that acts as a reference frame t
6 min read
Binary Search (Recursive and Iterative) - PythonBinary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:D
6 min read
Binary Search In JavaScriptBinary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexityExamples: Input : arr
3 min read
Binary Search using pthreadBinary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discards the half which has zero probability of having the key. On dividing, we check the midpoint for the key and use the lower half if the key is less than the midpoint and the
8 min read
Comparison with other Searching
Binary Search Intuition and Predicate Functions The binary search algorithm is used in many coding problems, and it is usually not very obvious at first sight. However, there is certainly an intuition and specific conditions that may hint at using binary search. In this article, we try to develop an intuition for binary search. Introduction to Bi
12 min read
Can Binary Search be applied in an Unsorted Array? Binary Search is a search algorithm that is specifically designed for searching in sorted data structures. This searching algorithm is much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. It has logarithmic time comp
9 min read
Find a String in given Array of Strings using Binary Search Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
6 min read