![]() |
VOOZH | about |
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 13
Explanation: As 4 < 6 < 10 <13, where i < j < k < l, arr[i] < arr[j] < arr[k] < arr[l]Input: arr[] = {1, 7, 4, 5, 3, 6}
Output: 1 4 5 6
Explanation: As 1 < 4 < 5 < 6, where i < j < k < l, arr[i] < arr[j] < arr[k] < arr[l]Input: arr[] = {4, 3, 1, 7}
Output: No such Quadruplet exists.
Naive Approach:
Hint: Use Auxiliary Space.
The approach is to find an element which has two element smaller than itself on the left side of the array and an element greater than itself on the right side of the array, if there is any such element then there exists a Quadruplet that satisfies the criteria, otherwise no such Quadruplet is present.
Algorithm:
Below is the implementation of the above approach:-
Quadruplets: 1 4 5 6
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: Follow the below idea to solve the problem:
The idea is to find first find three elements arr[i], arr[j] , arr[k] such that arr[i] < arr[j] < arr[k]. Then find a fourth element arr[l] greater than arr[k] by traversing the array with O(n) time and O(1) space. Then we can print the Quadruplet as arr[i], arr[j], arr[k], arr[l] .
Follow the steps to solve the problem:
Below is the implementation of the above approach:-
Quadruplets: 1 4 5 6
Time Complexity: O(N)
Auxiliary Space: O(1)