Find the Most Competitive Subsequence - Problem

Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.

An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.

We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 < 5.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,5,2,6], k = 2
Output: [2,6]
💡 Note: Among all possible subsequences of length 2: [3,5], [3,2], [3,6], [5,2], [5,6], [2,6]. The subsequence [2,6] is most competitive because 2 < 3 (first elements compared).
Example 2 — Larger Array
$ Input: nums = [2,4,3,3,5,4,9,6], k = 4
Output: [2,3,3,4]
💡 Note: We need to select 4 elements maintaining order. The most competitive subsequence starts with the smallest possible elements: 2, then 3, then 3, then 4.
Example 3 — All Elements
$ Input: nums = [1,2,3], k = 3
Output: [1,2,3]
💡 Note: When k equals array length, we must take all elements in their original order.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Find Most Competitive Subsequence3526Input: nums = [3,5,2,6], k = 226Output: [2,6]Most competitive subsequence: starts with smallest possible elementGreedy approach: remove larger elements when beneficial
Understanding the Visualization
1
Input
Array [3,5,2,6] with k=2 (need 2 elements)
2
Process
Use monotonic stack to greedily select smallest elements
3
Output
Most competitive subsequence [2,6]
Key Takeaway
🎯 Key Insight: Use monotonic stack to greedily build the lexicographically smallest subsequence by removing larger elements when possible
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.5K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen