Tuesday, November 19, 2024
Google search engine
HomeData Modelling & AINumber of elements that can be seen from right side

Number of elements that can be seen from right side

Given an array of integers, consider the elements as the height of the building, find the number of buildings that can be seen from the right side.

Examples: 

Input : height[] = {2, 6, 2, 4, 0, 1}
Output : 3
we can see only 3 building i.e with height 1, 4 and 6.
Input : height[] = {4, 8, 2, 0, 0, 5}
Output : 2

This problem seems to be finding longest increasing sub sequence from right but actually it is not.We have to just increase the count if we encounter any building with greater height found so far. 

Below is the implementation of the above approach. 

C++




// CPP program to find number of elements
// that can be seen from right side.
#include <bits/stdc++.h>
using namespace std;
 
int numberOfElements(int height[], int n)
{
    int max_so_far = 0;
    int count = 0;
 
    for (int i = n - 1; i >= 0; i--) {
        if (height[i] > max_so_far) {
            max_so_far = height[i];
            count++;
        }
    }
    return count;
}
 
// Driver code
int main()
{
    int n = 6;
    int height[] = { 4, 8, 2, 0, 0, 5 };
    cout << numberOfElements(height, n);
    return 0;
}


Java




// Java program to find number of elements
// that can be seen from right side.
import java.util.*;
class Solution
{
  
static int numberOfElements(int height[], int n)
{
    int max_so_far = 0;
    int coun = 0;
  
    for (int i = n - 1; i >= 0; i--) {
        if (height[i] > max_so_far) {
            max_so_far = height[i];
            coun++;
        }
    }
    return coun;
}
 
// Driver code
public static void main(String args[])
{
    int n = 6;
    int height[] = { 4, 8, 2, 0, 0, 5 };
    System.out.println( numberOfElements(height, n));
   
}
 
}
//contributed by Arnab Kundu


Python3




# Python3 program to find
# number of elements
# that can be seen from right side
 
def numberOfElements(height, n):
     
    max_so_far = 0
    coun = 0
     
    for i in range(n-1,-1,-1):
        if height[i] > max_so_far:
            max_so_far = height[i]
            coun = coun + 1
    return coun
 
#Driver code
if __name__=='__main__':
    n = 6
    height = [4, 8, 2, 0, 0, 5]
    print(numberOfElements(height, n))
     
# This code is contributed by
# Shashank_Sharma    


C#




// C# program to find number of elements
// that can be seen from right side.
using System;
 
class GFG
{
public static int numberOfElements(int []height,
                                   int n)
{
    int max_so_far = 0;
    int coun = 0;
 
    for (int i = n - 1; i >= 0; i--)
    {
        if (height[i] > max_so_far)
        {
            max_so_far = height[i];
            coun++;
        }
    }
    return coun;
}
 
// Driver code
public static void Main()
{
    int n = 6;
    int []height = { 4, 8, 2, 0, 0, 5 };
    Console.WriteLine(numberOfElements(height, n));
}
}
 
// This code is contributed by Soumik


Javascript




<script>
// javascript program to find number of elements
// that can be seen from right side.
 
    function numberOfElements(height , n)
    {
        var max_so_far = 0;
        var coun = 0;
 
        for (let i = n - 1; i >= 0; i--)
        {
            if (height[i] > max_so_far)
            {
                max_so_far = height[i];
                coun++;
            }
        }
        return coun;
    }
 
    // Driver code
    var n = 6;
    var height = [ 4, 8, 2, 0, 0, 5 ];
    document.write(numberOfElements(height, n));
 
// This code is contributed by gauravrajput1
</script>


PHP




<?php
// PHP program to find number of elements
// that can be seen from right side.
 
function numberOfElements($height, $n)
{
    $max_so_far = 0;
    $coun = 0;
 
    for ($i = $n - 1; $i >= 0; $i--)
    {
        if ($height[$i] > $max_so_far)
        {
            $max_so_far = $height[$i];
            $coun++;
        }
    }
    return $coun;
}
 
// Driver code
$n = 6;
$height = array(4, 8, 2, 0, 0, 5 );
echo numberOfElements($height, $n);
 
// This code is contributed
// by Akanksha Rai


Output

2








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

Approach:

We can traverse the array from left to right and push the elements onto the stack. For each new element, we can pop all the elements from the stack that are smaller than the current element, as they cannot be seen from the right side. The number of buildings that can be seen from the right side will be the size of the stack after all the elements have been processed.

  • Create an empty stack and initialize the count of visible buildings to 0.
  • Traverse the array of heights from left to right, one element at a time.
  • For each element, check if it is greater than or equal to the top element of the stack. If it is, then pop all the elements from the stack that are smaller than the current element, as they cannot be seen from the right side.
  • After all the smaller elements have been popped from the stack, push the current element onto the stack.
  • The number of buildings that can be seen from the right side is the size of the stack after all the elements have been processed.
  • Return the count of visible buildings.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int numberOfElements(int height[], int n)
{
    stack<int> st;
    int count = 0;
    for (int i = 0; i < n; i++) {
        while (!st.empty() && height[i] >= st.top()) {
            st.pop();
        }
        st.push(height[i]);
    }
    return st.size();
}
 
// Driver code
int main()
{
    int n = 6;
    int height[] = { 4, 8, 2, 0, 0, 5 };
    cout << numberOfElements(height, n);
    return 0;
}


Java




import java.util.Stack;
 
public class GFG {
 
    // Function to calculate the number of elements left
    // after removing smaller or equal elements from the
    // right side of each element in the array
    public static int numberOfElements(int[] height)
    {
        Stack<Integer> st = new Stack<>();
        int count = 0;
        for (int i = 0; i < height.length; i++) {
            while (!st.isEmpty()
                   && height[i] >= st.peek()) {
                st.pop();
            }
            st.push(height[i]);
        }
        return st.size();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 6;
        int[] height = { 4, 8, 2, 0, 0, 5 };
        System.out.println(numberOfElements(height));
    }
}
 
// This code is contributed by shivamgupta310570


Python3




def numberOfElements(height, n):
    stack = []
    count = 0
    for i in range(n):
        while stack and height[i] >= stack[-1]:
            stack.pop()
        stack.append(height[i])
    return len(stack)
 
# Driver code
n = 6
height = [4, 8, 2, 0, 0, 5]
print(numberOfElements(height, n))
 
# THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL


C#




using System;
using System.Collections.Generic;
 
class  Gfg{
    static int numberOfElements(int[] height, int n)
    {
        Stack<int> st = new Stack<int>();
        for (int i = 0; i < n; i++) {
            while (st.Count>0 && height[i] >= st.Peek()) {
                st.Pop();
            }
            st.Push(height[i]);
        }
        return st.Count;
    }
     
    // Driver code
    static void Main(string[] args)
    {
        int n = 6;
        int[] height = { 4, 8, 2, 0, 0, 5 };
        Console.WriteLine(numberOfElements(height, n));
    }
}


Javascript




function numberOfElements(height, n) {
    const st = [];
    let count = 0;
    for (let i = 0; i < n; i++) {
        while (st.length > 0 && height[i] >= st[st.length - 1]) {
            st.pop();
        }
        st.push(height[i]);
    }
    return st.length;
}
 
// Driver code
const n = 6;
const height = [4, 8, 2, 0, 0, 5];
console.log(numberOfElements(height, n));
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Output

2








Time Complexity: O(n), where n is the number of elements in the input array. 

Auxiliary Space: O(n), as the worst-case scenario is when all the elements are in increasing order, and the stack will have all the n elements.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments