MediumNo. 2345LeetCode Premium

Finding the Number of Visible Mountains — LeetCode 2345 Python Solution

Pattern
Stack
Topics
Stack, Array, Sorting, Monotonic Stack
Reading time
3 min

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.

Example

Input
peaks = [[2,2],[6,3],[5,4]]
Output
2
Explanation
The diagram above shows the mountains.

Python solution

PythonSolution
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, -inf
        for l, r in arr:
            if r <= cur:
                continue
            cur = r
            if cnt[(l, r)] == 1:
                ans += 1
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2345. Finding the Number of Visible Mountains is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0853Car FleetMedium
2454Next Greater Element IVHard
2736Maximum Sum QueriesHard
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium

Frequently asked questions

How hard is LeetCode 2345. Finding the Number of Visible Mountains?

LeetCode 2345. Finding the Number of Visible Mountains is rated Medium on LeetCode.

What is the time complexity of LeetCode 2345. Finding the Number of Visible Mountains?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 2345. Finding the Number of Visible Mountains?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2345. Finding the Number of Visible Mountains cover?

LeetCode 2345. Finding the Number of Visible Mountains is tagged Stack, Array, Sorting and Monotonic Stack on LeetCode.

Is LeetCode 2345. Finding the Number of Visible Mountains a premium problem?

Yes. LeetCode 2345. Finding the Number of Visible Mountains is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.