Problem 1673

Abstract / Summary

Given a sequence and a number keep, remove extra digits so the kept subsequence is as small as possible while preserving order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
16 lines | 603 bytes | submitted November 29, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Monotonic Stack
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.26 | σ = 0.80

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 17 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 1 medium 1 hard
4 solutions   November 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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