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
Most Competitive Subsequence INPUT Array nums: 3 i=0 5 i=1 2 i=2 6 i=3 Input Values: nums = [3, 5, 2, 6] k = 2 Goal: Find subsequence of size k that is lexicographically smallest (most competitive) ALGORITHM STEPS 1 Initialize Stack stack = [], process each num 2 Pop Condition While stack not empty AND top > curr AND can remove 3 Push Current Push num if stack.len < k 4 Return Result Stack contains answer Stack Trace: [3] [3,5] [2] [2,6] pop 3,5 for 2 push 6 FINAL RESULT Most Competitive Subsequence: 2 6 Output: [2, 6] OK - Verified! Subsequence length = 2 [2,6] beats [3,5], [3,6] [5,6], [3,2], etc. 2 < 3,5 at first position Key Insight: Use a monotonic stack to greedily build the smallest lexicographic subsequence. Pop larger elements if enough elements remain to fill k positions. This ensures we always pick the smallest possible value at each position while maintaining subsequence order. TutorialsPoint - Find the Most Competitive Subsequence | Greedy with Monotonic Stack
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.6K 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