Open In App

Number of buildings facing the sun

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array representing heights of buildings. The array has buildings from left to right as shown in below diagram, count number of buildings facing the sunset. It is assumed that heights of all buildings are distinct.

Examples: 

Input : arr[] = {7, 4, 8, 2, 9}
Output: 3
Explanation: As 7 is the first element, it can
see the sunset.
4 can't see the sunset as 7 is hiding it.
8 can see.
2 can't see the sunset.
9 also can see the sunset.

Input : arr[] = {2, 3, 4, 5}
Output : 4

Asked in : Amazon Interview

Method 1: Iterative approch

It can be easily observed that only the maximum element found so far will see the sunlight 
i.e. curr_max will see the sunlight and then only the element greater than curr_max will see the sunlight. We traverse given array from left to right. We keep track of maximum element seen so far. Whenever an element becomes more than current max, increment result and update current max.

Implementation:

C++
// C++ program to count buildings that can
// see sunlight.
#include <iostream>
using namespace std;

// Returns count buildings 
// that can see sunlight
int countBuildings(int arr[], int n)
{
    // Initialize result (Note that first building
    // always sees sunlight)
    int count = 1;

    // Start traversing element
    int curr_max = arr[0];
    for (int i = 1; i < n; i++) {
      
        // If curr_element is maximum
        // or current element is
        // equal, update maximum and increment count
        if (arr[i] > curr_max || arr[i] == curr_max) {
            count++;
            curr_max = arr[i];
        }
    }

    return count;
}

// Driver code
int main()
{
    int arr[] = { 7, 4, 8, 2, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countBuildings(arr, n);
    return 0;
}
Java
// Java program to count buildings that can
// see sunlight.

class Test {
    // Returns count buildings that can see sunlight
    static int countBuildings(int arr[], int n)
    {
        // Initialize result  (Note that first building
        // always sees sunlight)
        int count = 1;

        // Start traversing element
        int curr_max = arr[0];
        for (int i = 1; i < n; i++) {
          
            // If curr_element is maximum 
            // or current element
            // is equal, update maximum and increment count
            if (arr[i] > curr_max || arr[i] == curr_max) {
                count++;
                curr_max = arr[i];
            }
        }

        return count;
    }

    // Driver method
    public static void main(String[] args)
    {
        int arr[] = { 7, 4, 8, 2, 9 };

        System.out.println(countBuildings(arr, arr.length));
    }
}
Python3
# Python3 program to count buildings
# that can see sunlight.

# Returns count buildings that
# can see sunlight


def countBuildings(arr, n):

    # Initialize result (Note that first
    # building always sees sunlight)
    count = 1

    # Start traversing element
    curr_max = arr[0]
    for i in range(1, n):

        # If curr_element is maximum or 
        # current element is equal,
        # update maximum and increment count
        if (arr[i] > curr_max or arr[i] == curr_max):

            count += 1
            curr_max = arr[i]

    return count


# Driver code
arr = [7, 4, 8, 2, 9]
n = len(arr)
print(countBuildings(arr, n))

# This code is contributed by Rohit.
C#
// C# program to count buildings that can
// see sunlight.
using System;

class GFG {
  
    // Returns count buildings 
    // that can see sunlight
    static int countBuildings(int[] arr, int n)
    {
        
        // Initialize result (Note that first building
        // always sees sunlight)
        int count = 1;

        // Start traversing element
        int curr_max = arr[0];
        for (int i = 1; i < n; i++) {
          
            // If curr_element is maximum 
            // or current element
            // is equal, update maximum 
            // and increment count
            if (arr[i] > curr_max || arr[i] == curr_max) {
                count++;
                curr_max = arr[i];
            }
        }

        return count;
    }

    // Driver method
    public static void Main()
    {
        int[] arr = { 7, 4, 8, 2, 9 };

        Console.Write(countBuildings(arr, arr.Length));
    }
}

// This code is contributed by Rohit.
Javascript
<script>

// Javascript program to count buildings that can
// see sunlight.

// Returns count buildings 
// that can see sunlight
function countBuildings( arr, n)
{
    // Initialize result (Note that first building
    // always sees sunlight)
    let count = 1;

    // Start traversing element
    let curr_max = arr[0];
    for (let i = 1; i < n; i++) {
      
        // If curr_element is maximum
        // or current element is
        // equal, update maximum and increment count
        if (arr[i] > curr_max || arr[i] == curr_max) {
            count++;
            curr_max = arr[i];
        }
    }

    return count;
}

    
    // Driver program
    
    let arr = [ 7, 4, 8, 2, 9 ];
    let n = arr.length;
    document.write(countBuildings(arr, n));
       
</script>
PHP
<?php
// php program to count buildings
// that can see sunlight.

// Returns count buildings that 
// can see sunlight
function countBuildings($arr, $n)
{
    // Initialize result (Note that
    // first building always sees 
    // sunlight)
    $count = 1;

    // Start traversing element
    $curr_max = $arr[0];
    for ( $i = 1; $i < $n; $i++)
    {
        
        // If curr_element is maximum or
        // current element is equal,
        // update maximum and 
        // increment count
        if ($arr[$i] > $curr_max || $arr[$i] == $curr_max)
        {
            $count++;
            $curr_max=$arr[$i];
        }
    }

    return $count;
}

// Driver code
$arr = array(7, 4, 8, 2, 9);
$n = sizeof($arr) / sizeof($arr[0]);
echo countBuildings($arr, $n);

// This code is contributed by 
// Rohit
?>

Output
3

Time Complexity: O(n) 
Auxiliary Space: O(1)

Method 2: Using Stack (Previous greater element)

Here, we are taking stack and by using it we are finding the previous greater element in the given array which is height of building.

Then after finding previous greater element then we see that if previous greater is -1 then it don’t have any previous greater that means it can see sun easily, because no interruption by long building.

So count the number of -1 in previous greater array and print it as result.

C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

// Function to count the number of buildings facing the sun
int countBuildings(int h[], int n) {
    // Using stack to keep track of buildings that can see the sun
    stack<int> s;
    // Vector to store the indexes of buildings that can see the sun
    vector<int> ans;
    // Push a sentinel value to the stack
    s.push(-1);
    
    // Iterate through each building height
    for(int i = 0; i < n; i++) {
        int k = h[i];
        // Pop buildings from the stack until a taller building or the sentinel value is encountered
        while(s.top() < k && s.top() != -1) {
            s.pop();
        }
        // Store the index of the building that can see the sun
        ans.push_back(s.top());
        // Push the current building height to the stack
        s.push(k);
    }
    
    // Count the number of buildings that initially faced the sun
    int count = 0;
    for(int i = 0; i < n; i++) {
        if(ans[i] == -1) {
            count++;
        }
    }
    return count;
}

// Main function
int main() {
    // Array representing the heights of buildings
    int h[] = {7, 4, 8, 2, 9};
    int n = sizeof(h) / sizeof(h[0]); // Calculate the size of the array
    
    // Call the function to count the number of buildings facing the sun and print the result
    cout << "Number of buildings facing the sun: " << countBuildings(h, n) << endl;

    return 0;
}
Java
import java.util.Stack;

public class Main {

    // Function to count the number of buildings facing the sun
    static int countBuildings(int[] h) {
        Stack<Integer> s = new Stack<>();
        int n = h.length;
        int[] ans = new int[n];
        s.push(-1);

        for (int i = 0; i < n; i++) {
            int k = h[i];
            while (!s.isEmpty() && s.peek() < k) { // Check if the stack is empty before calling peek()
                s.pop();
            }
            ans[i] = s.isEmpty() ? -1 : s.peek(); // Check if the stack is empty before calling peek()
            s.push(k);
        }

        int count = 0;
        for (int value : ans) {
            if (value == -1) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] h = {7, 4, 8, 2, 9};
        System.out.println("Number of buildings facing the sun: " + countBuildings(h));
    }
}
Python3
def countBuildings(h):
    s = [-1]
    ans = []

    for height in h:
        while s[-1] < height and s[-1] != -1:
            s.pop()
        ans.append(s[-1])
        s.append(height)

    count = sum(1 for value in ans if value == -1)
    return count

# Main function
h = [7, 4, 8, 2, 9]
print("Number of buildings facing the sun:", countBuildings(h))
C#
using System;
using System.Collections.Generic;

public class Program
{
    // Function to count the number of buildings facing the sun
    static int CountBuildings(int[] h)
    {
        Stack<int> s = new Stack<int>();
        int n = h.Length;
        int[] ans = new int[n];
        s.Push(-1);

        for (int i = 0; i < n; i++)
        {
            int k = h[i];
            while (s.Peek() < k && s.Peek() != -1)
            {
                s.Pop();
            }
            ans[i] = s.Peek();
            s.Push(k);
        }

        int count = 0;
        foreach (int value in ans)
        {
            if (value == -1)
            {
                count++;
            }
        }
        return count;
    }

    public static void Main(string[] args)
    {
        int[] h = { 7, 4, 8, 2, 9 };
        Console.WriteLine("Number of buildings facing the sun: " + CountBuildings(h));
    }
}
JavaScript
// Function to count the number of buildings facing the sun
function countBuildings(h) {
    const s = [-1];
    const ans = [];

    for (const height of h) {
        while (s[s.length - 1] < height && s[s.length - 1] !== -1) {
            s.pop();
        }
        ans.push(s[s.length - 1]);
        s.push(height);
    }

    let count = 0;
    for (const value of ans) {
        if (value === -1) {
            count++;
        }
    }
    return count;
}

// Main function
const h = [7, 4, 8, 2, 9];
console.log("Number of buildings facing the sun:", countBuildings(h));
PHP
<?php

// Function to count the number of buildings facing the sun
function countBuildings($h) {
    $s = [-1];
    $ans = [];
    $n = count($h);

    for ($i = 0; $i < $n; $i++) {
        $k = $h[$i];
        while (end($s) < $k && end($s) != -1) {
            array_pop($s);
        }
        $ans[] = end($s);
        array_push($s, $k);
    }

    $count = 0;
    foreach ($ans as $value) {
        if ($value == -1) {
            $count++;
        }
    }
    return $count;
}

// Main function
$h = [7, 4, 8, 2, 9];
echo "Number of buildings facing the sun: " . countBuildings($h) . "\n";
?>

Output
Number of buildings facing the sun: 3

Time Complexity: O(n) 

Auxiliary Space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads