Finding the Number of Visible Mountains

Asked atMeta
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The 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: 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.

**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.

**Input **: peaks = [[3,2], [7,4], [5,3], [9,2]]

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

cpp

class Solution {
public:
    int visibleMountains(vector<vector<int>>& peaks) {
        // Your code goes here
    }
};

java

class Solution {
    public int visibleMountains(int[][] peaks) {
        // Your code goes here
    }
}

python

class Solution:
    def visibleMountains(self, peaks):
        # Your code goes here

javascript

class Solution {
    visibleMountains(peaks) {
        // Your code goes here
    }
}

csharp

public class Solution {
    public int VisibleMountains(List<List<int>> peaks) {
        // Your code goes here
    }
}

go

func visibleMountains(peaks [][]int) int {

}
Stuck? Show a way to structure it+
  1. 01Translate peaks into intervals
  2. 02Sort left ascending and right descending
  3. 03Track the greatest right endpoint seen
  4. 04Count only intervals that extend it, treating duplicates carefully

Reference answer

Then expect these follow-ups

  • How would you return the visible mountain indices?

    Tests: implementation extension

  • Why does the sort tie-breaker matter?

    Tests: correctness reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question