700357. Sorted subsequence of size 3
Sorted Subsequence of Size 3
Summary
Given an array of integers, find a subsequence of size 3 that is sorted in ascending order. This problem involves arrays and data structures, making it suitable for Amazon, FactSet, and Walmart interview questions.
Detailed Explanation
To solve this problem, we can use a simple greedy approach. First, sort the entire array in ascending order. Then, iterate through the array and keep track of the last two elements that are already part of our subsequence. If the current element is greater than or equal to the previous two elements, add it to the subsequence.
Here's a step-by-step breakdown of the solution:
- Sort the entire array in ascending order.
- Initialize three variables:
last,second_last, andsubsequenceto store the last two elements of the subsequence and the subsequence itself, respectively. - Iterate through the sorted array:
- If the current element is greater than or equal to
lastandsecond_last, add it tosubsequenceand updatelastandsecond_last. - If the current element is less than both
lastandsecond_last, resetsubsequenceand updatelastandsecond_lastwith the current element.
- If the current element is greater than or equal to
- Return the subsequence.
Time complexity: O(n log n) due to sorting, where n is the size of the array. Space complexity: O(1) as we only use a constant amount of space to store the variables.
Optimized Solutions
Java
public int[] sortedSubsequence(int[] arr) {
Arrays.sort(arr);
int[] subsequence = new int[3];
for (int i : arr) {
if (i >= subsequence[1] && i >= subsequence[0]) {
subsequence[2] = i;
return subsequence;
} else if (i < subsequence[0] && i < subsequence[1]) {
subsequence[0] = i;
subsequence[1] = i;
subsequence[2] = i;
}
}
return new int[] {};
}