How to use Stack (Previous greater element) In Data Structures and Algorithms

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)



Number of buildings facing the sun

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

Similar Reads

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....

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....