Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2345: Finding the Number of Visible Mountains

In this guide, we solve Leetcode #2345 Finding the Number of Visible Mountains in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Stack, Array, Sorting, Monotonic Stack

Intuition

We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.

Each element is pushed and popped at most once, yielding a linear-time scan.

Approach

Maintain a stack that is either increasing or decreasing, depending on the query.

When the invariant is broken, pop and resolve answers for those indices.

Steps:

  • Scan elements once.
  • Pop while the monotonic condition is violated.
  • Use stack indices to update answers.

Example

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.

Python Solution

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

The time complexity is O(n×log⁡n)O(n \times \log n)O(n×logn), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy