LeetCode 1762: Buildings With an Ocean View Solution
Master LeetCode problem 1762 (Buildings With an Ocean View), 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.
1762. Buildings With an Ocean View
Problem Explanation
Explanation:
To solve this problem, we need to find the buildings with an ocean view, which means the buildings have a greater height to their right. We can iterate through the buildings from right to left and keep track of the maximum height seen so far. If the current building's height is greater than the maximum height seen so far, it has an ocean view.
Algorithm:
- Initialize an empty stack to store the indices of buildings with an ocean view.
- Iterate over the buildings from right to left:
- If the stack is empty, push the current building index to the stack.
- If the current building height is greater than the height of the building at the top of the stack, pop elements from the stack until either the stack becomes empty or the top building has a greater height.
- Push the current building index to the stack.
- The stack now contains the indices of buildings with an ocean view.
Time Complexity: O(N) - where N is the number of buildings. Space Complexity: O(N) - for the stack to store the indices.
: :
Solution Code
public int[] findBuildings(int[] heights) {
Stack<Integer> stack = new Stack<>();
for (int i = heights.length - 1; i >= 0; i--) {
if (stack.isEmpty() || heights[i] > heights[stack.peek()]) {
stack.push(i);
}
}
int[] result = new int[stack.size()];
for (int i = 0; i < result.length; i++) {
result[i] = stack.pop();
}
return result;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1762 (Buildings With an Ocean View)?
This page provides optimized solutions for LeetCode problem 1762 (Buildings With an Ocean View) 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 1762 (Buildings With an Ocean View)?
The time complexity for LeetCode 1762 (Buildings With an Ocean View) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1762 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1762 in Java, C++, or Python.