Skip to content

1673. Find the Most Competitive Subsequence 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> mostCompetitive(vector<int>& nums, int k) {
    vector<int> ans;

    for (int i = 0; i < nums.size(); ++i) {
      // If |ans| - 1 + |nums[i..n)| >= k, then it means we still have enough
      // numbers, and we can safely pop an element from ans.
      while (!ans.empty() && ans.back() > nums[i] &&
             ans.size() - 1 + nums.size() - i >= k)
        ans.pop_back();
      if (ans.size() < k)
        ans.push_back(nums[i]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int[] mostCompetitive(int[] nums, int k) {
    int[] ans = new int[k];
    Deque<Integer> stack = new ArrayDeque<>();

    for (int i = 0; i < nums.length; ++i) {
      // If |stack| - 1 + |nums[i..n)| >= k, then it means we still have enough
      // numbers, and we can safely pop an element from stack.
      while (!stack.isEmpty() && stack.peek() > nums[i] && stack.size() - 1 + nums.length - i >= k)
        stack.pop();
      if (stack.size() < k)
        stack.push(nums[i]);
    }

    for (int i = 0; i < k; i++)
      ans[i] = stack.pollLast();

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def mostCompetitive(self, nums: list[int], k: int) -> list[int]:
    ans = []

    for i, num in enumerate(nums):
      # If |ans| - 1 + |nums[i..n)| >= k, then it means we still have enough
      # numbers, and we can safely pop an element from ans.
      while ans and ans[-1] > nums[i] and len(ans) - 1 + len(nums) - i >= k:
        ans.pop()
      if len(ans) < k:
        ans.append(nums[i])

    return ans