{"id":467,"date":"2025-06-29T20:24:00","date_gmt":"2025-06-29T14:54:00","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=467"},"modified":"2025-06-29T20:24:01","modified_gmt":"2025-06-29T14:54:01","slug":"sort-colors","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/sort-colors\/","title":{"rendered":"Sort Colors | Leetcode 75 | Brute, Better and Optimal"},"content":{"rendered":"\n<p>LeetCode <strong>\u201cSort Colors\u201d<\/strong> (#75) asks you to sort an array that contains only three distinct values\u2014<code>0<\/code>, <code>1<\/code>, and <code>2<\/code>\u2014so that all <code>0<\/code>s come first, then all <code>1<\/code>s, and finally all <code>2<\/code>s.<br>The trick: <strong>do it entirely in-place<\/strong> and, ideally, in a single pass.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Input<\/th><th>Output<\/th><\/tr><\/thead><tbody><tr><td><code>[2, 0, 2, 1, 1, 0]<\/code><\/td><td><code>[0, 0, 1, 1, 2, 2]<\/code><\/td><\/tr><tr><td><code>[2, 0, 1]<\/code><\/td><td><code>[0, 1, 2]<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The problem is famously solved by the <strong>Dutch National Flag<\/strong> algorithm\u2014but we\u2019ll walk through three escalating solutions to see how you reach that \u201coptimal\u201d idea.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/sort-colors\/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<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-fec6dc68-7bea-45de-9e7a-96e2b06d23b8\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#0-brute-force-solution-built-in-sort\" style=\"\">Brute Force Solution (Built-in Sort)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#4-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#7-better-solution-counting-sort\" style=\"\">Better Solution (Counting Sort)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#8-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#11-dry-run-2-0-2-1-1-0-\" style=\"\">Dry Run ([2, 0, 2, 1, 1, 0])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#12-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#14-optimal-solution-dutch-national-flag-one-pass-three-pointers\" style=\"\">Optimal Solution (Dutch National Flag \/ One-Pass, Three Pointers)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#15-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#16-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#17-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#18-dry-run-2-0-2-1-1-0-\" style=\"\">Dry Run ([2, 0, 2, 1, 1, 0])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#19-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#20-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-colors\/#21-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution-built-in-sort\">Brute Force Solution (Built-in Sort)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<p>Why overthink? <strong>Python\u2019s <code>list.sort()<\/code><\/strong> already arranges numbers in non-decreasing order. Because the array has only three distinct values, simply calling <code>sort()<\/code> achieves the goal\u2014though it doesn\u2019t respect the spirit of the challenge.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" 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;line-height:1.25rem;--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 sortColors(self, nums: List[int]) -&gt; None:\n        &quot;&quot;&quot;\n        Do not return anything, modify nums in-place instead.\n        &quot;&quot;&quot;\n        nums.sort()  # use Python\u2019s Timsort (O(n log n))\" 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\">sortColors<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #CE9178\">&quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        Do not return anything, modify nums in-place instead.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        &quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        nums.sort()  <\/span><span style=\"color: #6A9955\"># use Python\u2019s Timsort (O(n log n))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>nums.sort()<\/code><\/strong> uses Timsort (<code>O(n log n)<\/code>) and extra space for recursion overhead.<\/li>\n\n\n\n<li>Passes LeetCode but isn\u2019t linear and feels like cheating.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run\">Dry Run<\/h3>\n\n\n\n<p>Input <code>[2, 0, 1]<\/code> \u2192 after <code>sort()<\/code> \u2192 <code>[0, 1, 2]<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n log n)<\/code> \u2013 general-purpose sorting.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> extra (in-place operations only).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Quick and dirty, fine for production if constraints are tiny, but interviewers expect a linear-time answer.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-better-solution-counting-sort\">Better Solution (Counting Sort)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<p>With only <strong>three<\/strong> distinct values you can:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Count occurrences<\/strong> of <code>0<\/code>, <code>1<\/code>, and <code>2<\/code>.<\/li>\n\n\n\n<li><strong>Overwrite<\/strong> the array: first <code>count(0)<\/code> zeros, then <code>count(1)<\/code> ones, then <code>count(2)<\/code> twos.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" 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;line-height:1.25rem;--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 sortColors(self, nums: List[int]) -&gt; None:\n        &quot;&quot;&quot;\n        Do not return anything, modify nums in-place instead.\n        &quot;&quot;&quot;\n        n = len(nums)\n        # Counters for each color\n        cnt1 = 0  # number of 0s\n        cnt2 = 0  # number of 1s\n        cnt3 = 0  # number of 2s\n\n        # First pass \u2013 count frequencies\n        for i in range(0, n):\n            if nums[i] == 0:\n                cnt1 += 1\n            elif nums[i] == 1:\n                cnt2 += 1\n            else:\n                cnt3 += 1\n\n        # Second pass \u2013 overwrite array based on counts\n        for i in range(0, cnt1):\n            nums[i] = 0\n        for i in range(cnt1, cnt1 + cnt2):\n            nums[i] = 1\n        for i in range(cnt1 + cnt2, cnt1 + cnt2 + cnt3):\n            nums[i] = 2\" 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\">sortColors<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #CE9178\">&quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        Do not return anything, modify nums in-place instead.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        &quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Counters for each color<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        cnt1 = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># number of 0s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        cnt2 = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># number of 1s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        cnt3 = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># number of 2s<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># First pass \u2013 count frequencies<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[i] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cnt1 += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> nums[i] == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cnt2 += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cnt3 += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Second pass \u2013 overwrite array based on counts<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, cnt1):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums[i] = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cnt1, cnt1 + cnt2):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums[i] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cnt1 + cnt2, cnt1 + cnt2 + cnt3):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums[i] = <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Two passes:<\/strong> the first tallies colors, the second rewrites positions.<\/li>\n\n\n\n<li>Still linear, but touches the array twice and allocates three extra counters.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run-2-0-2-1-1-0-\">Dry Run (<code>[2, 0, 2, 1, 1, 0]<\/code>)<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Counts \u2192 <code>cnt1=2<\/code>, <code>cnt2=2<\/code>, <code>cnt3=2<\/code>.<\/li>\n\n\n\n<li>Rewrite \u2192 <code>[0, 0, 1, 1, 2, 2]<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n)<\/code> \u2013 two linear scans.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 only three integer counters.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Solid and simple. Yet we can squeeze to <strong>one pass<\/strong> with the Dutch National Flag trick.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-optimal-solution-dutch-national-flag-one-pass-three-pointers\">Optimal Solution (Dutch National Flag \/ One-Pass, Three Pointers)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<p>Maintain <strong>three regions<\/strong> within the array:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>0 \u2026 low-1<\/code><\/strong> \u2192 all <code>0<\/code>s<\/li>\n\n\n\n<li><strong><code>low \u2026 mid-1<\/code><\/strong> \u2192 all <code>1<\/code>s<\/li>\n\n\n\n<li><strong><code>mid \u2026 high<\/code><\/strong> \u2192 unknown \/ unprocessed<\/li>\n\n\n\n<li><strong><code>high+1 \u2026 end<\/code><\/strong> \u2192 all <code>2<\/code>s<\/li>\n<\/ul>\n\n\n\n<p>Process the <code>mid<\/code> pointer:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If <code>nums[mid] == 0<\/code> \u2192 swap with <code>low<\/code>, increment both <code>low<\/code> &amp; <code>mid<\/code>.<\/li>\n\n\n\n<li>If <code>nums[mid] == 1<\/code> \u2192 correct spot, just increment <code>mid<\/code>.<\/li>\n\n\n\n<li>If <code>nums[mid] == 2<\/code> \u2192 swap with <code>high<\/code>, decrement <code>high<\/code> (don\u2019t move <code>mid<\/code> yet).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" 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;line-height:1.25rem;--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 sortColors(self, nums: List[int]) -&gt; None:\n        &quot;&quot;&quot;\n        Do not return anything, modify nums in-place instead.\n        &quot;&quot;&quot;\n        low = 0                # boundary for 0s\n        mid = 0                # current element\n        high = len(nums) - 1   # boundary for 2s\n\n        while mid &lt;= high:\n            if nums[mid] == 0:\n                # swap current 0 into 0s region\n                nums[low], nums[mid] = nums[mid], nums[low]\n                low += 1\n                mid += 1\n            elif nums[mid] == 1:\n                # 1 is already in correct middle region\n                mid += 1\n            else:\n                # swap current 2 into 2s region\n                nums[mid], nums[high] = nums[high], nums[mid]\n                high -= 1\" 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\">sortColors<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #CE9178\">&quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        Do not return anything, modify nums in-place instead.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">        &quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        low = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># boundary for 0s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        mid = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># current element<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        high = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums) - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #6A9955\"># boundary for 2s<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> mid &lt;= high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[mid] == <\/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: #6A9955\"># swap current 0 into 0s region<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                nums[low], nums[mid] = nums[mid], nums[low]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                mid += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> nums[mid] == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># 1 is already in correct middle region<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                mid += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># swap current 2 into 2s region<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                nums[mid], nums[high] = nums[high], nums[mid]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"17-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Three pointers<\/strong> partition the array dynamically.<\/li>\n\n\n\n<li>Each swap places a <code>0<\/code> or <code>2<\/code> into its definitive region, so every element is <strong>handled at most once<\/strong>.<\/li>\n\n\n\n<li>Only one full sweep needed.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"18-dry-run-2-0-2-1-1-0-\">Dry Run (<code>[2, 0, 2, 1, 1, 0]<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>low<\/th><th>mid<\/th><th>high<\/th><th>nums after operation<\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>0<\/td><td>5<\/td><td>swap mid\/high \u2192 <code>[0,0,2,1,1,2]<\/code><\/td><\/tr><tr><td>0<\/td><td>0<\/td><td>4<\/td><td>swap mid\/low \u2192 <code>[0,0,2,1,1,2]<\/code><\/td><\/tr><tr><td>1<\/td><td>1<\/td><td>4<\/td><td>mid++ (1 stable)<\/td><\/tr><tr><td>1<\/td><td>2<\/td><td>4<\/td><td>swap mid\/high \u2192 <code>[0,0,1,1,2,2]<\/code><\/td><\/tr><tr><td>\u2026<\/td><td>\u2026<\/td><td>\u2026<\/td><td>loop ends \u2192 <code>[0,0,1,1,2,2]<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"19-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n)<\/code> \u2013 exactly one pass.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 only three indices.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"20-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The Dutch National Flag algorithm is the interview-ready, optimal solution:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Single pass<\/strong><\/li>\n\n\n\n<li><strong>Constant space<\/strong><\/li>\n\n\n\n<li><strong>Elegant pointer dance<\/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=\"21-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Brute (<code>sort<\/code>)<\/strong>: quickest to code, but <code>O(n log n)<\/code> and conceptually boring.<\/li>\n\n\n\n<li><strong>Counting Sort<\/strong>: two linear passes, fine space, but still touches data twice.<\/li>\n\n\n\n<li><strong>Dutch National Flag<\/strong>: one-pass, one-swap perfection, <strong>always aim for this in interviews<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>Master these three tiers and you\u2019ll be prepared for any \u201cmulti-value partition\u201d problem that comes your way. Happy sorting!<\/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:\/\/www.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\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>LeetCode \u201cSort Colors\u201d (#75) asks you to sort an array that contains only three distinct values\u20140, 1, and 2\u2014so that all 0s come first, then all 1s, and finally all 2s.The trick: do it entirely in-place and, ideally, in a single pass. Input Output [2, 0, 2, 1, 1, 0] [0, 0, 1, 1, 2,<\/p>\n","protected":false},"author":1,"featured_media":468,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,6],"tags":[7,19,12],"class_list":{"0":"post-467","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-array","10":"tag-medium","11":"tag-sorting-algos"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/sort-colors-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\/467","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=467"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/467\/revisions"}],"predecessor-version":[{"id":469,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/467\/revisions\/469"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/468"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=467"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=467"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=467"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}