LeetCode 1901: Find a Peak Element II Solution
Master LeetCode problem 1901 (Find a Peak Element II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1901. Find a Peak Element II
Problem Explanation
Explanation:
To find a peak element in a 2D grid, we can use a binary search approach. We start by finding the middle column of the matrix and then find the maximum element in that column. We then compare this maximum element with its adjacent neighbors (top, bottom). If the maximum element is greater than both its neighbors, we have found a peak element. If not, we move towards the side of the neighbor with a greater value and repeat the process.
- Time complexity: O(m log(n)) or O(n log(m))
- Space complexity: O(1)
:
Solution Code
class Solution {
public int[] findPeakGrid(int[][] mat) {
int left = 0, right = mat[0].length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
int maxRow = 0;
for (int i = 0; i < mat.length; i++) {
if (mat[i][mid] > mat[maxRow][mid]) {
maxRow = i;
}
}
boolean isPeak = true;
if (mid - 1 >= 0 && mat[maxRow][mid - 1] > mat[maxRow][mid]) {
isPeak = false;
right = mid - 1;
} else if (mid + 1 < mat[0].length && mat[maxRow][mid + 1] > mat[maxRow][mid]) {
isPeak = false;
left = mid + 1;
}
if (isPeak) {
return new int[]{maxRow, mid};
}
}
return new int[]{-1, -1};
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1901 (Find a Peak Element II)?
This page provides optimized solutions for LeetCode problem 1901 (Find a Peak Element II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1901 (Find a Peak Element II)?
The time complexity for LeetCode 1901 (Find a Peak Element II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1901 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1901 in Java, C++, or Python.