Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
🌍 The Why?
This algorithm is important because it teaches us how to find what truly stands out when things overlap. Just like tall mountains can hide smaller ones, some events or items get overshadowed in real life too on maps, timelines, or screens.
By sorting and scanning smartly, we figure out what’s actually visible. It’s fast, elegant, and applies to everything from calendar events to ad placements and 3D graphics.
The Situation:
You are given a list of mountains defined by their peaks on a 2D grid. Each mountain forms a right-angled isosceles triangle with its base on the x-axis.
The goal is to determine how many of these mountains are visible meaning their peaks do not lie inside or on the side of any other mountain.
The Question:
You are given a 0-indexed 2D integer array peaks where peaks[i] = [xi, yi] states that mountain i has a peak at coordinates (xi, yi). A mountain can be described as a right-angled isosceles triangle, with its base along the x-axis and a right angle at its peak. More formally, the gradients of ascending and descending the mountain are 1 and -1 respectively.
A mountain is considered visible if its peak does not lie within another mountain (including the border of other mountains).
Return the number of visible mountains.
The Task:
Efficiently compute the number of visible mountains from the given list, even if there are up to 100,000 mountains. Ensure performance is optimised and accounts for overlapping and identical mountains.
Action:
What can we do to solve this?
1. Let's see how the mountain range expands.
Each mountain is a triangle with its peak at [x, y].
The base spans from:
So we can represent each mountain as an interval [start, end]
2. Visibility Criteria
A mountain is not visible if any other mountain's interval fully covers it, including it's peak. That means:
3. Steps to Solve:
Actual Code:
The Result:
The sorting step creates the O(N log N) bottleneck in this algorithm, which is unavoidable since we need to process the mountains in a specific order.
The rest of the operations are all linear time.
#leetcode #intervals #google