Remove K Digits

Stack / Queues Monotonic Stack Medium
  • This problem is very akin to the concept of data compression used in many software applications and it also has relevance in financial tech apps
  • For instance, some apps need to display a large numerical data to users in an abridged format due to screen size limitations
  • They may abbreviate the number by removing less significant digits, essentially solving a problem similar to the one described
  • Similarly, in algorithmic trading, removing less significant digits (or "points") from large financial data is a routine task

Given a string nums representing a non-negative integer, and an integer k, find the smallest possible integer after removing k digits from num.

Examples:

Input: nums = "541892", k = 2

Output: "1892"

Explanation: Removing the two digits 5 and 4 yields the smallest number, 1892.

Input: nums = "1002991", k = 3

Output: "21"

Explanation: Remove the three digits 1(leading one), 9, and 9 to form the new number 21(Note that the output must not contain leading zeroes) which is the smallest.

Input: nums = "10", k = 2

Constraints

  •   1 <= k <= nums.length <= 104
  •   nums consists of only digits.
  •   nums does not have any leading zeros except for the zero itself.

Hints

  • Use a monotonic increasing stack to maintain the digits that will form the final number.
  • While iterating through nums. If the current digit is smaller than the top of the stack, remove the top of the stack (if k > 0). Push the current digit onto the stack.

Company Tags

Bloomberg Salesforce Docker Pinterest KPMG Freshworks Rakuten Roche AMD Micron Technology Visa HCL Technologies ARM HashiCorp Walmart Byju's Red Hat Electronic Arts Cloudflare Ernst & Young Alibaba Airbnb Epic Systems Unity Technologies Goldman Sachs Google Microsoft Amazon Meta Apple Netflix Adobe