Similar Problems
Similar Problems not available
Finding The Number Of Visible Mountains - Leetcode Solution
Companies:
LeetCode: Finding The Number Of Visible Mountains Leetcode Solution
Difficulty: Medium
Problem Statement:
You are given an array of positive integers representing the heights of mountains on a terrain. The mountains are facing east. A mountain is considered to be visible if there are no taller mountains in front of it.
Write a function that returns the number of visible mountains.
Function signature: int countVisibleMountains(int[] heights)
Example:
Input: [5, 3, 6, 7, 4]
Output: 3
Explanation: There are three visible mountains: 5, 6, and 7.
Solution:
To solve this problem, we will iterate through the given array and check if the current mountain is visible.
Initially, we will assume that the first mountain is the tallest, so we will keep track of the maximum height we have seen so far. We will increment the count of visible mountains if the current mountain's height is greater than the maximum height. Finally, we will update the maximum height to the current mountain's height.
The code will look like this:
int countVisibleMountains(int[] heights) {
int count = 0; // count of visible mountains int max_height = 0; // maximum height seen so far
for (int i = 0; i < heights.length; i++) { if (heights[i] > max_height) { count++; max_height = heights[i]; } }
return count; }
This solution runs in O(n) time complexity, where n is the size of the input array. This is because we are iterating through the array only once.
Finding The Number Of Visible Mountains Solution Code
1