Sorted subsequence of size 3 in linear time using constant space
Last Updated :
18 Sep, 2023
Given an array, the task is to find three elements of this array such that they are in sorted form i.e. for any three elements a[i], a[j] and a[k], they follow this relationship: a[i] < a[j] < a[k] where i < j < k. This problem must be solved using constant space or no extra space.
This problem is already solved in linear time using linear space: Find a sorted sub-sequence of size 3 in Linear Time
Examples:
Input: arr[] = {12, 11, 10, 5, 2, 6, 30}
Output: 5 6 30
or 2 6 30
Explanation: Answer is 5, 6, 30 because 5 < 6 < 30
and they occur in this sequence in the array.
Input: arr[] = {5, 7, 4, 8}
Output: 5 7 8
Explanation: Answer is 5 ,7 ,8 because 5 < 7 < 8
and they occur in the same sequence in the array
Solution: The objective is to find three elements a, b, and c such that a < b < c, and the elements must occur in the same sequence in the array.
Approach: The problem deals with finding three elements a, b, c where a < b < c and they must appear in the same order as in the array. So the intuition at any step must be followed as such. One of the variable (small) should store the smallest element of the array, and the second variable large will be assigned a value when there is already a smaller value present in the (small) variable. This will lead to the formation of a pair of two variables which will form the first two elements of the required sequence. Similarly, if another value can be found in the array that is assigned when the first two variables are already assigned and has a smaller value than the present element the search for the third value would be complete. This completes the triplet a, b and c such that a < b < c, in similar sequence to the array.
Algorithm
- Create three variables, small- Stores the smallest element,large- stores the second element of the sequence, i- loop counter
- Move along the input array from start till end.
- If the present element is smaller than or equal to variable small, update the variable.
- Else if the present element is smaller than or equal to variable large, update the variable. So here we get a pair (small, large) at this instant, where small < large and they occur in the required sequence.
- Else if the previous two cases fail to match, break the loop as we have got a pair where the present element is greater than both variables small and large. Store the index in variable i.
- If the break statement has not been encountered then it is guaranteed that no such triplet exists.
- Else there is a triplet satisfies the criteria but the variable small might have been updated to a new smaller value.
- So Traverse the array from start to index i.
- Re-assign the variable small to any element less than large, it is guaranteed that there exists one.
- Print the values small, large and ith array element
Implementation:
C++
// C/C++ program to find a sorted sub-sequence of
// size 3 using constant space
#include <bits/stdc++.h>
using namespace std;
// A function to fund a sorted sub-sequence of size 3
void find3Numbers(int arr[], int n)
{
// Initializing small and large(second smaller)
// by INT_MAX
int small = INT_MAX, large = INT_MAX;
int i;
for (i = 0; i < n; i++)
{
// Update small for smallest value of array
if (arr[i] <= small)
small = arr[i];
// Update large for second smallest value of
// array after occurrence of small
else if (arr[i] <= large)
large = arr[i];
// If we reach here, we found 3 numbers in
// increasing order : small, large and arr[i]
else
break;
}
if (i == n)
{
printf("No such triplet found");
return;
}
// last and second last will be same, but first
// element can be updated retrieving first element
// by looping upto i
for (int j = 0; j <= i; j++)
{
if (arr[j] < large)
{
small = arr[j];
break;
}
}
printf("%d %d %d", small, large, arr[i]);
return;
}
// Driver program to test above function
int main()
{
int arr[] = {5, 7, 4, 8};
int n = sizeof(arr)/sizeof(arr[0]);
find3Numbers(arr, n);
return 0;
}
Java
// Java program to find a sorted subsequence of
// size 3 using constant space
class GFG
{
// A function to fund a sorted subsequence of size 3
static void find3Numbers(int arr[], int n)
{
// Initializing small and large(second smaller)
// by INT_MAX
int small = +2147483647, large = +2147483647;
int i;
for (i = 0; i < n; i++)
{
// Update small for smallest value of array
if (arr[i] <= small)
small = arr[i];
// Update large for second smallest value of
// array after occurrence of small
else if (arr[i] <= large)
large = arr[i];
// If we reach here, we found 3 numbers in
// increasing order : small, large and arr[i]
else
break;
}
if (i == n)
{
System.out.print("No such triplet found");
return;
}
// last and second last will be same, but first
// element can be updated retrieving first element
// by looping upto i
for (int j = 0; j <= i; j++)
{
if (arr[j] < large)
{
small = arr[j];
break;
}
}
System.out.print(small+" "+large+" "+arr[i]);
return;
}
// Driver program
public static void main(String arg[])
{
int arr[] = {5, 7, 4, 8};
int n = arr.length;
find3Numbers(arr, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to find a sorted subsequence
# of size 3 using constant space
# Function to fund a sorted subsequence of size 3
def find3Numbers(arr, n):
# Initializing small and large(second smaller)
# by INT_MAX
small = +2147483647
large = +2147483647
for i in range(n):
# Update small for smallest value of array
if (arr[i] <= small):
small = arr[i]
# Update large for second smallest value of
# array after occurrence of small
elif (arr[i] <= large):
large = arr[i]
# If we reach here, we found 3 numbers in
# increasing order : small, large and arr[i]
else:
break
if (i == n):
print("No such triplet found")
return
# last and second last will be same, but
# first element can be updated retrieving
# first element by looping upto i
for j in range(i + 1):
if (arr[j] < large):
small = arr[j]
break
print(small," ",large," ",arr[i])
return
# Driver program
arr= [5, 7, 4, 8]
n = len(arr)
find3Numbers(arr, n)
# This code is contributed by Anant Agarwal.
C#
// C# program to find a sorted sub-sequence of
// size 3 using constant space
using System;
class GFG {
// A function to fund a sorted sub-sequence
// of size 3
static void find3Numbers(int []arr, int n)
{
// Initializing small and large(second smaller)
// by INT_MAX
int small = +2147483647, large = +2147483647;
int i;
for (i = 0; i < n; i++)
{
// Update small for smallest value of array
if (arr[i] <= small)
small = arr[i];
// Update large for second smallest value of
// array after occurrence of small
else if (arr[i] <= large)
large = arr[i];
// If we reach here, we found 3 numbers in
// increasing order : small, large and arr[i]
else
break;
}
if (i == n)
{
Console.Write("No such triplet found");
return;
}
// last and second last will be same, but first
// element can be updated retrieving first element
// by looping upto i
for (int j = 0; j <= i; j++)
{
if (arr[j] < large)
{
small = arr[j];
break;
}
}
Console.Write(small + " " + large + " " + arr[i]);
return;
}
// Driver program
public static void Main()
{
int []arr = {5, 7, 4, 8};
int n = arr.Length;
find3Numbers(arr, n);
}
}
<br>
// This code is contributed by nitin mittal
PHP
<?php
// PHP program to find a sorted
// subsequence of size 3 using
// constant space
// A function to fund a sorted
// subsequence of size 3
function find3Numbers($arr, $n)
{
// Initializing small and
// large(second smaller)
// by INT_MAX
$small = PHP_INT_MAX;
$large = PHP_INT_MAX;
$i;
for($i = 0; $i < $n; $i++)
{
// Update small for smallest
// value of array
if ($arr[$i] <= $small)
$small = $arr[$i];
// Update large for second
// smallest value of after
// occurrence of small
else if ($arr[$i] <= $large)
$large = $arr[$i];
// If we reach here, we
// found 3 numbers in
// increasing order :
// small, large and arr[i]
else
break;
}
if ($i == $n)
{
echo "No such triplet found";
return;
}
// last and second last will
// be same, but first
// element can be updated
// retrieving first element
// by looping upto i
for($j = 0; $j <= $i; $j++)
{
if ($arr[$j] < $large)
{
$small = $arr[$j];
break;
}
}
echo $small," ", $large," ", $arr[$i];
return;
}
// Driver Code
$arr = array(5, 7, 4, 8);
$n = count($arr);
find3Numbers($arr, $n);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// JavaScript program to find a
// sorted sub-sequence of
// size 3 using constant space
// A function to fund a sorted sub-sequence
// of size 3
function find3Numbers(arr, n)
{
// Initializing small and large(second smaller)
// by INT_MAX
let small = +2147483647, large = +2147483647;
let i;
for (i = 0; i < n; i++)
{
// Update small for smallest value of array
if (arr[i] <= small)
small = arr[i];
// Update large for second smallest value of
// array after occurrence of small
else if (arr[i] <= large)
large = arr[i];
// If we reach here, we found 3 numbers in
// increasing order : small, large and arr[i]
else
break;
}
if (i == n)
{
document.write("No such triplet found");
return;
}
// last and second last will be same, but first
// element can be updated retrieving first element
// by looping upto i
for (let j = 0; j <= i; j++)
{
if (arr[j] < large)
{
small = arr[j];
break;
}
}
document.write(small + " " + large + " " + arr[i]);
return;
}
let arr = [5, 7, 4, 8];
let n = arr.length;
find3Numbers(arr, n);
</script>
Complexity Analysis:
- Time Complexity: O(n).
As the array is traversed only twice, the time complexity is O(2*n) which is equal to O(n). - Space Complexity: O(1).
Since only three elements are stored, the space complexity is constant or O(1).
Similar Reads
Find a sorted sub-sequence of size 4 in linear time Given an array (arr[]) of N integers, find a subsequence of 4 elements such that a[i] < a[j] < a[k] < a[l] and i < j < k < l in O(N) time. If there are multiple such Quadruplet, then just print any one of them. Examples: Input: arr[] = {7, 4, 6, 10, 11, 13, 1, 2}Output: 4 6 10 13Ex
15+ min read
Sorted subsequence of size 3 Given an array of n integers, find the 3 elements such that a[i] < a[j] < a[k] and i < j < k in 0(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, 30Explanation: As 5 < 6 < 30, and they appear i
15+ min read
Count Subsequences with ordered integers in Array Given an array nums[] of N positive integers, the task is to find the number of subsequences that can be created from the array where each subsequence contains all integers from 1 to its size in any order. If two subsequences have different chosen indices, then they are considered different. Example
7 min read
Longest Increasing Subsequence using BIT Given an array arr, the task is to find the length of The Longest Increasing Sequence using Binary Indexed Tree (BIT) Examples: Input: arr = {6, 5, 1, 3, 2, 4, 8, 7} Output: 4 Explanation: The possible subsequences are {1 2 4 7}, {1 2 4 8}, {1 3 4 8}, {1 3 4 7} Now insert the elements one by one fro
13 min read
Longest Increasing Subsequence(LIS) using two arrays Given two arrays A[] and B[] of size N. Your Task is to find Longest Increasing Subsequence(LIS) in another array C[] such that array C[] is formed by following rules: C[i] = A[i] or C[i] = B[i] for all i from 1 to N.Examples: Input: A[] = {2, 3, 1}, B[] = {1, 2, 1}Output: 2Explanation: Form C[] as
9 min read
Count subsequence of length three in a given string Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string. Examples : Input : string = "GFGFGYSYIOIWIN", subsequence = "GFG" Output : 4 Explanation : There are 4 such subsequences as shown: GFGFGYSYIOIWIN GFGFGYSYIOIWIN GFGFGYSYI
15 min read
Longest Increasing consecutive subsequence | Set-2 Given an array arr[] of N elements, the task is to find the length of the longest increasing subsequence whose adjacent element difference is one. Examples: Input: arr[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output: 6 Explanation: The subsequence {3, 4, 5, 6, 7, 8} is the longest increasing subsequenc
5 min read
Longest Common Subsequence | DP using Memoization Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them. Examples: Input: s1 = âABCDGHâ, s2 = âAEDFHRâ Output: 3 LCS for input Sequences âAGGTABâ and âGXTXAYBâ is âGTABâ of length 4. Input: s1 = âstriverâ, s2 = ârajâ Output: 1 The naive s
13 min read
Longest increasing subsequence which forms a subarray in the sorted representation of the array Given an array arr[] of N integers, the task is to find the length of the longest increasing subsequence such that it forms a subarray when the original array is sorted. Examples: Input: arr[] = { 2, 6, 4, 8, 2, 9 }Output: 3Explanation: Sorted array: {2, 2, 4, 6, 8, 9}All possible non-decreasing seq
11 min read
Find the Second Longest Increasing Subsequence Given an array arr[] of integers, the task is to find the length of the second longest increasing subsequence (LIS). Examples: Input: arr[] = {1, 2, 3, 4}Output: 3 Explanation: Here the length of LIS is 4 which is whole array and length of second LIS is 3 which can be any sequence, {1, 2, 3} or {1,
15+ min read