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
A(3,2)B(5,4)C(7,10)Base [1,5]Base [1,9]Base [-3,17]Mountain Visibility ProblemMountain C completely covers both A and B โ†’ Only C is visibleVisibleHidden
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.4K Views
Medium Frequency
~25 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen