This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
You can traverse the buildings from the nearest to the ocean to the furthest.
Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, this problem or similar variations are commonly asked in technical interviews at companies like Amazon, Meta, and Google. It tests understanding of arrays, monotonic stacks, and efficient traversal techniques.
A simple variable to track the maximum height works for the most optimal solution. However, the problem can also be modeled using a monotonic stack that keeps buildings in decreasing height order.
The optimal approach is scanning the array from right to left while tracking the maximum height seen so far. If a building is taller than this maximum, it has an ocean view. This method runs in O(n) time and uses O(1) extra space.
The ocean lies to the right of the buildings, so any building’s visibility depends on buildings located after it. Traversing from right to left allows us to easily maintain the tallest building seen so far.