Greedy Algorithms8 sections · 316 units
Open in Course

Remove K Digits - Algorithm

Stack-based greedy

Use a stack. For each digit:

1.1. While stack top > current digit and k > 00, pop the stack (remove that digit) and decrement k.

2.2. Push current digit. After processing, if k > 00, remove from the end. Finally, strip leading zeros. Time: O(n)O(n). Space: O(n)O(n). The stack maintains an increasing sequence of digits from left to right. Each pop removes a 'peak' digit where a smaller digit follows. This ensures leftmost positions contain the smallest possible values. Common bug: forgetting to handle cases where kk removals finish before scanning all digits.