Finding the Number of Visible Mountains - Problem
Imagine you're standing on a vast plain looking at a range of perfectly triangular mountains. Each mountain has a unique peak and forms a right-angled isosceles triangle with its base on the ground.
You are given a 2D array peaks where peaks[i] = [xi, yi] represents the coordinates of mountain i's peak at position (xi, yi). Each mountain has:
- Its base along the x-axis
- A right angle at its peak
- Slopes of exactly +1 (ascending) and -1 (descending)
A mountain is visible if its peak is not completely hidden inside another mountain (touching the border counts as hidden). Your task is to determine how many mountains you can actually see from your vantage point.
Goal: Return the number of visible mountains.
Input & Output
example_1.py โ Basic Case
$
Input:
peaks = [[2,2],[6,3],[5,4]]
โบ
Output:
2
๐ก Note:
Mountain at (2,2) covers x-axis [0,4]. Mountain at (6,3) covers [3,9]. Mountain at (5,4) covers [1,9]. The peak (6,3) is inside mountain (5,4) since 1 < 6 < 9 and 3 โค 4, so it's hidden. Mountains at (2,2) and (5,4) are visible.
example_2.py โ All Visible
$
Input:
peaks = [[1,3],[1,3]]
โบ
Output:
1
๐ก Note:
Both peaks are identical at (1,3), so we only count unique mountains. After removing duplicates, only 1 mountain remains, which is obviously visible.
example_3.py โ Complete Coverage
$
Input:
peaks = [[0,1],[1,0]]
โบ
Output:
1
๐ก Note:
Mountain at (0,1) covers x-axis [-1,1]. Mountain at (1,0) covers [1,1] (just a point). The second peak (1,0) is on the boundary of the first mountain, which counts as hidden. Only the first mountain is visible.
Constraints
- 1 โค peaks.length โค 105
- peaks[i].length == 2
- 0 โค xi, yi โค 105
- Each mountain forms a right-angled isosceles triangle
Visualization
Tap to expand
Understanding the Visualization
1
Map Mountains
Each mountain (x,y) creates a triangle covering ground from x-y to x+y
2
Check Coverage
A mountain is hidden if its peak lies inside another mountain's triangle
3
Count Visible
Only mountains not completely covered by others remain visible
Key Takeaway
๐ฏ Key Insight: Transform peaks into base intervals and use containment relationships - a mountain is visible if no other mountain completely covers its interval with equal or greater height.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code