Finding the Number of Visible Mountains — LeetCode 2345 Python Solution

MediumLeetCode PremiumStackArraySortingMonotonic Stack
Problem
#2345
Pattern
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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

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

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 \times \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.

Get Stealth Interview