{"id":907,"date":"2025-08-19T12:34:45","date_gmt":"2025-08-19T07:04:45","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=907"},"modified":"2025-08-19T12:34:46","modified_gmt":"2025-08-19T07:04:46","slug":"remove-k-digits","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/remove-k-digits\/","title":{"rendered":"Remove K Digits | Leetcode 402 | Optimal Stack Solution"},"content":{"rendered":"\n<p>Given string num representing a non-negative integer&nbsp;<code>num<\/code>, and an integer&nbsp;<code>k<\/code>, return&nbsp;<em>the smallest possible integer after removing<\/em>&nbsp;<code>k<\/code>&nbsp;<em>digits from<\/em>&nbsp;<code>num<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/remove-k-digits\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> num = \"1432219\", k = 3<br><strong>Output:<\/strong> \"1219\"<br><strong>Explanation:<\/strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> num = \"10200\", k = 1<br><strong>Output:<\/strong> \"200\"<br><strong>Explanation:<\/strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> num = \"10\", k = 2<br><strong>Output:<\/strong> \"0\"<br><strong>Explanation:<\/strong> Remove all the digits from the number and it is left with nothing which is 0.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5<\/sup><\/code><\/li>\n\n\n\n<li><code>num<\/code>\u00a0consists of only digits.<\/li>\n\n\n\n<li><code>num<\/code>\u00a0does not have any leading zeros except for the zero itself.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><span style=\"text-decoration: underline;\">Optimal Approach:\u00a0<strong>Greedy + Monotonic Increasing Stack<\/strong><\/span><\/h2>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Intuition<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Traverse digits left to right.<\/li>\n\n\n\n<li>Maintain a\u00a0<strong>stack<\/strong>\u00a0of digits in\u00a0<strong>non-decreasing<\/strong>\u00a0order.<\/li>\n\n\n\n<li>For each digit:\n<ul class=\"wp-block-list\">\n<li>While\u00a0<code>k > 0<\/code>\u00a0and the\u00a0<strong>last digit in stack > current digit<\/strong>,\u00a0<strong>pop<\/strong>\u00a0the stack (remove that larger digit) and decrement\u00a0<code>k<\/code>.<\/li>\n\n\n\n<li>Push the current digit.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>After traversal, if\u00a0<code>k > 0<\/code>, remove the remaining digits from the\u00a0<strong>end<\/strong>\u00a0(they\u2019re the largest tail).<\/li>\n\n\n\n<li>Finally,\u00a0<strong>strip leading zeros<\/strong>. If the result is empty, return\u00a0<code>\"0\"<\/code>.<\/li>\n<\/ul>\n\n\n\n<p>This guarantees the&nbsp;<strong>lexicographically smallest<\/strong>&nbsp;result for the given number of deletions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Code<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def removeKdigits(self, num: str, k: int) -&gt; str:\n        stack = []\n        for digit in num:\n            # Greedily remove larger preceding digits to minimize number\n            while k &gt; 0 and len(stack) != 0 and stack[-1] &gt; digit:\n                stack.pop()\n                k -= 1\n            stack.append(digit)\n        # If k &gt; 0, remove from the end\n        while k &gt; 0:\n            stack.pop()\n            k -= 1\n        # Build result and remove leading zeros\n        result = &quot;&quot;.join(stack).lstrip(&quot;0&quot;)\n        if len(result) != 0:\n            return result\n        return &quot;0&quot;\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">removeKdigits<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">num<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">k<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> digit <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> num:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Greedily remove larger preceding digits to minimize number<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> k &gt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(stack) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> stack[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] &gt; digit:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                stack.pop()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                k -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            stack.append(digit)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># If k &gt; 0, remove from the end<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> k &gt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            stack.pop()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            k -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Build result and remove leading zeros<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = <\/span><span style=\"color: #CE9178\">&quot;&quot;<\/span><span style=\"color: #D4D4D4\">.join(stack).lstrip(<\/span><span style=\"color: #CE9178\">&quot;0&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(result) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> result<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">&quot;0&quot;<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works (<strong>Conceptual Walkthrough<\/strong>)<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The\u00a0<strong>while<\/strong>\u00a0loop inside the traversal removes any\u00a0<strong>descending pair<\/strong>\u00a0(<code>prev > current<\/code>) while we still have deletions left, this is the\u00a0<strong>greedy<\/strong>\u00a0step ensuring earlier digits are as\u00a0<strong>small as possible<\/strong>.<\/li>\n\n\n\n<li>If removals remain after scanning all digits, we trim from the\u00a0<strong>right<\/strong>\u00a0since the suffix holds the\u00a0<strong>largest<\/strong>\u00a0remaining digits.<\/li>\n\n\n\n<li><code>lstrip(\"0\")<\/code>\u00a0ensures the result has\u00a0<strong>no leading zeros<\/strong>; if stripped to empty, return\u00a0<code>\"0\"<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Dry Run&nbsp;<strong>Examples<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Input:\u00a0<strong>num = &#8220;1432219&#8221;<\/strong>,\u00a0<strong>k = 3<\/strong><br>Steps: remove \u20184\u2019 (since 1&lt;4), then remove \u20183\u2019 (after 12 vs 132\u2026), then remove \u20182\u2019 \u2192 result becomes\u00a0<strong>&#8220;1219&#8221;<\/strong>.<\/li>\n\n\n\n<li>Input:\u00a0<strong>num = &#8220;10200&#8221;<\/strong>,\u00a0<strong>k = 1<\/strong><br>Remove \u20181\u2019? No\u2014\u20181\u2019 \u2264 \u20180\u2019 is false but next comparison pops \u20181\u2019 when encountering \u20180\u2019 (since 1>0). Stack builds \u2192\u00a0<code>\"0200\"<\/code>\u00a0\u2192 strip leading zeros \u2192\u00a0<strong>&#8220;200&#8221;<\/strong>.<\/li>\n\n\n\n<li>Input:\u00a0<strong>num = &#8220;10&#8221;<\/strong>,\u00a0<strong>k = 2<\/strong><br>Remove both digits \u2192 empty \u2192\u00a0<strong>&#8220;0&#8221;<\/strong>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"time-and-space-complexity\">Time and Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>\u00a0<strong>O(n)<\/strong>\u00a0&#8211; each digit is\u00a0<strong>pushed<\/strong>\u00a0at most once and\u00a0<strong>popped<\/strong>\u00a0at most once.<\/li>\n\n\n\n<li><strong>Space:<\/strong>\u00a0<strong>O(n)<\/strong>\u00a0&#8211; for the stack and result string.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Common Pitfalls and&nbsp;<strong>Tips<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Don\u2019t forget to handle the case where\u00a0<strong>k remains<\/strong>\u00a0after the main loop, remove from the\u00a0<strong>end<\/strong>.<\/li>\n\n\n\n<li>Always\u00a0<strong>strip leading zeros<\/strong>; return\u00a0<strong>&#8220;0&#8221;<\/strong>\u00a0if the result is empty.<\/li>\n\n\n\n<li>The stack must be\u00a0<strong>non-decreasing<\/strong>\u00a0to maintain the smallest possible prefix.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">When to Use This&nbsp;<strong>Pattern<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Any problem where you need the\u00a0<strong>smallest\/lexicographically smallest<\/strong>\u00a0result after removing\u00a0<strong>k elements<\/strong>\u00a0while preserving order often hints at a\u00a0<strong>monotonic stack<\/strong>\u00a0(e.g., \u201cremove k digits,\u201d \u201cbuild smallest subsequence,\u201d etc.).<\/li>\n<\/ul>\n\n\n\n<p>This solution is\u00a0<strong>concise<\/strong>,\u00a0<strong>greedy-optimal<\/strong>, and\u00a0<strong>linear time<\/strong>, perfect for interviews and production.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given string num representing a non-negative integer&nbsp;num, and an integer&nbsp;k, return&nbsp;the smallest possible integer after removing&nbsp;k&nbsp;digits from&nbsp;num. Here&#8217;s the [Problem Link] to begin with. Example 1: Input: num = &#8220;1432219&#8221;, k = 3Output: &#8220;1219&#8221;Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input:<\/p>\n","protected":false},"author":1,"featured_media":908,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[18,37],"class_list":{"0":"post-907","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-hard","10":"tag-stack-and-queues"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/remove-K-digits-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/907","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=907"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/907\/revisions"}],"predecessor-version":[{"id":911,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/907\/revisions\/911"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/908"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=907"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=907"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=907"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}