Remove K Digits

Hard
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Remove K Digits

Approach

Use a monotonic increasing stack of digits. While the current digit is smaller than stack top and removals remain, pop larger digits to reduce the number lexicographically. Remove any extra digits from the end, then strip leading zeros.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Monotonic Stack + Greedy

Why It Works

Earlier digits have higher place value impact. Greedily removing larger preceding digits when a smaller digit appears yields the smallest final number.

Updated Feb 2026