Magicsheet logo

Find the Most Competitive Subsequence

Medium
25%
Updated 8/1/2025

Find the Most Competitive Subsequence

What is this problem about?

The Find the Most Competitive Subsequence interview question asks you to find a subsequence of length kk from an array such that the subsequence is lexicographically smallest. A subsequence is "more competitive" if, at the first index where they differ, it has a smaller element.

Why is this asked in interviews?

Companies like Uber and Google use this to test your understanding of the Monotonic Stack interview pattern. It evaluations your ability to make greedy choices while respecting a global constraint (maintaining a specific length). It’s a test of whether you can identify that a smaller element should always replace a larger one, provided there are enough elements left in the array to still finish a subsequence of length kk.

Algorithmic pattern used

This problem is solved using a Monotonic Stack.

  1. Maintain a stack of elements that form the subsequence.
  2. Iterate through the array. For each element XX:
    • While the stack is not empty, XX is smaller than the stack's top, and the remaining elements in the array are enough to fill the rest of the kk slots:
      • Pop the top of the stack (it's less "competitive").
    • If the stack size is less than kk, push XX onto the stack.
  3. The stack will contain the most competitive subsequence at the end.

Example explanation

nums = [3, 5, 2, 6], k=2k = 2.

  1. Process 3: Stack = [3].
  2. Process 5: Stack = [3, 5]. (Stack is full, but 5 isn't smaller than 3).
  3. Process 2: 2 is smaller than 5.
    • Can we pop 5? We have 1 element left (6). StackSize(1)+Left(1)k(2)StackSize(1) + Left(1) \ge k(2). Yes.
    • Pop 5. Stack = [3].
    • 2 is smaller than 3. Can we pop 3? StackSize(0)+Left(1)<k(2)StackSize(0) + Left(1) < k(2). No!
    • If we pop 3, we only have [2, 6] left, which is length 2. Wait, the count is TotalCurrentIndexTotal - CurrentIndex.
  4. Correct logic: we can pop as long as StackSize + (TotalCount - i - 1) >= k.

Common mistakes candidates make

  • Greedy without look-ahead: Popping elements without checking if you can still reach length kk, resulting in a subsequence that is too short.
  • O(N2)O(N^2) approach: Trying all possible subsequences.
  • Off-by-one: Miscalculating the number of elements remaining in the array.

Interview preparation tip

The Monotonic Stack is the go-to data structure for "Lexicographically Smallest/Largest Subsequence" problems. Practice the condition while (X < stack.top() && can_afford_to_pop) as it is the standard template for these challenges.

Similar Questions