Number of buildings facing the sun
Last Updated :
19 Mar, 2025
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>
using namespace std;
int longest(vector<int>& arr) {
int n = arr.size();
// base case
if (n == 0)
return 0;
// Answer is set to one as first
// building will get light
int ans = 0;
for (int i = 0; i < n; i++) {
bool maxi = true;
// For each building, check all
// the buildings on its left side.
for (int j = 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++;
}
}
return ans;
}
int main() {
vector<int> arr = {6, 2, 8, 4, 11, 13};
cout << longest(arr) << endl;
return 0;
}
C
// C Program to find number of
// buildings facing sun
#include <stdio.h>
int longest(int arr[], int n) {
// base case
if (n == 0) return 0;
// Answer is set to zero
int ans = 0;
for (int i = 0; i < n; i++) {
int maxi = 1;
// For each building, check all
// the buildings on its left side.
for (int j = 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++;
}
}
return ans;
}
int main() {
int arr[] = {6, 2, 8, 4, 11, 13};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longest(arr, n));
return 0;
}
Java
// Java Program to find number of
// buildings facing sun
class GfG {
static int longest(int[] arr) {
int n = arr.length;
// base case
if (n == 0) return 0;
// Answer is set to zero
int ans = 0;
for (int i = 0; i < n; i++) {
boolean maxi = true;
// For each building, check all
// the buildings on its left side.
for (int j = 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++;
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = {6, 2, 8, 4, 11, 13};
System.out.println(longest(arr));
}
}
Python
# Python Program to find number of
# buildings facing sun
def longest(arr):
n = len(arr)
# base case
if n == 0:
return 0
# Answer is set to zero
ans = 0
for i in range(n):
maxi = True
# For each building, check all
# the buildings on its left side.
for j in range(i):
# 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 += 1
return ans
if __name__ == "__main__":
arr = [6, 2, 8, 4, 11, 13]
print(longest(arr))
C#
// C# Program to find number of
// buildings facing sun
using System;
class GfG {
static int Longest(int[] arr) {
int n = arr.Length;
// base case
if (n == 0) return 0;
int ans = 0;
for (int i = 0; i < n; i++) {
bool maxi = true;
// For each building, check all
// the buildings on its left side.
for (int j = 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++;
}
}
return ans;
}
static void Main(string[] args) {
int[] arr = {6, 2, 8, 4, 11, 13};
Console.WriteLine(Longest(arr));
}
}
JavaScript
// JavaScript Program to find number of
// buildings facing sun
function longest(arr) {
let n = arr.length;
// base case
if (n === 0) return 0;
let ans = 0;
for (let i = 0; i < n; i++) {
let maxi = true;
// For each building, check all
// the buildings on its left side.
for (let j = 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++;
}
}
return ans;
}
let arr = [6, 2, 8, 4, 11, 13];
console.log(longest(arr));
[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>
using namespace std;
int longest(const vector<int>& arr) {
stack<int> s;
int count = 0;
for (int i = 0; i < arr.size(); ++i) {
while (!s.empty() && arr[s.top()] <= arr[i]) {
s.pop();
}
// If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
// Also, the very last building will always receive sunlight.
if (s.empty() || i == arr.size() - 1) {
count++;
}
s.push(i);
}
return count;
}
int main() {
vector<int> arr = {6, 2, 8, 4, 11, 13};
cout << longest(arr) << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
int longest(int* arr, int size) {
int* stack = (int*)malloc(size * sizeof(int));
int top = -1;
int count = 0;
for (int i = 0; i < size; ++i) {
while (top != -1 && arr[stack[top]] <= arr[i]) {
top--;
}
// If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
// Also, the very last building will always receive sunlight.
if (top == -1 || i == size - 1) {
count++;
}
stack[++top] = i;
}
free(stack);
return count;
}
int main() {
int arr[] = {6, 2, 8, 4, 11, 13};
int size = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longest(arr, size));
return 0;
}
Java
import java.util.Stack;
public class GfG {
public static int longest(int[] arr) {
Stack<Integer> s = new Stack<>();
int count = 0;
for (int i = 0; i < arr.length; ++i) {
while (!s.isEmpty() && arr[s.peek()] <= arr[i]) {
s.pop();
}
// If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
// Also, the very last building will always receive sunlight.
if (s.isEmpty() || i == arr.length - 1) {
count++;
}
s.push(i);
}
return count;
}
public static void main(String[] args) {
int[] arr = {6, 2, 8, 4, 11, 13};
System.out.println(longest(arr));
}
}
Python
def longest(arr):
stack = []
count = 0
for i in range(len(arr)):
while stack and arr[stack[-1]] <= arr[i]:
stack.pop()
# If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
# Also, the very last building will always receive sunlight.
if not stack or i == len(arr) - 1:
count += 1
stack.append(i)
return count
arr = [6, 2, 8, 4, 11, 13]
print(longest(arr))
C#
using System;
using System.Collections.Generic;
class GfG {
static int Longest(int[] arr) {
Stack<int> s = new Stack<int>();
int count = 0;
for (int i = 0; i < arr.Length; ++i) {
while (s.Count > 0 && arr[s.Peek()] <= arr[i]) {
s.Pop();
}
// If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
// Also, the very last building will always receive sunlight.
if (s.Count == 0 || i == arr.Length - 1) {
count++;
}
s.Push(i);
}
return count;
}
static void Main() {
int[] arr = { 6, 2, 8, 4, 11, 13 };
Console.WriteLine(Longest(arr));
}
}
JavaScript
function longest(arr) {
let stack = [];
let count = 0;
for (let i = 0; i < arr.length; ++i) {
while (stack.length > 0 && arr[stack[stack.length - 1]] <= arr[i]) {
stack.pop();
}
// If the stack is empty, it means there are no taller buildings to the right (that haven't been removed).
// Also, the very last building will always receive sunlight.
if (stack.length === 0 || i === arr.length - 1) {
count++;
}
stack.push(i);
}
return count;
}
const arr = [6, 2, 8, 4, 11, 13];
console.log(longest(arr));
[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>
using namespace std;
int longest(vector<int>& arr) {
int n = arr.size();
// base case
if (n == 0) return 0;
// Answer is set to one as first
// building will get light
int ans = 1;
// It will hold the value of maximum
// height of a building.
int maxi = arr[0];
for (int i = 1; i < n ; i++) {
// If the current building has
// the maximum height so far
if (arr[i] >= maxi) {
// Increment the answer
ans++;
// Update maximum value
maxi = arr[i];
}
}
return ans;
}
int main() {
vector<int> arr = {6, 2, 8, 4, 11, 13};
cout << longest(arr) << endl;
return 0;
}
C
// C Program to find number of
// buildings facing sun
#include <stdio.h>
// Function to find the number of buildings facing sun
int longest(int arr[], int n) {
// base case
if (n == 0) return 0;
// Answer is set to one as first
// building will get light
int ans = 1;
// It will hold the value of maximum
// height of a building.
int maxi = arr[0];
for (int i = 1; i < n; i++) {
// If the current building has
// the maximum height so far
if (arr[i] >= maxi) {
// Increment the answer
ans++;
// Update maximum value
maxi = arr[i];
}
}
return ans;
}
int main() {
int arr[] = {6, 2, 8, 4, 11, 13};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longest(arr, n));
return 0;
}
Java
// Java Program to find number of
// buildings facing sun
import java.util.*;
class GfG {
static int longest(int arr[]) {
int n = arr.length;
// base case
if (n == 0) return 0;
// Answer is set to one as first
// building will get light
int ans = 1;
// It will hold the value of maximum
// height of a building.
int maxi = arr[0];
for (int i = 1; i < n; i++) {
// If the current building has
// the maximum height so far
if (arr[i] >= maxi) {
// Increment the answer
ans++;
// Update maximum value
maxi = arr[i];
}
}
return ans;
}
public static void main(String[] args) {
int arr[] = {6, 2, 8, 4, 11, 13};
System.out.println(longest(arr));
}
}
Python
# Python Program to find number of
# buildings facing sun
def longest(arr):
n = len(arr)
# base case
if n == 0:
return 0
# Answer is set to one as first
# building will get light
ans = 1
# It will hold the value of maximum
# height of a building.
maxi = arr[0]
for i in range(1, n):
# If the current building has
# the maximum height so far
if arr[i] >= maxi:
# Increment the answer
ans += 1
# Update maximum value
maxi = arr[i]
return ans
if __name__ == "__main__":
arr = [6, 2, 8, 4, 11, 13]
print(longest(arr))
C#
// C# Program to find number of
// buildings facing sun
using System;
using System.Collections.Generic;
class GfG {
static int Longest(int[] arr) {
int n = arr.Length;
// base case
if (n == 0) return 0;
// Answer is set to one as first
// building will get light
int ans = 1;
// It will hold the value of maximum
// height of a building.
int maxi = arr[0];
for (int i = 1; i < n; i++) {
// If the current building has
// the maximum height so far
if (arr[i] >= maxi) {
// Increment the answer
ans++;
// Update maximum value
maxi = arr[i];
}
}
return ans;
}
static void Main(string[] args) {
int[] arr = { 6, 2, 8, 4, 11, 13 };
Console.WriteLine(Longest(arr));
}
}
JavaScript
// JavaScript Program to find number of
// buildings facing sun
function longest(arr) {
const n = arr.length;
// base case
if (n === 0) return 0;
// Answer is set to one as first
// building will get light
let ans = 1;
// It will hold the value of maximum
// height of a building.
let maxi = arr[0];
for (let i = 1; i < n; i++) {
// If the current building has
// the maximum height so far
if (arr[i] >= maxi) {
// Increment the answer
ans++;
// Update maximum value
maxi = arr[i];
}
}
return ans;
}
const arr = [6, 2, 8, 4, 11, 13];
console.log(longest(arr));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem