Finding the Number of Visible Mountains Problem
Description
LeetCode Problem 2345.
You are given a 0-indexed 2D integer array peaks where peaks[i] = [x_i, y_i] states that mountain i has a peak at coordinates (x_i, y_i). 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.
Example 1:

Input: peaks = [[2,2],[6,3],[5,4]]
Output: 2
Explanation: The diagram above shows the mountains.
- Mountain 0 is visible since its peak does not lie within another mountain or its sides.
- Mountain 1 is not visible since its peak lies within the side of mountain 2.
- Mountain 2 is visible since its peak does not lie within another mountain or its sides.
There are 2 mountains that are visible.
Example 2:

Input: peaks = [[1,3],[1,3]]
Output: 0
Explanation: The diagram above shows the mountains (they completely overlap).
Both mountains are not visible since their peaks lie within each other.
Constraints:
1 <= peaks.length <= 10^5peaks[i].length == 21 <= x_i, y_i <= 10^5
Solution
Approach: Sort the Intervals
A mountain with peak (x, y) covers the interval [x - y, x + y] on the ground, and it is hidden exactly when another mountain's interval contains its own (a mountain is hidden when its peak lies inside or on the edge of another one).
Convert every peak to its interval and sort by left end ascending, and by right end descending for equal left ends. Sweep through the intervals while keeping the largest right end seen so far:
- If the current right end is not beyond that value, the mountain is hidden: skip it.
- Otherwise it sticks out, so update the largest right end. It is visible only if no other mountain has exactly the same interval, so count it when its interval occurs once.
Complexity: O(n log n) time and O(n) extra space.
from collections import Counter
class Solution:
def visibleMountains(self, peaks: List[List[int]]) -> int:
arr = [(x - y, x + y) for x, y in peaks]
cnt = Counter(arr)
arr.sort(key=lambda x: (x[0], -x[1]))
ans, cur = 0, float('-inf')
for l, r in arr:
if r <= cur:
continue
cur = r
if cnt[(l, r)] == 1:
ans += 1
return ans