31. Sorted Subsequence of Size 3
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
You are given an array arr, and you need to find any three elements in it such that arr[i] < arr[j] < arr[k] and i < j < k.
If such a subsequence is found, return
1.If no such subsequence exists, return an empty array.
If the subsequence is not in the required format, the output will be
-1.
Example:
Input:
arr = [1, 2, 1, 1, 3]Output:
1Explanation: A subsequence 1 2 3 exists.
My Approach
Initialization:
We maintain two auxiliary arrays
smallerandgreaterto store indices of elements that are smaller and greater than the current element, respectively.
Traverse Array to Fill Smaller Array:
Start from the left of the array and update
smaller[i]with the index of the smallest element seen so far to the left of the current element.
Traverse Array to Fill Greater Array:
Start from the right of the array and update
greater[i]with the index of the largest element seen so far to the right of the current element.
Find the Required Subsequence:
Scan through the array to find an element such that both
smaller[i]andgreater[i]are not-1. Return the elements at these indices as the result.
Edge Cases:
If the array has fewer than three elements, immediately return an empty array.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse the array a constant number of times, where
nis the length of the array.Expected Auxiliary Space Complexity: O(n), due to the additional space required for the
smallerandgreaterarrays.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated