Data Structures and Algorithms (DSA)  

Buildings with Sunlight

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:

  • There is no taller building before it (to its left)

Important:

  • Buildings with equal height DO NOT block each other

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:

  • maxHeight → tallest building seen so far

  • count → number of buildings receiving sunlight

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

IndexHeightmaxHeightGets Sunlight?Count
066Yes1
126No1
288Yes2
348No2
41111Yes3
51313Yes4

Output

4

Another Example

Input

arr = [3, 3, 3, 1]
HeightConditionResult
3First buildingYES
3Equal heightYES
3Equal heightYES
1SmallerNO

Output

3

Algorithm (Simple Steps)

  • Initialize:

    • maxHeight = 0

    • count = 0

  • 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

  • Time Complexity: O(n)
    → Single pass through array

  • Space Complexity: O(1)
    → No extra space used

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)