Given the array arr[] of heights of certain buildings that lie adjacent to each other, Sunlight starts falling from the left side of the buildings. If there is a building of a certain height, all the buildings to the right side of it having lesser heights cannot see the sun. The task is to find the total number of buildings that receive sunlight.
Examples:
Input: arr[] = [6, 2, 8, 4, 11, 13] Output: 4 Explanation: Only buildings of height 6, 8, 11 and 13 can see the sun, hence output is 4.
Input: arr[] = [2, 5, 1, 8, 3] Output: 3 Explanation: Only buildings of height 2, 5 and 8 can see the sun, hence output is 3.
[Naive Approach] Using Nested loop - O(n^2) Time and O(1) Space
The idea is to compare each building's height with all the buildings on its left side. If any building's height is greater than current building's height, then continue. Otherwise, increment the answer.
C++
// C++ Program to find number of// buildings facing sun#include<bits/stdc++.h>usingnamespacestd;intlongest(vector<int>&arr){intn=arr.size();// base caseif(n==0)return0;// Answer is set to one as first// building will get lightintans=0;for(inti=0;i<n;i++){boolmaxi=true;// For each building, check all// the buildings on its left side.for(intj=0;j<i;j++){// If a building has greater height// than current building, then set// maxi = false.if(arr[j]>arr[i]){maxi=false;break;}}// If the current building's height// is greater than all buildings on// left side, then increment answer.if(maxi){ans++;}}returnans;}intmain(){vector<int>arr={6,2,8,4,11,13};cout<<longest(arr)<<endl;return0;}
C
// C Program to find number of // buildings facing sun#include<stdio.h>intlongest(intarr[],intn){// base caseif(n==0)return0;// Answer is set to zerointans=0;for(inti=0;i<n;i++){intmaxi=1;// For each building, check all // the buildings on its left side.for(intj=0;j<i;j++){// If a building has greater height // than current building, then set// maxi = false.if(arr[j]>arr[i]){maxi=0;break;}}// If the current building's height// is greater than all buildings on// left side, then increment answer.if(maxi){ans++;}}returnans;}intmain(){intarr[]={6,2,8,4,11,13};intn=sizeof(arr)/sizeof(arr[0]);printf("%d\n",longest(arr,n));return0;}
Java
// Java Program to find number of // buildings facing sunclassGfG{staticintlongest(int[]arr){intn=arr.length;// base caseif(n==0)return0;// Answer is set to zerointans=0;for(inti=0;i<n;i++){booleanmaxi=true;// For each building, check all // the buildings on its left side.for(intj=0;j<i;j++){// If a building has greater height // than current building, then set// maxi = false.if(arr[j]>arr[i]){maxi=false;break;}}// If the current building's height// is greater than all buildings on// left side, then increment answer.if(maxi){ans++;}}returnans;}publicstaticvoidmain(String[]args){int[]arr={6,2,8,4,11,13};System.out.println(longest(arr));}}
Python
# Python Program to find number of # buildings facing sundeflongest(arr):n=len(arr)# base caseifn==0:return0# Answer is set to zeroans=0foriinrange(n):maxi=True# For each building, check all # the buildings on its left side.forjinrange(i):# If a building has greater height # than current building, then set# maxi = False.ifarr[j]>arr[i]:maxi=Falsebreak# If the current building's height# is greater than all buildings on# left side, then increment answer.ifmaxi:ans+=1returnansif__name__=="__main__":arr=[6,2,8,4,11,13]print(longest(arr))
C#
// C# Program to find number of // buildings facing sunusingSystem;classGfG{staticintLongest(int[]arr){intn=arr.Length;// base caseif(n==0)return0;intans=0;for(inti=0;i<n;i++){boolmaxi=true;// For each building, check all // the buildings on its left side.for(intj=0;j<i;j++){// If a building has greater height // than current building, then set// maxi = false.if(arr[j]>arr[i]){maxi=false;break;}}// If the current building's height// is greater than all buildings on// left side, then increment answer.if(maxi){ans++;}}returnans;}staticvoidMain(string[]args){int[]arr={6,2,8,4,11,13};Console.WriteLine(Longest(arr));}}
JavaScript
// JavaScript Program to find number of // buildings facing sunfunctionlongest(arr){letn=arr.length;// base caseif(n===0)return0;letans=0;for(leti=0;i<n;i++){letmaxi=true;// For each building, check all // the buildings on its left side.for(letj=0;j<i;j++){// If a building has greater height // than current building, then set// maxi = false.if(arr[j]>arr[i]){maxi=false;break;}}// If the current building's height// is greater than all buildings on// left side, then increment answer.if(maxi){ans++;}}returnans;}letarr=[6,2,8,4,11,13];console.log(longest(arr));
Output
4
[Expected Approach - 1] Using Stack - O(n) time and O(n) space
We use a stack to keep track of buildings that can see the sunlight. As we iterate through the array, for each building, we pop the stack if any building in the stack is shorter or equal to the current building. The stack ultimately stores only the buildings that can receive sunlight.
C++
#include<iostream>#include<vector>#include<stack>usingnamespacestd;intlongest(constvector<int>&arr){stack<int>s;intcount=0;for(inti=0;i<arr.size();++i){// Remove all smaller or equal buildings on the leftwhile(!s.empty()&&s.top()<=arr[i]){s.pop();}// If stack is empty, no taller building exists on the leftif(s.empty()){count++;}// Push current building heights.push(arr[i]);}returncount;}intmain(){vector<int>arr={6,2,8,4,11,13};cout<<longest(arr)<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>intlongest(int*arr,intsize){int*stack=(int*)malloc(size*sizeof(int));inttop=-1;intcount=0;for(inti=0;i<size;++i){// Remove all smaller or equal buildings on the leftwhile(top!=-1&&stack[top]<=arr[i]){top--;}// If stack is empty, no taller building exists on the leftif(top==-1){count++;}// Push current building heightstack[++top]=arr[i];}free(stack);returncount;}intmain(){intarr[]={6,2,8,4,11,13};intsize=sizeof(arr)/sizeof(arr[0]);printf("%d\n",longest(arr,size));return0;}
Java
importjava.util.Stack;publicclassGfG{publicstaticintlongest(int[]arr){Stack<Integer>s=newStack<>();intcount=0;for(inti=0;i<arr.length;++i){// Remove all smaller or equal buildings on the leftwhile(!s.isEmpty()&&s.peek()<=arr[i]){s.pop();}// If stack is empty, no taller building exists on the leftif(s.isEmpty()){count++;}// Push current building heights.push(arr[i]);}returncount;}publicstaticvoidmain(String[]args){int[]arr={6,2,8,4,11,13};System.out.println(longest(arr));}}
Python
deflongest(arr):stack=[]count=0foriinrange(len(arr)):# Remove all smaller or equal buildings on the leftwhilestackandstack[-1]<=arr[i]:stack.pop()# If stack is empty, no taller building exists on the leftifnotstack:count+=1# Push current building heightstack.append(arr[i])returncountarr=[6,2,8,4,11,13]print(longest(arr))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticintLongest(int[]arr){Stack<int>s=newStack<int>();intcount=0;for(inti=0;i<arr.Length;++i){// Remove all smaller or equal buildings on the leftwhile(s.Count>0&&s.Peek()<=arr[i]){s.Pop();}// If stack is empty, no taller building exists on the leftif(s.Count==0){count++;}// Push current building heights.Push(arr[i]);}returncount;}staticvoidMain(){int[]arr={6,2,8,4,11,13};Console.WriteLine(Longest(arr));}}
JavaScript
functionlongest(arr){letstack=[];letcount=0;for(leti=0;i<arr.length;++i){// Remove all smaller or equal buildings on the leftwhile(stack.length>0&&stack[stack.length-1]<=arr[i]){stack.pop();}// If stack is empty, no taller building exists on the leftif(stack.length===0){count++;}// Push current building heightstack.push(arr[i]);}returncount;}constarr=[6,2,8,4,11,13];console.log(longest(arr));
Output
4
[Expected Approach - 2] Using Iterative Method - O(n) Time and O(1) Space
The idea is to iterate over the array from left to right and compare each building's height with the maximum height of a building so far. If its height is greater than maximum height, then increment the answer and update the value of maximum height. Note: The first building will always receive sunlight as it does not have any building on its left side. So we can start iteration from second index and set maximum height to height of first building.
C++
// C++ Program to find number of // buildings facing sun#include<bits/stdc++.h>usingnamespacestd;intlongest(vector<int>&arr){intn=arr.size();// base caseif(n==0)return0;// Answer is set to one as first// building will get lightintans=1;// It will hold the value of maximum// height of a building.intmaxi=arr[0];for(inti=1;i<n;i++){// If the current building has// the maximum height so farif(arr[i]>=maxi){// Increment the answerans++;// Update maximum valuemaxi=arr[i];}}returnans;}intmain(){vector<int>arr={6,2,8,4,11,13};cout<<longest(arr)<<endl;return0;}
C
// C Program to find number of // buildings facing sun#include<stdio.h>// Function to find the number of buildings facing sunintlongest(intarr[],intn){// base caseif(n==0)return0;// Answer is set to one as first// building will get lightintans=1;// It will hold the value of maximum// height of a building.intmaxi=arr[0];for(inti=1;i<n;i++){// If the current building has// the maximum height so farif(arr[i]>=maxi){// Increment the answerans++;// Update maximum valuemaxi=arr[i];}}returnans;}intmain(){intarr[]={6,2,8,4,11,13};intn=sizeof(arr)/sizeof(arr[0]);printf("%d\n",longest(arr,n));return0;}
Java
// Java Program to find number of // buildings facing sunimportjava.util.*;classGfG{staticintlongest(intarr[]){intn=arr.length;// base caseif(n==0)return0;// Answer is set to one as first// building will get lightintans=1;// It will hold the value of maximum// height of a building.intmaxi=arr[0];for(inti=1;i<n;i++){// If the current building has// the maximum height so farif(arr[i]>=maxi){// Increment the answerans++;// Update maximum valuemaxi=arr[i];}}returnans;}publicstaticvoidmain(String[]args){intarr[]={6,2,8,4,11,13};System.out.println(longest(arr));}}
Python
# Python Program to find number of # buildings facing sundeflongest(arr):n=len(arr)# base caseifn==0:return0# Answer is set to one as first# building will get lightans=1# It will hold the value of maximum# height of a building.maxi=arr[0]foriinrange(1,n):# If the current building has# the maximum height so farifarr[i]>=maxi:# Increment the answerans+=1# Update maximum valuemaxi=arr[i]returnansif__name__=="__main__":arr=[6,2,8,4,11,13]print(longest(arr))
C#
// C# Program to find number of // buildings facing sunusingSystem;usingSystem.Collections.Generic;classGfG{staticintLongest(int[]arr){intn=arr.Length;// base caseif(n==0)return0;// Answer is set to one as first// building will get lightintans=1;// It will hold the value of maximum// height of a building.intmaxi=arr[0];for(inti=1;i<n;i++){// If the current building has// the maximum height so farif(arr[i]>=maxi){// Increment the answerans++;// Update maximum valuemaxi=arr[i];}}returnans;}staticvoidMain(string[]args){int[]arr={6,2,8,4,11,13};Console.WriteLine(Longest(arr));}}
JavaScript
// JavaScript Program to find number of // buildings facing sunfunctionlongest(arr){constn=arr.length;// base caseif(n===0)return0;// Answer is set to one as first// building will get lightletans=1;// It will hold the value of maximum// height of a building.letmaxi=arr[0];for(leti=1;i<n;i++){// If the current building has// the maximum height so farif(arr[i]>=maxi){// Increment the answerans++;// Update maximum valuemaxi=arr[i];}}returnans;}constarr=[6,2,8,4,11,13];console.log(longest(arr));