Ctrl K

Smallest Subsequence of a Given Length

Medium
You are given an array values and a number size. Cross out some numbers so that exactly size remain, keeping their original order. Of all possible results, return the lexicographically smallest one: two sequences of equal length are compared at the first position where they differ, and the one with the smaller number there is smaller.
Example 1
values=[6, 2, 7, 1, 5], size=3 → [2, 1, 5]

Starting with 1 is impossible: only one number would follow it. The best start is 2, then 1 and 5: [2, 1, 5].

Example 2
values=[4, 4, 3, 4], size=2 → [3, 4]

Take the 3 and the last 4: [3, 4] beats [4, 3] and [4, 4].

Example 3
values=[9, 8, 7], size=3 → [9, 8, 7]

Every number must be kept, so there is no choice.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁹
  • 1 ≤ size ≤ len(values)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFix the Middle of the Line MediumMost Pieces Sorted Separately MediumTree of Leaf Products MediumOutclassed Heroes MediumHopping Along the Stones Medium
loading Python…
Input
values=[6, 2, 7, 1, 5], size=3
Expected
[2, 1, 5]

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.