Python 1673.py
class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
# the problem asks for the subsequence a such that a < b for all b
result = []
remaining = len(nums)
for n in nums:
# remove large numbers from the right side
# if there are enough numbers left to have k elements in the end
while result and result[-1] > n and len(result) + remaining > k:
result.pop()
if len(result) < k:
result.append(n)
remaining -= 1
return result
Difficulty
and has an acceptance rate of about 53% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Monotonic Stack
- Stack
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the lexicographically smallest subsequence of length k that can be obtained from the input list nums. It does so by iterating once over the input while maintaining a mutable collection (result) that behaves like a monotonic stack. The algorithm ensures that at any point the elements kept in result can still be extended to a full subsequence of the required length, thereby guaranteeing correctness without backtracking.
Core Logic
The function begins by initializing an empty list result that will hold the chosen elements and a counter remaining that tracks how many items are still to be examined in nums.
result = []
remaining = len(nums)
The main loop processes each number n in the original order. For each n the algorithm first attempts to discard previously selected elements that are larger than n while still leaving enough numbers to reach the target length k. This is achieved with a while loop that checks three conditions: the stack is non-empty, the top element is greater than the current number, and the combined size of the stack and the yet-unprocessed elements exceeds k.
while result and result[-1] > n and len(result) + remaining > k:
result.pop()
If after possible removals the stack still contains fewer than k elements, the current number is appended, thereby growing the candidate subsequence.
if len(result) < k:
result.append(n)
Finally, the counter remaining is decremented to reflect that one more element has been consumed from the input.
remaining -= 1
When the loop finishes, result holds exactly k elements and is returned as the most competitive subsequence.
return result
Edge Cases Handled
When the input list is empty, remaining starts at zero, the loop body never executes, and the function returns an empty list, which is the correct subsequence of length k when k is also zero.
If k equals the length of nums, the condition len(result) + remaining > k never becomes true while processing the early elements, so no element is removed from result. Consequently, the algorithm simply copies the entire input into result.
When k is zero, the check len(result) < k is never satisfied, preventing any insertion into result. The function therefore returns an empty list regardless of the contents of nums.
For strictly decreasing sequences, each new element is smaller than the previous stack top, causing the while loop to pop all earlier elements until only the necessary amount remains to satisfy the length constraint. This yields the smallest possible subsequence consisting of the last k numbers.
Conversely, for strictly increasing sequences, the condition result[-1] > n never holds, so the algorithm never removes elements. It simply takes the first k numbers, which is the only viable subsequence respecting order.
When duplicate values appear, the algorithm treats them like any other element: it removes a previous duplicate only if a smaller value follows and enough elements remain to fill the subsequence. This ensures that the earliest possible occurrence of a value is kept only when it does not jeopardize competitiveness.
Performance Optimizations
The implementation achieves linear time behavior by processing each element of nums exactly once and performing at most one push or pop per element. The use of a Python list as a stack provides O(1) amortized operations for both append and pop.
The guard len(result) + remaining > k prevents unnecessary removals when the remaining input cannot compensate for a pop, thereby avoiding wasted work and ensuring that the stack never shrinks below the size needed to reach k.
By updating remaining after each iteration, the algorithm maintains an accurate view of the future supply of elements without recomputing the length of the unprocessed suffix, which eliminates repeated scanning of the input.
Overall, the code leverages a single pass, in-place modifications, and constant-time stack operations to deliver an efficient solution for constructing the most competitive subsequence.
ELI5 - Simplified Explanation
Imagine you have a long line of blocks, and each block has a different number written on it. You get to choose a small group of these blocks to keep, but you have to pick exactly k of them. You want your group to be the most special one possible, where the numbers are as small as you can make them from the very start.
The computer looks at the blocks one by one. When it sees a new block, it checks the group you have already started holding. If the block you are holding right now is bigger than the new block, and you have enough blocks left in the original line to fill up your group later, it decides to put the bigger block back and swap it for the smaller new one instead. This way, the smallest numbers end up at the front of your group.
This happens over and over as the computer walks down the line of blocks. It keeps checking if a smaller number could take the place of a bigger one you are already holding. As it goes, it remembers to throw away the extra choices until the group is exactly the right size. By the time it reaches the end of the line, the group in your hands is the smallest one you could possibly build.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1081: Smallest Subsequence of Distinct Characters
Solved On The Same Day
- problem 942: DI String Match
- problem 856: Score of Parentheses
- problem 1028: Recover a Tree From Preorder Traversal
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality