Find the Most Competitive Subsequence

Medium

Description

Given an integer array nums and a positive integer k, return the most competitive subsequence of length k. Smaller is more competitive.

Examples

Input:nums = [3,5,2,6], k = 2
Output:[2,6]
Explanation:

[2,6] is smallest.

Input:nums = [7,1,9,4,8,3], k = 3
Output:[1,3,8]
Explanation:

Need the lexicographically smallest subsequence of length 3. Starting with the smallest available element 1, then the requirement is 2 more elements from [9,4,8,3]. Taking 3 next, the requirement is 1 more element from [8] (since it is not possible to go back). However, the optimal approach would consider [1,4,8] vs [1,3,8] - since there are enough elements remaining, it is possible to take 3 instead of 4, giving us [1,3,8] which uses the 8 that comes after 3.

Input:nums = [1,2,3,4], k = 1
Output:[1]
Explanation:

This is an edge case where k=1 and the array is already sorted in ascending order. The most competitive subsequence of length 1 is simply the smallest element in the array, which is 1.

Constraints

  • 1 ≤ nums.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!