Skip to content
Related Articles

Related Articles

Improve Article

Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building

  • Difficulty Level : Expert
  • Last Updated : 04 Sep, 2021

Given an array arr[] consisting of N integers, where each array element represents the height of a building situated on the X co-ordinates, the task is to check if it is possible to select 3 buildings, such that the third selected building is taller than the first selected building and shorter than the second selected building.

Examples:

Input: arr[] = {4, 7, 11, 5, 13, 2}
Output: Yes
Explanation:
One possible way is to select the building at indices [0, 1, 3] with heights 4, 7 and 5 respectively.

Input: arr[] = {11, 11, 12, 9}
Output: No

Approach: The given problem can be solved using the Stack data structure. Follow the steps below to solve the problem:



  • If N is less than 3, then print “No“.
  • Initialize an array, say preMin[], to store the prefix minimum array of array arr[].
  • Traverse the array arr[] and update preMin[i] as preMin[i] = min(preMin[i-1], arr[i]).
  • Now, initialize a Stack, say stack, to store the elements from the ending in ascending order.
  • Traverse the array arr[] in reverse using a variable, say i, and perform the following steps:
  • After completing the above steps, if none of the above cases satisfy, then print “No“.

Below is the implementation of the above approach:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
string recreationalSpot(int arr[], int N)
{
 
    if (N < 3) {
        return "No";
    }
 
    // Stores prefix min array
    int preMin[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for (int i = 1; i < N; i++) {
        preMin[i] = min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    stack<int> stack;
 
    // Iterate until j is greater than
    // or equal to 0
    for (int j = N - 1; j >= 0; j--) {
 
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j]) {
 
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
 
            while (!stack.empty()
                   && stack.top() <= preMin[j]) {
                // Remove the top element
                stack.pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (!stack.empty() && stack.top() < arr[j]) {
                return "Yes";
            }
            // Push the arr[j] in stack
            stack.push(arr[j]);
        }
    }
    // If none of the above case
    // satisfy then return "No"
    return "No";
}
 
// Driver code
int main()
{
    // Input
    int arr[] = { 4, 7, 11, 5, 13, 2 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    cout << recreationalSpot(arr, size);
}

Java




// Java implementation of the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
static String recreationalSpot(int arr[], int N)
{
    if (N < 3)
    {
        return "No";
    }
 
    // Stores prefix min array
    int preMin[] = new int[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for(int i = 1; i < N; i++)
    {
        preMin[i] = Math.min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    Stack<Integer> stack = new Stack<Integer>();
 
    // Iterate until j is greater than
    // or equal to 0
    for(int j = N - 1; j >= 0; j--)
    {
         
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j])
        {
             
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
            while (stack.empty() == false &&
                   stack.peek() <= preMin[j])
            {
                 
                // Remove the top element
                stack.pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (stack.empty() == false &&
                stack.peek() < arr[j])
            {
                return "Yes";
            }
             
            // Push the arr[j] in stack
            stack.push(arr[j]);
        }
    }
     
    // If none of the above case
    // satisfy then return "No"
    return "No";
}
 
// Driver code
public static void main(String[] args)
{
     
    // Input
    int arr[] = { 4, 7, 11, 5, 13, 2 };
    int size = arr.length;
 
    System.out.println(recreationalSpot(arr, size));
}
}
 
// This code is contributed by Dharanendra L V.

Python3




# Python3 implementation of the above approach
 
# Function to check if it is possible
# to select three buildings that
# satisfy the given condition
def recreationalSpot(arr, N):
     
    if (N < 3):
        return "No"
 
    # Stores prefix min array
    preMin = [0] * N
    preMin[0] = arr[0]
 
    # Iterate over the range [1, N-1]
    for i in range(1, N):
        preMin[i] = min(preMin[i - 1], arr[i])
 
    # Stores the element from the
    # ending in increasing order
    stack = []
 
    # Iterate until j is greater than
    # or equal to 0
    for j in range(N - 1, -1, -1):
         
        # If current array element is
        # greater than the prefix min
        # upto j
        if (arr[j] > preMin[j]):
 
            # Iterate while stack is not
            # empty and top element is
            # less than or equal to preMin[j]
            while (len(stack) > 0 and
                   stack[-1] <= preMin[j]):
                        
                # Remove the top element
                del stack[-1]
 
            # If stack is not empty and top
            # element of the stack is less
            # than the current element
            if (len(stack) > 0 and stack[-1] < arr[j]):
                return "Yes"
 
            # Push the arr[j] in stack
            stack.append(arr[j])
 
    # If none of the above case
    # satisfy then return "No"
    return "No"
 
# Driver code
if __name__ == '__main__':
     
    # Input
    arr =  [ 4, 7, 11, 5, 13, 2 ]
    size = len(arr)
 
    print (recreationalSpot(arr, size))
 
# This code is contributed by mohit kumar 29

C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
public class GFG{
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
static String recreationalSpot(int []arr, int N)
{
    if (N < 3)
    {
        return "No";
    }
 
    // Stores prefix min array  
    int []preMin = new int[N];
    preMin[0] = arr[0];
 
    // Iterate over the range [1, N-1]
    for(int i = 1; i < N; i++)
    {
        preMin[i] = Math.Min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    Stack<int> stack = new Stack<int>();
 
    // Iterate until j is greater than
    // or equal to 0
    for(int j = N - 1; j >= 0; j--)
    {
         
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j])
        {
             
            // Iterate while stack is not
            // empty and top element is
            // less than or equal to preMin[j]
            while (stack.Count!=0 &&
                   stack.Peek() <= preMin[j])
            {
                 
                // Remove the top element
                stack.Pop();
            }
 
            // If stack is not empty and top
            // element of the stack is less
            // than the current element
            if (stack.Count!=0 &&
                stack.Peek() < arr[j])
            {
                return "Yes";
            }
             
            // Push the arr[j] in stack
            stack.Push(arr[j]);
        }
    }
     
    // If none of the above case
    // satisfy then return "No"
    return "No";
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Input
    int []arr = { 4, 7, 11, 5, 13, 2 };
    int size = arr.Length;
 
    Console.WriteLine(recreationalSpot(arr, size));
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// JavaScript implementation of the above approach
 
// Function to check if it is possible
// to select three buildings that
// satisfy the given condition
function recreationalSpot(arr, N)
{
 
    if (N < 3) {
        return "No";
    }
 
    // Stores prefix min array
    var preMin = new Array(N);
    preMin[0] = arr[0];
    var i;
    // Iterate over the range [1, N-1]
    for (i = 1; i < N; i++) {
        preMin[i] = Math.min(preMin[i - 1], arr[i]);
    }
 
    // Stores the element from the
    // ending in increasing order
    var st = [];
    var j;
    // Iterate until j is greater than
    // or equal to 0
    for (j = N - 1; j >= 0; j--) {
 
        // If current array element is
        // greater than the prefix min
        // upto j
        if (arr[j] > preMin[j]) {
 
            // Iterate while st is not
            // empty and top element is
            // less than or equal to preMin[j]
 
            while (st.length>0
                   && st[st.length-1] <= preMin[j]) {
                // Remove the top element
                st.pop();
            }
 
            // If st is not empty and top
            // element of the st is less
            // than the current element
            if (st.length>0 && st[st.length-1] < arr[j]) {
                return "Yes";
            }
            // Push the arr[j] in st
            st.push(arr[j]);
        }
    }
    // If none of the above case
    // satisfy then return "No"
    return "No";
}
 
// Driver code
 
    // Input
    var arr = [4, 7, 11, 5, 13, 2];
    var size = arr.length;
 
    document.write(recreationalSpot(arr, size));
 
</script>
Output: 
Yes

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :