DDSA Solutions

Buildings with Sunlight

Advertisement

Intuition

A building is visible from the east (left side) if and only if it is at least as tall as every building to its left. Tracking a running maximum 'ptr' lets us decide visibility in O(1) per building: if arr[i] >= ptr the building is visible and becomes the new tallest seen so far.

Algorithm

  1. 1Initialise ptr = arr[0] and count = 0.
  2. 2Walk left-to-right from index 0 to n-1.
  3. 3If arr[i] >= ptr: the building receives sunlight — increment count and update ptr = arr[i].
  4. 4Return count.

Example Walkthrough

Input: arr = [7, 4, 8, 2, 9]

  1. 1.i=0: arr[0]=7 >= ptr=7 → visible, count=1, ptr=7.
  2. 2.i=1: arr[1]=4 < ptr=7 → blocked.
  3. 3.i=2: arr[2]=8 >= ptr=7 → visible, count=2, ptr=8.
  4. 4.i=3: arr[3]=2 < ptr=8 → blocked.
  5. 5.i=4: arr[4]=9 >= ptr=8 → visible, count=3, ptr=9.

Output: 3

Common Pitfalls

  • Use >= (not >) because the code treats an equal-height building as visible; confirm against the specific problem statement.
  • Start the loop from index 0 (not 1) since the first building always sees the sun and initialises ptr.
Buildings with Sunlight.java
Java

// Approach: A building receives sunlight if no taller or equal building blocks it from the left.
// Track a running maximum 'ptr' starting at arr[0]. Walk left-to-right: whenever arr[i] >= ptr,
// the building is visible (it is at least as tall as every building before it), so count it and
// update ptr to arr[i].
//
// Time: O(N) — single pass over the array.
// Space: O(1) — only two integer variables.
class Solution {

    public int visibleBuildings(int arr[]) {
        int build = 0, ptr = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= ptr) {
                build++;
                ptr = arr[i];
            }
        }

        return build;
    }
}
Advertisement
Was this solution helpful?