Finding the Number of Visible Mountains - Problem

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.

Input & Output

Example 1 — Basic Visibility
$ Input: peaks = [[2,1],[2,2],[1,4]]
Output: 2
💡 Note: Mountain at (2,1) has base [1,3], mountain at (2,2) has base [0,4], mountain at (1,4) has base [-3,5]. The first mountain is completely contained within the second (same left boundary but smaller right), so only 2 mountains are visible.
Example 2 — All Visible
$ Input: peaks = [[1,3],[1,1],[2,2]]
Output: 3
💡 Note: Mountain bases are [-2,4], [0,2], [0,4]. No mountain completely contains another, so all 3 are visible.
Example 3 — Duplicate Peaks
$ Input: peaks = [[0,1],[1,0]]
Output: 2
💡 Note: Peak (0,1) creates base [-1,1] and peak (1,0) creates base [1,1]. These are different ranges with no containment, so both mountains are visible.

Constraints

  • 1 ≤ peaks.length ≤ 105
  • peaks[i].length == 2
  • 1 ≤ xi, yi ≤ 105

Visualization

Tap to expand
Finding the Number of Visible Mountains INPUT 0 1 2 3 4 0 1 2 3 (2,1) (2,2) (1,4) peaks array: [2,1] [2,2] [1,4] Each mountain is a triangle with slopes of +1 and -1 Base width = 2 * height ALGORITHM STEPS 1 Convert to intervals [x-y, x+y] for each peak (2,1) --> [1, 3] (2,2) --> [0, 4] (1,4) --> [-3, 5] 2 Sort intervals By left asc, right desc Sorted: [-3,5], [0,4], [1,3] (wider intervals first) 3 Check containment Track max right endpoint [-3,5]: visible (maxR=5) [0,4]: visible (4 < 5, unique) [1,3]: hidden (3 <= 5) 4 Remove duplicates Same peak = not visible Count unique visible: 2 FINAL RESULT VISIBLE VISIBLE HIDDEN Visible Hidden Output: 2 2 mountains have visible peaks Key Insight: A mountain with peak (x,y) covers x-axis interval [x-y, x+y]. Mountain A hides mountain B if A's interval completely contains B's interval. Sort by left endpoint ascending and right endpoint descending, then track maximum right boundary to detect contained intervals in O(n log n) time. TutorialsPoint - Finding the Number of Visible Mountains | Optimal Solution
Asked in
Google 12 Facebook 8 Amazon 6
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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