Subsequence of size 3 with 3rd greater than the 1st and snaller than 2nd
Last Updated :
23 Jul, 2025
You are given an array arr of size n, where each element represents the height of a building positioned along the x-axis. Your task is to determine whether it is possible to choose three distinct buildings such that:
- The third building is taller than the first, and
- The third building is shorter than the second.
In other words, check if there exist indices i < j < k such that: arr[i] < arr[k] < arr[j].
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
Explanation: No 3 buildings fit the given condition.
Naive Approach - Three Nested Loops - O(n^3) Time and O(1) Space
We run three nested loops to consider all subsequences of size 3. As soon as we find a triplet that satisfies the given conditions, we return tree.
C++
#include <iostream>
#include <vector>
using namespace std;
bool isPossible(vector<int>& arr) {
int n = arr.size();
// Check all triplets (i, j, k) such that i < j < k
// and arr[i] < arr[k] < arr[j]
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] < arr[k] && arr[k] < arr[j])
return true;
}
}
}
return false;
}
int main() {
vector<int> arr1 = {4, 7, 11, 5, 13, 2};
cout << (isPossible(arr1) ? "Yes" : "No") << endl;
vector<int> arr2 = {11, 11, 12, 9};
cout << (isPossible(arr2) ? "Yes" : "No") << endl;
return 0;
}
Java
// Import necessary libraries
import java.util.*;
public class Main {
static boolean isPossible(int[] arr) {
int n = arr.length;
// Check all triplets (i, j, k) such that i < j < k
// and arr[i] < arr[k] < arr[j]
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] < arr[k] && arr[k] < arr[j])
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int[] arr1 = {4, 7, 11, 5, 13, 2};
System.out.println(isPossible(arr1) ? "Yes" : "No");
int[] arr2 = {11, 11, 12, 9};
System.out.println(isPossible(arr2) ? "Yes" : "No");
}
}
Python
# Define the function to check for triplets
def is_possible(arr):
n = len(arr)
# Check all triplets (i, j, k) such that i < j < k
# and arr[i] < arr[k] < arr[j]
for i in range(n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if arr[i] < arr[k] < arr[j]:
return True
return False
# Main execution
arr1 = [4, 7, 11, 5, 13, 2]
print("Yes" if is_possible(arr1) else "No")
arr2 = [11, 11, 12, 9]
print("Yes" if is_possible(arr2) else "No")
C#
// Import necessary libraries
using System;
using System.Linq;
public class MainClass {
static bool IsPossible(int[] arr) {
int n = arr.Length;
// Check all triplets (i, j, k) such that i < j < k
// and arr[i] < arr[k] < arr[j]
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] < arr[k] && arr[k] < arr[j])
return true;
}
}
}
return false;
}
public static void Main(string[] args) {
int[] arr1 = {4, 7, 11, 5, 13, 2};
Console.WriteLine(IsPossible(arr1) ? "Yes" : "No");
int[] arr2 = {11, 11, 12, 9};
Console.WriteLine(IsPossible(arr2) ? "Yes" : "No");
}
}
JavaScript
// Function to check for triplets
function isPossible(arr) {
const n = arr.length;
// Check all triplets (i, j, k) such that i < j < k
// and arr[i] < arr[k] < arr[j]
for (let i = 0; i < n - 2; i++) {
for (let j = i + 1; j < n - 1; j++) {
for (let k = j + 1; k < n; k++) {
if (arr[i] < arr[k] && arr[k] < arr[j])
return true;
}
}
}
return false;
}
// Main execution
const arr1 = [4, 7, 11, 5, 13, 2];
console.log(isPossible(arr1) ? "Yes" : "No");
const arr2 = [11, 11, 12, 9];
console.log(isPossible(arr2) ? "Yes" : "No");
[Expected Approach] - Using Stack - O(n) Time and O(n) Space
We process the array in reverse while keeping track of the minimum value seen so far from the left (using a prefix minimum array). This helps us identify a possible first building for each current building considered. For the minimum from the right side (or third value), we use a stack helps maintain candidates for the third building in ascending order, allowing constant-time comparisons.
Follow the below given step-by-step approach:
- If
N
is less than 3, return "No" as it's not possible to select three buildings. - Initialize a prefix minimum array
preMin[]
such that preMin[i]
holds the minimum value among arr[0]
to arr[i]
. - Traverse the array from left to right and update
preMin[i] = min(preMin[i - 1], arr[i])
. - Initialize an empty Stack to store building heights in ascending order from the end.
- Traverse the array from right to left:
- If
arr[i]
is greater than preMin[i]
, it means there is a smaller element before it that can be the first building. - While the Stack is not empty and the top of the Stack is less than or equal to
preMin[i]
, pop elements from the Stack. - If the Stack is not empty and the top of the Stack is less than
arr[i]
, return "Yes". - Push
arr[i]
onto the Stack.
- If the traversal ends without finding such a triplet, return "No".
Below is given the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool recreationalSpot(vector<int> &arr) {
int n = arr.size();
// if there are less than 3 buildings
if (n < 3) {
return false;
}
// Stores prefix min array
vector<int> preMin(n);
preMin[0] = arr[0];
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> st;
// 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 st is not
// empty and top element is
// less than or equal to preMin[j]
while (!st.empty() && st.top() <= 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.empty() && st.top() < arr[j]) {
return true;
}
// Push the arr[j] in st
st.push(arr[j]);
}
}
// If none of the above case
// satisfy then return false
return false;
}
int main() {
vector<int> arr = { 4, 7, 11, 5, 13, 2 };
if(recreationalSpot(arr)) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
Java
import java.util.*;
class GfG {
static boolean recreationalSpot(List<Integer> arr) {
int n = arr.size();
// if there are less than 3 buildings
if (n < 3) {
return false;
}
// Stores prefix min array
int[] preMin = new int[n];
preMin[0] = arr.get(0);
for (int i = 1; i < n; i++) {
preMin[i] = Math.min(preMin[i - 1], arr.get(i));
}
// Stores the element from the
// ending in increasing order
Stack<Integer> st = new 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.get(j) > preMin[j]) {
// Iterate while st is not
// empty and top element is
// less than or equal to preMin[j]
while (!st.isEmpty() && st.peek() <= 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.isEmpty() && st.peek() < arr.get(j)) {
return true;
}
// Push the arr[j] in st
st.push(arr.get(j));
}
}
// If none of the above case
// satisfy then return false
return false;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(4, 7, 11, 5, 13, 2);
if (recreationalSpot(arr)) {
System.out.print("Yes");
} else {
System.out.print("No");
}
}
}
Python
def recreationalSpot(arr):
n = len(arr)
# if there are less than 3 buildings
if n < 3:
return False
# Stores prefix min array
preMin = [0] * n
preMin[0] = arr[0]
for i in range(1, n):
preMin[i] = min(preMin[i - 1], arr[i])
# Stores the element from the
# ending in increasing order
st = []
# 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 st is not
# empty and top element is
# less than or equal to preMin[j]
while st and st[-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 and st[-1] < arr[j]:
return True
# Push the arr[j] in st
st.append(arr[j])
# If none of the above case
# satisfy then return false
return False
arr = [4, 7, 11, 5, 13, 2]
if recreationalSpot(arr):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class GfG {
static bool recreationalSpot(List<int> arr) {
int n = arr.Count;
// if there are less than 3 buildings
if (n < 3) {
return false;
}
// Stores prefix min array
int[] preMin = new int[n];
preMin[0] = arr[0];
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> st = 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 st is not
// empty and top element is
// less than or equal to preMin[j]
while (st.Count > 0 && st.Peek() <= 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.Count > 0 && st.Peek() < arr[j]) {
return true;
}
// Push the arr[j] in st
st.Push(arr[j]);
}
}
// If none of the above case
// satisfy then return false
return false;
}
static void Main() {
List<int> arr = new List<int> { 4, 7, 11, 5, 13, 2 };
if (recreationalSpot(arr)) {
Console.Write("Yes");
} else {
Console.Write("No");
}
}
}
JavaScript
function recreationalSpot(arr) {
let n = arr.length;
// if there are less than 3 buildings
if (n < 3) {
return false;
}
// Stores prefix min array
let preMin = new Array(n);
preMin[0] = arr[0];
for (let i = 1; i < n; i++) {
preMin[i] = Math.min(preMin[i - 1], arr[i]);
}
// Stores the element from the
// ending in increasing order
let st = [];
// Iterate until j is greater than
// or equal to 0
for (let 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 true;
}
// Push the arr[j] in st
st.push(arr[j]);
}
}
// If none of the above case
// satisfy then return false
return false;
}
let arr = [4, 7, 11, 5, 13, 2];
if (recreationalSpot(arr)) {
console.log("Yes");
} else {
console.log("No");
}
Further Optimizations
This problem is mainly a variation of Largest Rectangular Area in a Histogram. We can use the same logic to solve this problem using one for loop and a single stack. We mainly need to find both next smaller and previous smaller for every element and as soon as we find an element that has both, we return true.
132 Geeky Buildings | DSA Problem
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