15% off all plans & roadmaps Use code

See plans

Find the Most Competitive Subsequence

Updated

TL;DR: You pick k numbers in their original order so the result is the smallest in dictionary order. A monotonic stack does this in one pass by replacing larger kept values with smaller later values, as long as enough numbers remain.

Problem

You are given an integer array nums and a positive integer k. Return the most competitive subsequence of nums with size k.

A subsequence keeps the original order of the elements. You get one by erasing some (possibly zero) elements from the array.

Subsequence a is more competitive than subsequence b (both of the same length) if, at the first position where they differ, a holds a smaller number than b. For example, [1,3,4] is more competitive than [1,3,5]. They first differ at the last position, and 4 is less than 5.

Example 1

Input: nums = [3,5,2,6], k = 2
Output: [2,6]
Explanation: Among all subsequences {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.

Example 2

Input: nums = [2,4,3,3,5,4,9,6], k = 4
Output: [2,3,3,4]

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • 1 <= k <= nums.length

Constraints that matter

  • n up to 10^5 rules out listing every subsequence. Choosing k values from n gives C(n, k) candidates, which is far beyond any machine's reach.
  • nums[i] up to 10^9 means the values can only be compared, not used as array indexes. The solution must work with comparisons alone.
  • 1 <= k <= n guarantees a valid answer exists. The algorithm must never leave the stack with fewer than k values, so the length rule has to be checked on every pop.
  • k can equal n, which forces the answer to be the whole array. Any pop in that case would be wrong, so the feasibility check must block it.

View on LeetCode

Hints

Hint 1

The statement compares subsequences from the left, so the first value dominates the comparison.

Hint 2

The beginner's solution lists every subsequence of length k and keeps the smallest one under the statement's order.

Solution

Intuition

The statement compares subsequences from the left, so the first value dominates the comparison. You want the smallest value you can place first, and it must leave k - 1 positions after it. Then you repeat that choice for the second position, and so on. Each choice is greedy, and the monotonic stack carries out those choices in one pass.

It is like filling a shelf of k slots from a line of boxes in order. The stack is the shelf, and a lighter box can push out a heavier box on top if enough boxes remain to fill the slots.

What to notice: if a later number is smaller than a number you already kept, the later number wins at the first position where they differ. You can swap the larger kept number out for it. A stack that stays in increasing order lets each smaller arrival remove the larger values on its top.

The length k is the constraint that stops this from being free. You may drop a kept value only if the answer can still reach k values. Count the kept values, add the current element and every element after it, and require the total to exceed k. When that holds, the pop is safe, and the stack ends with the best k values.

Watch the pattern animation

Worked example

Input: nums = [2, 4, 3, 3, 5, 4, 9, 6], k = 4
Output: [2, 3, 3, 4]
Explanation: The answer keeps the values at indices 0, 2, 3 and 5. The first value is 2, the smallest value in the array, and it sits at index 0 with seven positions after it. Each later pick is the smallest value that still leaves enough room to reach length 4.

Approach 1: Brute force

The beginner's solution lists every subsequence of length k and keeps the smallest one under the statement's order. Python's tuple comparison follows that same order, so min finds the answer once the candidates exist. The trouble is the count. There are C(n, k) candidates, and that number is far beyond what a computer can enumerate at n = 10^5.

The search below walks the index choices in order and compares each finished candidate with the best one so far. Nothing is reused between candidates, so shared prefixes get rebuilt again and again.

Steps

  1. Pick k indices from 0 to n - 1 in increasing order.
  2. Build the subsequence that those indices spell out.
  3. Compare the subsequence with the best one found so far, position by position.
  4. Replace the best one if the new candidate is smaller at the first differing position.
  5. Repeat until every choice of indices has been tried, then return the best candidate.

Dry run

On nums = [2, 4, 3, 3, 5, 4, 9, 6] with k = 4, there are C(8, 4) = 70 candidates. The search starts with indices 0, 1, 2, 3, which build [2, 4, 3, 3]. Later, the indices 0, 2, 3, 5 build [2, 3, 3, 4].

At the second value, 3 is less than 4, so the new candidate replaces the best. No later candidate is smaller, so the final answer is [2, 3, 3, 4].

Complexity

TimeO(k * C(n, k))
SpaceO(k)

Let n be the array length and k the answer length. The search tree has one leaf for each k-subset of indices, so there are C(n, k) leaves. Each leaf costs O(k) to copy and compare, and each leaf has at most k ancestors doing O(1) work, so the total is O(k * C(n, k)). The recursion depth and the two lists take O(k) space.

PythonTested in our runner

from typing import List, Optional
from itertools import combinations

class Solution:
    def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
        # min compares the tuples lexicographically, which matches the statement
        return list(min(combinations(nums, k)))

The Monotonic Stack infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Monotonic Stack

Part of Stack Patterns

Approach 2: One-pass monotonic stackOptimalMonotonic Stack

What's slow in brute force: it rebuilds every subset and compares whole lists, even though the first kept value already decides most comparisons. The insight that fixes it: build the answer from left to right and settle each kept value once. A stack holds the kept values in increasing order. When a smaller value arrives, larger values on top can leave, but only while the answer can still reach length k.

The pop test has three parts: the stack is not empty, the current value is smaller than the top, and len(stack) + (n - i) > k. The last part counts the kept values plus the current element and everything after it. Removing the top leaves len - 1 kept values, so the test asks whether len - 1 + (n - i) is at least k. After popping, push the current value only if the stack holds fewer than k values.

Why it is correct. At every point the stack holds the smallest possible subsequence of the prefix seen so far, among those that can still be extended to length k. When a smaller value arrives, popping a larger top is safe, since the smaller value wins at the first differing position. The length check means a pop never leaves fewer than k values in reach, so no valid answer is ever lost.

Steps

  1. Set n to the length of nums and start with an empty stack.
  2. For each index i with value val, pop while the stack is not empty, val is smaller than the top, and len(stack) + (n - i) > k.
  3. Push val only if the stack holds fewer than k values.
  4. Move to the next element and repeat the pop and push checks.
  5. After the last element, the stack holds exactly k values. Return it.

Dry run

The table shows the state after each index for nums = [2, 4, 3, 3, 5, 4, 9, 6] and k = 4. Here n = 8, so the feasibility test is len + (8 - i) > 4.

Stepinums[i]Stack beforePopsPush?Stack after
102[]noneyes[2]
214[2]none, 4 is not less than 2yes[2, 4]
323[2, 4]pop 4, since 2 + 6 > 4yes[2, 3]
433[2, 3]none, 3 is not less than 3yes[2, 3, 3]
545[2, 3, 3]noneyes[2, 3, 3, 5]
654[2, 3, 3, 5]pop 5, since 4 + 3 = 7 > 4yes, size 3 < 4[2, 3, 3, 4]
769[2, 3, 3, 4]noneno, full[2, 3, 3, 4]
876[2, 3, 3, 4]noneno, full[2, 3, 3, 4]

The pops at steps 3 and 6 are the only removals. At step 6, the test passes because four kept values plus three remaining positions give 7. The final stack is [2, 3, 3, 4], which matches the expected output.

Complexity

TimeO(n)
SpaceO(k)

Let n be the array length. Each index is pushed at most once, so there are at most n pushes, and each pop removes a value pushed earlier, so pops total at most n. Each push and pop costs O(1), so the total time is O(n). The stack never holds more than k values, so the space is O(k).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
        stack = []
        n = len(nums)
        for i, val in enumerate(nums):
            # pop larger kept values while the answer can still reach length k
            while stack and val < stack[-1] and len(stack) + (n - i) > k:
                stack.pop()
            if len(stack) < k:
                stack.append(val)
        return stack

Common mistakes

  • The loop condition while stack and val < stack[-1]: has no feasibility test. On [5, 4, 3] with k = 2, every value pops the one before it, and the function returns [3], one value short. Add len(stack) + (n - i) > k to the loop condition.
  • The feasibility test uses n - i - 1 instead of n - i. The current element must be counted. On [1, 3, 2] with k = 2, the test 2 + 0 > 2 fails, so 3 stays and the answer becomes [1, 3]. The correct answer is [1, 2].
  • Skipping the pop loop once the stack is full, for example with if len(stack) == k: continue. On [1, 2, 3, 0] with k = 2, the 0 must replace 2, which gives [1, 0]. Always run the pop loop first, then push only if there is room.
  • Pushing without the len(stack) < k guard. On [2, 4, 3, 3, 5, 4, 9, 6] with k = 4, the stack ends as [2, 3, 3, 4, 6], which has five values. Guard every push.
  • Comparing brute-force candidates by sum, length or first value instead of lexicographically. For [2, 6] and [3, 3], the sums are 8 and 6, but [2, 6] is the more competitive subsequence because 2 is less than 3 at the first position.

Edge cases

  • k = n: the whole array is the only valid answer, so return it unchanged. [5, 1, 2] with k = 3 returns [5, 1, 2].
  • k = 1: the answer is one minimum value. [2, 1, 1] with k = 1 returns [1].
  • Strictly decreasing input: [5, 4, 3, 2, 1] with k = 2 returns [2, 1]. The feasibility test keeps enough values for the tail.
  • Strictly increasing input: [1, 2, 3, 4] with k = 2 returns [1, 2], with no pops.
  • All equal values: [7, 7, 7] with k = 2 returns [7, 7]. Equal values never pop each other because the test is strictly less than.
  • Values up to 10^9 fit in a 32-bit signed integer. The solution only compares values, so Java and C# need no wider type.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find the Most Competitive Subsequence, with how to answer them.

Unlock the follow-ups

Find the Most Competitive Subsequence FAQ

What is the time complexity of Find the Most Competitive Subsequence?

The one-pass monotonic stack runs in O(n) time, where n is the length of nums. Each element is pushed and popped at most once. The space is O(k) for the stack.

Why use a monotonic stack for Find the Most Competitive Subsequence?

The stack keeps the kept values in increasing order, so a smaller new value can remove larger values from the top. Each value is removed at most once, which keeps the total work linear. This turns the greedy choice into one left-to-right pass.

Can Find the Most Competitive Subsequence be solved in O(1) extra space?

Yes, if you count only space beyond the output. Use the result array as the stack and keep a top index. The output itself still holds k values, so the total space is O(k) either way.

Why does the feasibility check matter in the Most Competitive Subsequence problem?

Without it, the stack can shrink below k values, and the answer becomes too short. The check counts the kept values plus the remaining elements, so every pop leaves a valid subsequence of length k possible.

Why is brute force so slow for Find the Most Competitive Subsequence?

Brute force checks every choice of k indices, and there are C(n, k) of them. That count grows far beyond practical limits at n = 10^5. The stack approach avoids the enumeration entirely.

Asked at

See which companies ask this — Pro

Practise it