VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-sorted-subsequence-of-size-3-in-linear-time/

⇱ Sorted subsequence of size 3 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorted subsequence of size 3

Last Updated : 9 Apr, 2026

Given an array arr[] of n integers, find the 3 elements such that a[i] < a[j] < a[k] and i < j < k in O(n) time. If there are multiple such triplets, then print any one of them.

Examples:

Input: arr[] = [12, 11, 10, 5, 6, 2, 30]
Output: 5, 6, 30
Explanation: As 5 < 6 < 30, and they appear in the same sequence in the array

Input: arr[] = [1, 2, 3, 4]
Output: 1, 2, 3
Explanation: As 1 < 2 < 3, and they appear in the same sequence in the array

Input: arr[] = [4, 3, 2, 1]
Output: No such triplet exists.

[Naive Approach] - O(n) Time and O(n) Space

The main motive is to find an element which has an element smaller than itself on the left side of the array and an element greater than itself on the right side of the array.

  1. Create an auxiliary array smaller[0..n-1]. smaller[i] stores the index of a number which is smaller than arr[i] and is on the left side. The array contains -1 if there is no such element.
  2. Create another auxiliary array greater[0..n-1]. greater[i] stores the index of a number which is greater than arr[i] and is on the right side of arr[i]. The array contains -1 if there is no such element.
  3. Finally traverse both smaller[] and greater[] and find the index [i] for which both smaller[i] and greater[i] are not equal to -1.

Output
5 6 30 

[Expected Approach] - O(n) Time and O(1) Space

First find two elements arr[i] & arr[j] such that arr[i] < arr[j]. Then find a third element arr[k] greater than arr[j]. We can think of the problem in three simple terms.

  1. First we only need to find two elements arr[i] < arr[j] and i < j. This can be done in linear time with just 1 loop over the range of the array. For instance, while keeping track of the min element, it is easy to find any subsequent element that is greater than it. Thus we have our arr[i] & arr[j]. Consider {3, 4, -1, 0, 2}. Initially min is 3, arr[i] is 3 and arr[j] is 4. While iterating over the array we can easily keep track of min and eventually update it to -1, so arr[i] & arr[j] become -1 and 0.
  2. As soon as we have arr[i] & arr[j] values, we can immediately start monitoring the subsequent elements in the same loop for an arr[k] > arr[j]. Thus we can find all three values arr[i] < arr[j] < arr[k] in a single pass over the array.

Output
5 6 30 
Comment
Article Tags: