LeetCode 2345: Finding the Number of Visible Mountains Solution
Master LeetCode problem 2345 (Finding the Number of Visible Mountains), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2345. Finding the Number of Visible Mountains
Problem Explanation
Explanation
To find the number of visible mountains, we can iterate through the array of mountain heights from left to right. We will keep track of the maximum height seen so far. If the current mountain height is greater than the maximum height seen so far, we increment the count of visible mountains and update the maximum height seen. At the end of the iteration, the count of visible mountains will be the answer.
Time complexity: O(n) - We iterate through the array once. Space complexity: O(1) - We use constant extra space.
Solution Code
class Solution {
public int visibleMountains(int[] heights) {
int count = 0;
int maxSeen = 0;
for (int height : heights) {
if (height > maxSeen) {
count++;
maxSeen = height;
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2345 (Finding the Number of Visible Mountains)?
This page provides optimized solutions for LeetCode problem 2345 (Finding the Number of Visible Mountains) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2345 (Finding the Number of Visible Mountains)?
The time complexity for LeetCode 2345 (Finding the Number of Visible Mountains) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2345 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2345 in Java, C++, or Python.