#1673
Find the Most Competitive Subsequence
MediumArrayStackGreedyMonotonic StackGreedy algorithmsMonotonic stack
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a stack to maintain the most competitive subsequence while iterating through the array. This method ensures that we always keep the smallest possible elements and can efficiently discard larger elements that would make the subsequence less competitive.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty stack and calculate how many elements we can remove from nums.
- 2Step 2: Iterate through each number in nums, and for each number, check if it can replace the top of the stack to maintain competitiveness.
- 3Step 3: If the stack size is less than k, push the current number onto the stack.
- 4Step 4: Return the first k elements from the stack.
solution.py13 lines
1# Full working Python code
2from collections import deque
3
4def mostCompetitive(nums, k):
5 stack = []
6 to_remove = len(nums) - k
7 for num in nums:
8 while to_remove > 0 and stack and stack[-1] > num:
9 stack.pop()
10 to_remove -= 1
11 stack.append(num)
12 return stack[:k]
13ℹ
Complexity note: The time complexity is O(n) because we process each element of the array once. The space complexity is O(n) due to the stack that may store up to n elements in the worst case.
- 1The most competitive subsequence is determined by the smallest elements appearing first.
- 2Using a stack allows us to efficiently manage the elements we want to keep.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.