Find the Most Competitive Subsequence — LeetCode 1673 Python Solution
- Problem
- #1673
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [3,5,2,6], k = 2
- Output
- [2,6]
- Explanation
- Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
Python solution
class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
stk = []
n = len(nums)
for i, v in enumerate(nums):
while stk and stk[-1] > v and len(stk) + n - i > k:
stk.pop()
if len(stk) < k:
stk.append(v)
return stkComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(k) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1673. Find the Most Competitive Subsequence is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1673. Find the Most Competitive Subsequence?
- LeetCode 1673. Find the Most Competitive Subsequence is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1673. Find the Most Competitive Subsequence?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1673. Find the Most Competitive Subsequence?
- The Python solution on this page uses O(k) auxiliary space.
- What topics does LeetCode 1673. Find the Most Competitive Subsequence cover?
- LeetCode 1673. Find the Most Competitive Subsequence is tagged Stack, Greedy, Array and Monotonic Stack on LeetCode.