We are given a 2D grid of integers. We need to find all "peak" elements. A peak is an element that is greater than all its adjacent neighbors. Adjacent neighbors are typically up, down, left, right (4-directional). Sometimes diagonals are considered? The problem statement says "adjacent neighbors", which usually means the four orthogonal neighbors. But we should clarify: In typical "find peak in 2D" problems, adjacent neighbors are up, down, left, right. But sometimes it includes diagonals? The phrase "adjacent neighbors" could be interpreted as sharing an edge (4-direction). However, some might consider 8-direction. But the classic "find peak element" in 1D uses neighbors to left and right. In 2D, it's often 4-direction. I'll assume 4-direction unless specified otherwise. But the problem says "greater than all its adjacent neighbors". So we need to check the element against its neighbors. For edge/corner elements, they have fewer neighbors.
We need to write a function that returns the peak elements? Possibly return their coordinates? Or the values? The problem says "find the peak elements". It doesn't specify output format. Usually we return a list of positions (i,j) where grid[i][j] is a peak. Or maybe just the values. I'll assume we return a list of tuples (i, j) for each peak. Or perhaps return the values. But to be safe, I'll return the coordinates. In explanation, we can clarify.
Algorithm: Straightforward: iterate over each cell, check its 4 neighbors. If it is greater than all existing neighbors (only check within bounds), then it's a peak. That is O(m*n) time, O(1) extra space (or O(k) for output). That's acceptable.
But there might be a more efficient algorithm? The classic 2D peak finding problem often uses divide and conquer to find a peak in O(n log n) time for an n x n grid. But that's for finding any peak, not all peaks. Here we want all peaks. So we have to check all cells anyway, so O(mn) is optimal because we need to examine each element at least once. So the simple approach is fine.
Edge cases: grid empty? Return empty list. Grid with one element? That element is a peak (no neighbors). So we should return that.
Implementation details: For each cell (i,j), get its value v. Check up: if i>0 and grid[i-1][j] >= v, not peak. Similarly down, left, right. Actually condition: peak if v > all neighbors. So if any neighbor exists and neighbor >= v, then not peak. So we can check:
if (i == 0 or v > grid[i-1][j]) and (i == m-1 or v > grid[i+1][j]) and (j == 0 or v > grid[i][j-1]) and (j == n-1 or v > grid[i][j+1]) then it's a peak.
But careful: The condition "greater than all its adjacent neighbors" means strictly greater? Typically yes. So if a neighbor is equal, then it's not a peak. So we use >.
We'll implement as:
def find_peaks(grid):
if not grid or not grid[0]:
return []
m, n = len(grid), len(grid[0])
peaks = []
for i in range(m):
for j in range(n):
v = grid[i][j]
# check up
if i > 0 and grid[i-1][j] >= v:
continue
# check down
if i < m-1 and grid[i+1][j] >= v:
continue
# check left
if j > 0 and grid[i][j-1] >= v:
continue
# check right
if j < n-1 and grid[i][j+1] >= v:
continue
peaks.append((i, j))
return peaks
Alternatively we can use all() with a generator for conditions.
But note: The above uses continue to skip if any neighbor is >= v. That works.
Time complexity: O(mn). Space: O(k) for peaks.
Now, the problem says "Write a function to find the 'peak' elements." It might ask to return the values, but we can return coordinates or values. We'll return coordinates. Or we could return values. Let's decide: Usually in such problems, we return the positions. But the phrase "find the peak elements" might mean return the elements themselves. But we can return both. However, to be safe, I'll return a list of the peak values. But then if there are duplicates, we lose location. But maybe they want all peaks, so we could return a list of tuples (value, row, col). But the problem statement is ambiguous. I'll assume we return the coordinates. In my explanation, I'll mention that we can adapt to return values.
Let's write a clear solution with explanation.
But the user says: "You are given a 2D grid of integers. Write a function to find the "peak" elements. A peak is an element that is greater than all its adjacent neighbors. Please write a function that solves this problem, and explain your algorithm."
So we need to produce code and explanation. We'll write in Python.
We'll also consider if diagonals are included? The phrase "adjacent neighbors" typically means cells that share an edge. But in some contexts, it could include diagonals. However, the classic 2D peak problem uses 4-direction. I'll go with 4-direction. If we wanted 8-direction, we'd need to check 8 neighbors. But the problem didn't specify. I'll mention in explanation that we assume 4-directional adjacency. We could also provide an option for 8-direction. But to be safe, I'll implement with 4-direction and note that it can be modified.
Thus final answer: function find_peaks(grid) returns list of (i,j) for peaks.
Let's produce a thorough explanation.
Algorithm:
- Iterate through each cell in the grid.
- For each cell, compare its value with its adjacent neighbors (up, down, left, right). If the cell has any neighbor with value greater than or equal to the cell's value, it is not a peak.
- If the cell is greater than all its neighbors (or has no neighbor in a direction because it's on the border), then it is a peak; record its coordinates.
- After scanning all cells, return the list of peaks.
Complexity: O(mn) time, O(k) space for output.
Edge cases: empty grid, single cell.
We'll provide code with docstring.
Potential improvements: If we only need one peak, we could use a more efficient algorithm, but for all peaks we need to check all cells.
Now, I'll write the code.
We'll also include a test example.
Let's produce final answer.
Solution Explanation
A peak in a 2D grid is an element that is strictly greater than all of its adjacent neighbors.
We consider adjacency in the four cardinal directions (up, down, left, right). Elements on the border have fewer neighbors – they only need to be greater than the neighbors that exist.
The straightforward approach is to examine every cell and compare it with its neighbors. If a cell is larger than all of them, it is a peak. This requires a single pass over the grid.
Algorithm
- Input validation: If the grid is empty, return an empty list.
- Initialize an empty list
peaks to store the coordinates of peaks.
- Iterate over each cell
(i, j):
- Let
v = grid[i][j].
- Check the four possible neighbors:
- Up: if
i > 0 and grid[i-1][j] >= v → not a peak.
- Down: if
i < m-1 and grid[i+1][j] >= v → not a peak.
- Left: if
j > 0 and grid[i][j-1] >= v → not a peak.
- Right: if
j < n-1 and grid[i][j+1] >= v → not a peak.
- If none of the above conditions triggered,
(i, j) is a peak → add it to peaks.
- Return
peaks.
Correctness Proof
We prove that the algorithm returns exactly the set of peak elements.
Lemma 1: For any cell c processed by the algorithm, if c is added to peaks, then c is a peak.
Proof: The algorithm adds c only after verifying that for every existing neighbor n (up, down, left, right) we have grid[c] > grid[n]. This is precisely the definition of a peak. ∎
Lemma 2: If a cell c is a peak, the algorithm will add it to peaks.
Proof: Since c is a peak, it satisfies grid[c] > grid[n] for every adjacent neighbor n. During the check for c, the algorithm examines exactly those neighbors. Because all comparisons are strict, none of the “neighbor ≥ v” conditions will be true, so the algorithm will not skip c and will append it. ∎
Theorem: The list peaks returned by the algorithm contains all and only the peak elements of the grid.
Proof: By Lemma 1, every element in peaks is a peak (only peaks are added). By Lemma 2, every peak in the grid is added to peaks. Hence the sets are equal. ∎
Complexity Analysis
- Time: The grid has
m × n cells. Each cell performs up to 4 constant‑time neighbor checks. Total time is O(m n).
- Space: Aside from the output list (which holds at most
m n coordinates), the algorithm uses only a few variables → O(1) auxiliary space.
Reference Implementation (Python)
from typing import List, Tuple
def find_peaks(grid: List[List[int]]) -> List[Tuple[int, int]]:
"""
Find all peak elements in a 2D grid.
A peak is an element strictly greater than its four orthogonal neighbors
(up, down, left, right). Border cells have fewer neighbors.
Parameters:
grid: 2D list of integers.
Returns:
List of (row, col) tuples indicating the positions of peaks.
Returns an empty list for an empty grid.
"""
if not grid or not grid[0]:
return []
m, n = len(grid), len(grid[0])
peaks = []
for i in range(m):
for j in range(n):
v = grid[i][j]
# Check up
if i > 0 and grid[i-1][j] >= v:
continue
# Check down
if i < m-1 and grid[i+1][j] >= v:
continue
# Check left
if j > 0 and grid[i][j-1] >= v:
continue
# Check right
if j < n-1 and grid[i][j+1] >= v:
continue
peaks.append((i, j))
return peaks
# Example usage
if __name__ == "__main__":
grid = [
[1, 2, 3],
[4, 9, 5],
[6, 7, 8]
]
print(find_peaks(grid)) # Output: [(1, 1)] because 9 > 2,5,4,7
Note: If diagonal neighbors should also be considered, simply add checks for the four diagonal directions ((i-1,j-1), (i-1,j+1), (i+1,j-1), (i+1,j+1)). The core logic remains the same.