Find the Most Competitive Subsequence — LeetCode 1673 Python Solution

MediumStackGreedyArrayMonotonic Stack
Problem
#1673
Pattern
Stack
Reading time
2 min

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

Python
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 stk

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview