702686. Buildings receiving sunlight

Easy

Buildings receiving sunlight

Slug: buildings-receiving-sunlight3032

Difficulty: Easy

Id: 702686

Topic Tags: Arrays, Data Structures

Company Tags: Amazon, Microsoft

Summary

Given a list of buildings and their respective elevations, we need to determine which buildings receive direct sunlight. A building receives direct sunlight if the elevation of that building is higher than or equal to any building that comes after it in the list.

Detailed Explanation

To solve this problem, we can iterate through the list of buildings from left to right. For each building, we check if its elevation is greater than or equal to the elevation of any subsequent building. If it is, then we consider this building as receiving direct sunlight and mark it accordingly. We keep track of the last index where we found a building that receives direct sunlight. If no such building is found, then all buildings receive direct sunlight.

Here's a step-by-step breakdown:

  1. Initialize an empty array sunlightReceivers to store the indices of buildings that receive direct sunlight.
  2. Iterate through the list of buildings from left to right.
  3. For each building, check if its elevation is greater than or equal to the elevation of any subsequent building.
  4. If it is, add the current index to sunlightReceivers and update the last index where we found a building that receives direct sunlight.
  5. Return the length of sunlightReceivers, which represents the number of buildings that receive direct sunlight.

Optimized Solutions

Java

View on GeeksforGeeks
public int countSunlightReceivers(int[] elevations) {
    int sunlightReceivers = 0;
    for (int i = 0; i < elevations.length; i++) {
        boolean receivesDirectSunlight = true;
        for (int j = i + 1; j < elevations.length; j++) {
            if (elevations[i] <= elevations[j]) {
                receivesDirectSunlight = false;
                break;
            }
        }
        if (receivesDirectSunlight) {
            sunlightReceivers++;
        }
    }
    return sunlightReceivers;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.