700357. Sorted subsequence of size 3

Medium

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:

  1. Sort the entire array in ascending order.
  2. Initialize three variables: last, second_last, and subsequence to store the last two elements of the subsequence and the subsequence itself, respectively.
  3. Iterate through the sorted array:
    • If the current element is greater than or equal to last and second_last, add it to subsequence and update last and second_last.
    • If the current element is less than both last and second_last, reset subsequence and update last and second_last with the current element.
  4. 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

View on GeeksforGeeks
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[] {};
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.