Problem Summary
You are given an array arr[] where each element represents the height of a building.
Sunlight comes from the left side.
A building can see sunlight if:
Important:
Key Insight
A building gets sunlight if its height is:
greater than or equal to the maximum height seen so far from the left
Concept (Greedy Approach)
We traverse the array from left to right and track:
Rule:
If:
current height >= maxHeight
It gets sunlight.
Then:
Increase count
Update maxHeight
Example Walkthrough
Input
arr = [6, 2, 8, 4, 11, 13]
Step-by-step
| Index | Height | maxHeight | Gets Sunlight? | Count |
|---|
| 0 | 6 | 6 | Yes | 1 |
| 1 | 2 | 6 | No | 1 |
| 2 | 8 | 8 | Yes | 2 |
| 3 | 4 | 8 | No | 2 |
| 4 | 11 | 11 | Yes | 3 |
| 5 | 13 | 13 | Yes | 4 |
Output
4
Another Example
Input
arr = [3, 3, 3, 1]
| Height | Condition | Result |
|---|
| 3 | First building | YES |
| 3 | Equal height | YES |
| 3 | Equal height | YES |
| 1 | Smaller | NO |
Output
3
Algorithm (Simple Steps)
Initialize:
Traverse array:
If arr[i] >= maxHeight:
count++
maxHeight = arr[i]
Return count
Java Code
class Solution {
public int visibleBuildings(int arr[]) {
int maxHeight = 0;
int count = 0;
for (int height : arr) {
if (height >= maxHeight) {
count++;
maxHeight = height;
}
}
return count;
}
}
Complexity
Key Takeaways
This is a greedy + traversal problem
Track the maximum so far
Equal heights are allowed (important edge case!)
Very common in interviews (Amazon, Microsoft)