{"id":666,"date":"2025-07-15T13:51:25","date_gmt":"2025-07-15T08:21:25","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=666"},"modified":"2025-07-15T13:51:27","modified_gmt":"2025-07-15T08:21:27","slug":"sort-a-linked-list-of-0s-1s-and-2s","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/","title":{"rendered":"Sort a linked list of 0s, 1s and 2s | GFG Question Explained"},"content":{"rendered":"\n<p>Given the&nbsp;<strong>head<\/strong>&nbsp;of a linked list where nodes can contain values&nbsp;<strong>0s<\/strong>,&nbsp;<strong>1s,<\/strong>&nbsp;and&nbsp;<strong>2s&nbsp;<\/strong>only. Your&nbsp;task is to&nbsp;<strong>rearrange<\/strong>&nbsp;the list so that all&nbsp;<strong>0s<\/strong>&nbsp;appear at the beginning, followed by all&nbsp;<strong>1s<\/strong>, and all&nbsp;<strong>2s<\/strong>&nbsp;are placed at the end.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/given-a-linked-list-of-0s-1s-and-2s-sort-it\/1\" 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>Examples:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>head =<strong> <\/strong>1 \u2192 2 \u2192 2 \u2192 1 \u2192 2 \u2192 0 \u2192 2 \u2192 2<br><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/media.geeksforgeeks.org\/img-practice\/prod\/addEditProblem\/893386\/Web\/Other\/blobid0_1745663585.jpg\" width=\"829\" height=\"101\"><br><strong>Output: <\/strong>0 \u2192 1 \u2192 1 \u2192 2 \u2192 2 \u2192 2 \u2192 2 \u2192 2<br><img decoding=\"async\" src=\"https:\/\/media.geeksforgeeks.org\/img-practice\/prod\/addEditProblem\/893386\/Web\/Other\/blobid1_1745663752.jpg\" width=\"829\" height=\"101\"><strong>\nExplanation: <\/strong>All the 0s are segregated to the left end of the linked list, 2s to the right end of the list, and 1s in between.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>head = 2 \u2192 2 \u2192 0 \u2192 1<br><img decoding=\"async\" src=\"https:\/\/media.geeksforgeeks.org\/img-practice\/prod\/addEditProblem\/893386\/Web\/Other\/blobid1_1745653669.jpg\" width=\"459\" height=\"95\"><br><strong>Output: <\/strong>0 \u2192 1 \u2192 2 \u2192 2<br><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/media.geeksforgeeks.org\/img-practice\/prod\/addEditProblem\/893386\/Web\/Other\/blobid2_1745653710.jpg\" width=\"453\" height=\"94\"><strong>\nExplanation: <\/strong>After arranging all the 0s, 1s and 2s in the given format, the output will be 0 \u2192 1 \u2192 2 \u2192 2.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><br>1 \u2264 no. of nodes \u2264 10<sup>6<\/sup><br>0 \u2264 node-&gt;data \u2264 2<\/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-6ceab751-0ef8-443c-8c51-1d643e64f0b7\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" 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-a-linked-list-of-0s-1s-and-2s\/#0-solution-1-brute-force-approach-count-and-replace\" style=\"\">Solution 1: Brute Force Approach (Count and Replace)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#1-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#2-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#3-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#4-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#5-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#6-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#7-simplifying-it\" style=\"\">Simplifying It<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#8-solution-2-optimal-approach-three-separate-lists\" style=\"\">Solution 2: Optimal Approach (Three Separate Lists)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#9-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#10-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#11-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#12-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#13-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#14-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#15-simplifying-it\" style=\"\">Simplifying It<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sort-a-linked-list-of-0s-1s-and-2s\/#16-summary\" style=\"\">Summary<\/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-solution-1-brute-force-approach-count-and-replace\">Solution 1: Brute Force Approach (Count and Replace)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition\">Intuition<\/h3>\n\n\n\n<p>Think of this like organizing colored balls in a box! You have three colors &#8211; let&#8217;s say red (0), blue (1), and green (2) balls mixed up. One simple way to organize them is to first count how many balls of each color you have, then arrange them in order. You&#8217;d put all red balls first, then all blue balls, then all green balls. We use the same idea here &#8211; count all the 0s, 1s, and 2s, then replace the values in the original list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Count Phase<\/strong>: Walk through the entire linked list and count how many 0s, 1s, and 2s we have<\/li>\n\n\n\n<li><strong>Replace Phase<\/strong>: Walk through the linked list again and replace values in order<\/li>\n\n\n\n<li><strong>Fill 0s First<\/strong>: Replace the first&nbsp;<code>count0<\/code>&nbsp;nodes with 0<\/li>\n\n\n\n<li><strong>Fill 1s Next<\/strong>: Replace the next&nbsp;<code>count1<\/code>&nbsp;nodes with 1<\/li>\n\n\n\n<li><strong>Fill 2s Last<\/strong>: Replace the remaining&nbsp;<code>count2<\/code>&nbsp;nodes with 2<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled 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.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 segregate(self, head):\n        if head is None or head.next is None:\n            return head  # Empty list or single node - already sorted\n        \n        temp = head\n        cnt0, cnt1, cnt2 = 0, 0, 0  # Counters for 0s, 1s, and 2s\n        \n        # First pass: Count occurrences of each value\n        while temp:\n            if temp.data == 0:\n                cnt0 += 1     # Count 0s\n            elif temp.data == 1:\n                cnt1 += 1     # Count 1s\n            else:\n                cnt2 += 1     # Count 2s\n            temp = temp.next\n        \n        temp = head  # Reset pointer to head for second pass\n        \n        # Second pass: Replace values with sorted order\n        # Fill first cnt0 nodes with 0\n        for _ in range(cnt0):\n            temp.data = 0\n            temp = temp.next\n        \n        # Fill next cnt1 nodes with 1\n        for _ in range(cnt1):\n            temp.data = 1\n            temp = temp.next\n        \n        # Fill remaining cnt2 nodes with 2\n        for _ in range(cnt2):\n            temp.data = 2\n            temp = temp.next\n        \n        return head\" 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\">segregate<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">head<\/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\"> head <\/span><span style=\"color: #569CD6\">is<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> head.next <\/span><span style=\"color: #569CD6\">is<\/span><span style=\"color: #D4D4D4\"> <\/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: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> head  <\/span><span style=\"color: #6A9955\"># Empty list or single node - already sorted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        temp = head<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        cnt0, cnt1, cnt2 = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># Counters for 0s, 1s, and 2s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># First pass: Count occurrences of each value<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> temp:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> temp.data == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cnt0 += <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">     <\/span><span style=\"color: #6A9955\"># Count 0s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> temp.data == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cnt1 += <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">     <\/span><span style=\"color: #6A9955\"># Count 1s<\/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\">                cnt2 += <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">     <\/span><span style=\"color: #6A9955\"># Count 2s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp = temp.next<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        temp = head  <\/span><span style=\"color: #6A9955\"># Reset pointer to head for second pass<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Second pass: Replace values with sorted order<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Fill first cnt0 nodes with 0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cnt0):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp.data = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp = temp.next<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Fill next cnt1 nodes with 1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cnt1):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp.data = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp = temp.next<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Fill remaining cnt2 nodes with 2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(cnt2):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp.data = <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            temp = temp.next<\/span><\/span>\n<span class=\"line\"><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\"> head<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-code-explanation\">Code Explanation<\/h3>\n\n\n\n<p>We use a two-pass approach here. In the first pass, we count how many times each value (0, 1, and 2) appears in the linked list. In the second pass, we go through the linked list again and replace the values in sorted order. We first fill the required number of nodes with 0s, then with 1s, and finally with 2s. This ensures all values are arranged in ascending order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-dry-run\">Dry Run<\/h3>\n\n\n\n<p>Let&#8217;s trace through:&nbsp;<code>1 -&gt; 0 -&gt; 2 -&gt; 1 -&gt; 0<\/code><\/p>\n\n\n\n<p><strong>First Pass (Count Values):<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Visit node 1: cnt0=0, cnt1=1, cnt2=0<\/li>\n\n\n\n<li>Visit node 0: cnt0=1, cnt1=1, cnt2=0<\/li>\n\n\n\n<li>Visit node 2: cnt0=1, cnt1=1, cnt2=1<\/li>\n\n\n\n<li>Visit node 1: cnt0=1, cnt1=2, cnt2=1<\/li>\n\n\n\n<li>Visit node 0: cnt0=2, cnt1=2, cnt2=1<\/li>\n<\/ul>\n\n\n\n<p><strong>Second Pass (Replace Values):<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Fill 2 nodes with 0:&nbsp;<code>0 -&gt; 0 -&gt; 2 -&gt; 1 -&gt; 0<\/code><\/li>\n\n\n\n<li>Fill 2 nodes with 1:&nbsp;<code>0 -&gt; 0 -&gt; 1 -&gt; 1 -&gt; 0<\/code><\/li>\n\n\n\n<li>Fill 1 node with 2:&nbsp;<code>0 -&gt; 0 -&gt; 1 -&gt; 1 -&gt; 2<\/code><\/li>\n<\/ul>\n\n\n\n<p><strong>Result:<\/strong>&nbsp;<code>0 -&gt; 0 -&gt; 1 -&gt; 1 -&gt; 2<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(n) &#8211; We traverse the list twice, but it&#8217;s still linear<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1) &#8211; We only use a few counter variables<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-simplifying-it\">Simplifying It<\/h3>\n\n\n\n<p>This approach is like taking inventory first, then organizing. You count everything you have, then arrange them in the right order. It&#8217;s straightforward but requires two passes through the list &#8211; one to count, one to replace.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-solution-2-optimal-approach-three-separate-lists\">Solution 2: Optimal Approach (Three Separate Lists)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-intuition\">Intuition<\/h3>\n\n\n\n<p>Imagine you have three separate boxes labeled &#8220;0s&#8221;, &#8220;1s&#8221;, and &#8220;2s&#8221;. Instead of counting first, you can directly sort items as you see them! As you go through the mixed items, you put each item directly into its correct box. At the end, you just connect all three boxes in order &#8211; first the 0s box, then the 1s box, then the 2s box.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Create Three Lists<\/strong>: Set up three separate linked lists for 0s, 1s, and 2s using dummy nodes<\/li>\n\n\n\n<li><strong>Sort While Traversing<\/strong>: Go through the original list and put each node into its correct list<\/li>\n\n\n\n<li><strong>Track Tails<\/strong>: Keep track of the last node in each list to add new nodes easily<\/li>\n\n\n\n<li><strong>Connect Lists<\/strong>: Connect the three lists in order: 0s \u2192 1s \u2192 2s<\/li>\n\n\n\n<li><strong>Handle Empty Lists<\/strong>: Make sure to handle cases where some lists might be empty<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled 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.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 segregate(self, head):\n        # Create three dummy nodes to start three separate lists\n        zeroD = Node(0)   # Dummy node for 0s list\n        oneD = Node(1)    # Dummy node for 1s list  \n        twoD = Node(2)    # Dummy node for 2s list\n\n        # Initialize pointers to track the end of each list\n        zero = zeroD      # Current end of 0s list\n        one = oneD        # Current end of 1s list\n        two = twoD        # Current end of 2s list\n\n        curr_node = head  # Pointer to traverse original list\n        \n        # Traverse the original list and distribute nodes\n        while curr_node:\n            # Check current node's value and add to appropriate list\n            if curr_node.data == 0:\n                zero.next = curr_node  # Add to 0s list\n                zero = zero.next       # Move 0s list pointer\n            elif curr_node.data == 1:\n                one.next = curr_node   # Add to 1s list\n                one = one.next         # Move 1s list pointer\n            else:\n                two.next = curr_node   # Add to 2s list\n                two = two.next         # Move 2s list pointer\n            curr_node = curr_node.next\n\n        # Connect the three lists: 0s -&gt; 1s -&gt; 2s\n        if oneD.next:\n            zero.next = oneD.next      # Connect 0s to 1s if 1s exist\n        else:\n            zero.next = twoD.next      # Connect 0s to 2s if no 1s exist\n        \n        one.next = twoD.next           # Connect 1s to 2s\n        two.next = None                # End the final list\n\n        return zeroD.next              # Return head of sorted list (skip dummy)\" 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\">segregate<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">head<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Create three dummy nodes to start three separate lists<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        zeroD = Node(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)   <\/span><span style=\"color: #6A9955\"># Dummy node for 0s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        oneD = Node(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)    <\/span><span style=\"color: #6A9955\"># Dummy node for 1s list  <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        twoD = Node(<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">)    <\/span><span style=\"color: #6A9955\"># Dummy node for 2s list<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Initialize pointers to track the end of each list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        zero = zeroD      <\/span><span style=\"color: #6A9955\"># Current end of 0s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        one = oneD        <\/span><span style=\"color: #6A9955\"># Current end of 1s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        two = twoD        <\/span><span style=\"color: #6A9955\"># Current end of 2s list<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        curr_node = head  <\/span><span style=\"color: #6A9955\"># Pointer to traverse original list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Traverse the original list and distribute nodes<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> curr_node:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Check current node&#39;s value and add to appropriate list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> curr_node.data == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                zero.next = curr_node  <\/span><span style=\"color: #6A9955\"># Add to 0s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                zero = zero.next       <\/span><span style=\"color: #6A9955\"># Move 0s list pointer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> curr_node.data == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                one.next = curr_node   <\/span><span style=\"color: #6A9955\"># Add to 1s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                one = one.next         <\/span><span style=\"color: #6A9955\"># Move 1s list pointer<\/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\">                two.next = curr_node   <\/span><span style=\"color: #6A9955\"># Add to 2s list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                two = two.next         <\/span><span style=\"color: #6A9955\"># Move 2s list pointer<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            curr_node = curr_node.next<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Connect the three lists: 0s -&gt; 1s -&gt; 2s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> oneD.next:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            zero.next = oneD.next      <\/span><span style=\"color: #6A9955\"># Connect 0s to 1s if 1s exist<\/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\">            zero.next = twoD.next      <\/span><span style=\"color: #6A9955\"># Connect 0s to 2s if no 1s exist<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        one.next = twoD.next           <\/span><span style=\"color: #6A9955\"># Connect 1s to 2s<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        two.next = <\/span><span style=\"color: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># End the final list<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> zeroD.next              <\/span><span style=\"color: #6A9955\"># Return head of sorted list (skip dummy)<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-code-explanation\">Code Explanation<\/h3>\n\n\n\n<p>We create three separate linked lists using dummy nodes as starting points. As we traverse the original list, we move each node to its appropriate list based on its value. We keep track of the tail of each list so we can easily add new nodes. Finally, we connect the three lists in order: all 0s first, then all 1s, then all 2s. We handle the case where some lists might be empty by checking before connecting.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-dry-run\">Dry Run<\/h3>\n\n\n\n<p>Let&#8217;s trace through:&nbsp;<code>1 -&gt; 0 -&gt; 2 -&gt; 1 -&gt; 0<\/code><\/p>\n\n\n\n<p><strong>Initial Setup:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>zeroD \u2192 (dummy), oneD \u2192 (dummy), twoD \u2192 (dummy)<\/li>\n\n\n\n<li>zero = zeroD, one = oneD, two = twoD<\/li>\n<\/ul>\n\n\n\n<p><strong>Process Each Node:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Node 1: Add to 1s list \u2192 oneD \u2192 1<\/li>\n\n\n\n<li>Node 0: Add to 0s list \u2192 zeroD \u2192 0<\/li>\n\n\n\n<li>Node 2: Add to 2s list \u2192 twoD \u2192 2<\/li>\n\n\n\n<li>Node 1: Add to 1s list \u2192 oneD \u2192 1 \u2192 1<\/li>\n\n\n\n<li>Node 0: Add to 0s list \u2192 zeroD \u2192 0 \u2192 0<\/li>\n<\/ul>\n\n\n\n<p><strong>Connect Lists:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>0s list: zeroD \u2192 0 \u2192 0<\/li>\n\n\n\n<li>1s list: oneD \u2192 1 \u2192 1<\/li>\n\n\n\n<li>2s list: twoD \u2192 2<\/li>\n\n\n\n<li>Connect: 0 \u2192 0 \u2192 1 \u2192 1 \u2192 2<\/li>\n<\/ul>\n\n\n\n<p><strong>Result:<\/strong>&nbsp;<code>0 \u2192 0 \u2192 1 \u2192 1 \u2192 2<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(n) &#8211; We traverse the list only once<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1) &#8211; We only use a few pointer variables (dummy nodes don&#8217;t count as extra space)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-simplifying-it\">Simplifying It<\/h3>\n\n\n\n<p>This approach is like having three separate conveyor belts &#8211; one for each value. As items come in, you immediately put them on the correct belt. At the end, you just connect the three belts in order. More efficient since you only need one pass through the original list!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"16-summary\">Summary<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Approach<\/th><th>Time<\/th><th>Space<\/th><th>Difficulty<\/th><th>Best For<\/th><\/tr><\/thead><tbody><tr><td>Brute Force (Count &amp; Replace)<\/td><td>O(n)<\/td><td>O(1)<\/td><td>Easy<\/td><td>Learning the concept<\/td><\/tr><tr><td>Optimal (Three Lists)<\/td><td>O(n)<\/td><td>O(1)<\/td><td>Medium<\/td><td>Production code<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The&nbsp;<strong>optimal approach<\/strong>&nbsp;is generally preferred because it solves the problem in a single pass while using the same space complexity. However, the brute force approach is more intuitive and easier to understand when you&#8217;re first learning about linked list manipulation.<\/p>\n\n\n\n<p>Both solutions effectively solve the problem with the same time and space complexity, but the optimal solution is more elegant because it sorts the nodes in one pass. The key insight is that when you only have three possible values, you can create separate &#8220;buckets&#8221; for each value and then combine them, which is much more efficient than general sorting algorithms!<\/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 the&nbsp;head&nbsp;of a linked list where nodes can contain values&nbsp;0s,&nbsp;1s,&nbsp;and&nbsp;2s&nbsp;only. Your&nbsp;task is to&nbsp;rearrange&nbsp;the list so that all&nbsp;0s&nbsp;appear at the beginning, followed by all&nbsp;1s, and all&nbsp;2s&nbsp;are placed at the end. Here&#8217;s the [Problem Link] to begin with. Examples: Input: head = 1 \u2192 2 \u2192 2 \u2192 1 \u2192 2 \u2192 0 \u2192 2 \u2192 2Output:<\/p>\n","protected":false},"author":1,"featured_media":667,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[19,29],"class_list":{"0":"post-666","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-medium","10":"tag-singly-linked-list"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/sort-a-linked-list-of-0s-1s-and-2s-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\/666","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=666"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/666\/revisions"}],"predecessor-version":[{"id":669,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/666\/revisions\/669"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/667"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=666"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=666"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=666"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}