ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find Peak Element in a 2D Grid

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1/**
2* Finds a peak element in a 2D grid.
3* A peak element is an element that is strictly greater than its neighbors.
4* This implementation uses a binary search-like approach on rows.
5*
6* @param {number[][]} grid The 2D grid of numbers.
7* @returns {number[] | null} An array [row, col] representing the coordinates of a peak element, or null if the grid is empty.
8*/
9function findPeakElement2D(grid) {
10if (!grid || grid.length === 0 || grid[0].length === 0) {
11return null; // Handle empty or invalid grid
12}
13
14const numRows = grid.length;
15const numCols = grid[0].length;
16
17let lowRow = 0;
18let highRow = numRows - 1;
19
20while (lowRow <= highRow) {
21const midRow = Math.floor((lowRow + highRow) / 2);
22
23// Find the column with the maximum element in the midRow
24let maxColInMidRow = 0;
25for (let j = 1; j < numCols; j++) {
26if (grid[midRow][j] > grid[midRow][maxColInMidRow]) {
27maxColInMidRow = j;
28}
29}
30
31const currentElement = grid[midRow][maxColInMidRow];
32
33// Check neighbors
34const topNeighbor = midRow > 0 ? grid[midRow - 1][maxColInMidRow] : -Infinity;
35const bottomNeighbor = midRow < numRows - 1 ? grid[midRow + 1][maxColInMidRow] : -Infinity;
36
37if (currentElement > topNeighbor && currentElement > bottomNeighbor) {
38// Found a peak element in this row that is also greater than its vertical neighbors
39// Now, we need to ensure it's greater than its horizontal neighbors.
40// Since we picked the max in the row, it's already greater than or equal to its horizontal neighbors.
41// If it's strictly greater, it's a peak.
42// If it's equal to a horizontal neighbor, we might need to search further, but this algorithm guarantees finding *a* peak.
43// For simplicity and correctness of finding *a* peak, this condition is sufficient.
44return [midRow, maxColInMidRow];
45} else if (currentElement < topNeighbor) {
46// The peak must be in the upper half
47highRow = midRow - 1;
48} else {
49// The peak must be in the lower half (currentElement < bottomNeighbor)
50lowRow = midRow + 1;
51}
52}
53
54// This part should theoretically not be reached if the grid is valid and non-empty,
55// as a peak is guaranteed to exist.
56return null;
57}
58
59/**
60* Helper function to get the maximum element in a specific row.
61* This is implicitly handled within the main loop for efficiency.
62* @param {number[][]} grid The 2D grid.
63* @param {number} rowIndex The index of the row.
64* @returns {number} The maximum value in the specified row.
65*/
66function getMaxInRow(grid, rowIndex) {
67if (!grid || grid.length === 0 || rowIndex < 0 || rowIndex >= grid.length) {
68return -Infinity; // Or throw an error
69}
70let maxVal = grid[rowIndex][0];
71for (let j = 1; j < grid[rowIndex].length; j++) {
72if (grid[rowIndex][j] > maxVal) {
73maxVal = grid[rowIndex][j];
74}
75}
76return maxVal;
77}
78
79// Example Usage:
80// const grid1 = [[1, 4], [3, 2]];
81// console.log(findPeakElement2D(grid1)); // Expected: [0, 1] or [1, 0]
82
83// const grid2 = [[10, 20, 15], [21, 30, 14], [7, 16, 32]];
84// console.log(findPeakElement2D(grid2)); // Expected: [1, 1] or [2, 2]
85
86// const grid3 = [[1]];
87// console.log(findPeakElement2D(grid3)); // Expected: [0, 0]
88
89// const grid4 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
90// console.log(findPeakElement2D(grid4)); // Expected: [2, 2]
91
92// const grid5 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
93// console.log(findPeakElement2D(grid5)); // Expected: [0, 0]
Algorithm description viewbox

Find Peak Element in a 2D Grid

Algorithm description:

This function finds a peak element in a 2D grid. A peak element is defined as an element that is strictly greater than all its adjacent neighbors (up, down, left, right). This algorithm is useful in scenarios where you need to find a local maximum in a matrix, such as in image processing for feature detection or in game AI for finding advantageous positions.

Algorithm explanation:

The algorithm finds a peak element in a 2D grid using a binary search approach on the rows. In each step, it finds the column with the maximum element in the middle row. It then compares this element with its top and bottom neighbors. If the middle element is greater than both, it's a peak. If the top neighbor is greater, the search space is reduced to the upper half of the rows; otherwise, it's reduced to the lower half. This process continues until a peak is found. The time complexity is O(M log N) where M is the number of rows and N is the number of columns, because we perform a binary search on rows (log N iterations) and in each iteration, we scan a row to find the maximum element (M operations). The space complexity is O(1) as it uses a constant amount of extra space. Edge cases like empty grids or single-element grids are handled by returning null or the element itself, respectively.

Pseudocode:

function findPeakElement2D(grid):
  if grid is empty or invalid:
    return null

  numRows = number of rows in grid
  numCols = number of columns in grid

  lowRow = 0
  highRow = numRows - 1

  while lowRow <= highRow:
    midRow = floor((lowRow + highRow) / 2)

    maxColInMidRow = find column index of max element in grid[midRow]
    currentElement = grid[midRow][maxColInMidRow]

    topNeighbor = element above currentElement, or -Infinity if at top edge
    bottomNeighbor = element below currentElement, or -Infinity if at bottom edge

    if currentElement > topNeighbor and currentElement > bottomNeighbor:
      return [midRow, maxColInMidRow] // Found a peak
    else if currentElement < topNeighbor:
      highRow = midRow - 1 // Peak is in upper half
    else:
      lowRow = midRow + 1 // Peak is in lower half

  return null // Should not be reached for valid non-empty grids