<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zouhair Tajdine on Medium]]></title>
        <description><![CDATA[Stories by Zouhair Tajdine on Medium]]></description>
        <link>https://medium.com/@tajdine.zouhair?source=rss-83a5b7e26e54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vUkZaCkfmoiD4rCJEQ2ikg.png</url>
            <title>Stories by Zouhair Tajdine on Medium</title>
            <link>https://medium.com/@tajdine.zouhair?source=rss-83a5b7e26e54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:35:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tajdine.zouhair/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Push Swap: The Path to Sorting 500 Numbers in Under 3,850 Moves]]></title>
            <link>https://medium.com/@tajdine.zouhair/mastering-push-swap-the-path-to-sorting-500-numbers-in-under-3-850-moves-977a8292aebb?source=rss-83a5b7e26e54------2</link>
            <guid isPermaLink="false">https://medium.com/p/977a8292aebb</guid>
            <category><![CDATA[ecole-42]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[push-swap]]></category>
            <category><![CDATA[born2code]]></category>
            <category><![CDATA[42-network]]></category>
            <dc:creator><![CDATA[Zouhair Tajdine]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 16:29:56 GMT</pubDate>
            <atom:updated>2025-10-14T16:29:56.602Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“ Shout-out to anyone who studying hard.. and we don’t mess with lazy people. Study, and keep on studying.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EStZwqYqF27IGK25wpjNog.png" /></figure><p><em>Oh Push Swap.. what a monster you were..<br>I’ve enjoyed facing all those obstacles along the way .. and every step of the confrontation with this beast. <br>Bugs came out of nowhere.. hitting me on the head, leaving me injured..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*9M9lrdpC7xsAehYDrt-uxg.png" /></figure><p><em>Got stabbed in the back by unexpected memory leaks.. blood pouring out of my mouth ..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*sv4Fe1g1o235qeN3NYRYjg.png" /></figure><p><em>Hearing the black hole on the edge with its terrifying evil laugh ..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*KQlja0DPkJtO0xwAjtkRbQ.png" /></figure><p><em>And the worst part of all this … was losing my sister .. passing away to heaven while I was still fighting .. <br>But none of that defeated me, none of that broke my will.. NAH.. I was still standing !!!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ei8tWDXZSqOBQepO7HT9pA.gif" /></figure><p><em>Matter of fact.. I was getting even more excited.. a wide smile spread across my face, with a terrifying look in my eyes filled with RAGE..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*iv3Sl_ZG1qBFbtccjETTCQ.png" /></figure><p><em>I drew my sword from the ground and jumped up.. face to face with this WILD beast, while my heart burned with the flames of excitement !</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ufmg2Avhj8u_Bg_Mf4qfqw.gif" /></figure><p><em>And here I am now, recounting to you, dear reader, my fantastic adventure.. may it guide you on your way when you face this Level 2 Circle dungeon BOSS.</em></p><p><strong>Now</strong> that we’re past the intro (I hope you liked it! ^^), let’s dive in.</p><p>You may have seen many articles and documents about push_swap. Some explain the subject itself and what you should do, others explain how operations works and how to manipulate your stacks, and some of them explained in detailed way some of the algorithms that exist.</p><p>I’m not going to do that here, other students have done a fantastic job doing all of those documentations , actually if you didn’t see any of those articles yet i highly i suggest cheeking up on them if you didn’t so. But what i m doing instead in this article.. is that i will try to give my own perspective in a fun way, to make sure you, my dear reader .. don’t feel bored while reading it.</p><p>I will go through things that i struggled to find when i as looking to understand what is told me to do and getting out from that “void” period when you are just getting started with a new 42 project. Answering frequent questions that i get from my peers who look at my code, and overall, make push_swap more fun .. especially since I’ve noticed people don’t like it that much.</p><p>I’m not here to force you to follow my way, not at all. My goal is to give you another perspective on this project.. so you can choose the path that’s destined for you. This is about helping you make the right choice, to pick up the perfect items and tips that will suit you for going inside this dungeon to face this boss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ugQbDoj4GyUFgiUXudPrjQ.png" /></figure><p>Before you can fight the boss, you don’t only need items and … need a strategy. In the world of programming, these strategies are called algorithms. Some are simple .. but brutish, while others are elegant .. but they are complex to implement.</p><p>Let’s look at one of those simplest algorithms. You’ve probably seen during the Piscine a code look like this :</p><pre>    i = 0;<br><br>    while (i &lt; size - 1)<br>    {<br>        j = i;<br>        while (j &lt; size)<br>        {<br>            if (tab[i] &gt; tab[j])<br>            {<br>                tmp = tab[i];<br>                tab[i] = tab[j];<br>                tab[j] = tmp;<br>            }<br>            j++;<br>        }<br>        i++;<br>    }</pre><p>This is a code for sorting an array of integers. The strategy is simple: find the smallest element in the entire array and swap it with the first element, then move to the second position .. again find the smallest element in the <em>rest</em> of the array.. and swap it into place. This continues until the whole array is sorted in ascending order. This method is called <strong>Selection Sort</strong>.</p><p><strong><em>This looks so simple, why not using on push_swap ?</em></strong></p><p>Hmm .. well .. this is where the problem lies, the constant re-scanning each time to find the smallest element in the array, The time complexity for Selection Sort is <strong>O(<em>n²</em>) </strong>that because we are doing two loops<strong> </strong>( ah sh*t 😱.. mathematical stuff !! .. Get me out of here … Don’t worry dear reader, it’s not that scary as you might think it is .. everything will be alright).</p><p>The first loop while (i &lt; size - 1)is to select an element of array one by one , it’s time complexity will be = O(<em>n</em>). <br>The second loop while (j &lt; size)​ is for comparing that element with every other array element , and also it’s time complexity will be = O(<em>n</em>).<br>And now to get the overall complexity, we will simply do the multiplication of the <em>complexity of the first loop</em> * <em>complexity of the second loop</em></p><p>That means: = O(n) * O(n)</p><p>Which is the same thing as: = O(n * n)</p><p>Therefore: = O(n²)</p><p><strong><em>But wait .. what this Big O Really Is ?</em></strong></p><p>Think of Big O as a <strong>category</strong> that describes an algorithm’s overall efficiency as the input grows, it basically answers the question: <em>“If my array doubles in size, how much more work will my algorithm have to do? Will it be twice as much? Four times as much? A lot more?”<br></em>Ok let’s imagine you’re building a square wall 🧱 . The wall’s size is n bricks high and n bricks wide. To build an n x n wall, I need to lay n * n or n² bricks. The effort required is in the <strong>category of O(<em>n²</em>)</strong>.<br>Whether the wall is 10x10 or 100x100, the <em>formula</em> for the total work (n²) stays the same. The Big O describes this formula.</p><p>Let’s take an example of an array like this [42, 13, 37] of size n=3, the Selection Sort algorithm will have a time complexity of <strong>O(n²) :</strong></p><ol><li><strong>First Pass (i=0):</strong></li></ol><ul><li>The algorithm needs to find the smallest element in the <em>entire</em> array [42, 13, 37] to place it at the first position.</li><li>It compares 42 with 13.</li><li>It compares the winner (13) with 37.</li></ul><p>This pass requires roughly<em> -&gt; </em><strong><em>3 &lt;- </em>comparisons</strong>.</p><ul><li><em>Resulting Array:</em> [13, 42, 37]</li></ul><ol><li><strong>Second Pass (i=1):</strong></li></ol><ul><li>The algorithm now looks for the smallest element in the <em>rest</em> of the array [42, 37].</li><li>It compares 42 with 37.</li><li>This pass requires<em> -&gt; </em><strong><em>2 &lt;- </em>comparisons</strong>.</li><li><em>Resulting Array:</em> [13, 37, 42]</li></ul><p>The total number of comparisons is 3 + 2 = 5. For an array of size n, the total is roughly n * n, which is why we categorize it as <strong>O(<em>n²</em>)</strong>.</p><p>Since the size of array is n = 3, the complexity is <strong>O(3²)</strong>, which is <strong>O(9)</strong>.</p><p>You might ask, <em>“But we only counted 5 comparisons, so why 9?”</em></p><p>That’s because Big O notation gives you an <em>estimate</em> of the growth. The exact number of operations was 5. While not exactly 9, <strong>BUT </strong>the 9 is the theoretical value which reflect the quadratic growth pattern that O(<em>n²</em>) describes, giving us an estimate around 9. <br>The key takeaway is that the number of operations is roughly proportional to n squared. If you had an array of n=100, the work would be proportional to 100² (10,000). or an array of n=500The work would be proportional to 500² (250,000) . Insane right ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*9uvSiIRikIjDag-ZBW5oLw.png" /></figure><p>So that’s why for our <strong>push_swap</strong> project, this is a fatal flaw. To “find the smallest element” in Stack A you would have to rotate through the stack (ra or rra) many times just to inspect all the numbers. Each rotation is a move. After you find the smallest, you then have to perform even more moves to bring it to the top and push it to Stack B. Repeating this process for every single number would result in a massive number of operations.</p><p>This article breaks down the architecture and algorithms behind one approach to this fascinating problem. We’ll explore the design choices, from the underlying data structures to the core sorting logic.</p><p>( To be continued … )</p><p>Before writing any code, it’s crucial to understand time complexity — how an algorithm’s runtime scales with the size of the input (n).</p><pre>🟢 O(n) — Linear Time: The fastest category. The work grows linearly <br>    with the input size. Think of a single pass over a list, like checking<br>    if it’s already sorted.<br><br>🟡 O(nlogn) - Linearithmic Time: The gold standard for general-purpose <br>    sorting algorithms like Merge Sort or Quick Sort.<br>    It&#39;s highly efficient for large datasets.<br><br>🔴 O(n2) - Quadratic Time: The runtime grows exponentially. <br>    This is acceptable for very small inputs but becomes a major bottleneck <br>    as the list gets larger. <br>    Simple algorithms like Bubble Sort fall into this category</pre><p>In this project, the goal was to build the core sorting algorithm with <br>O(<em>n logn)</em> efficiency. However, one of the initial data processing steps, the ranking system, used a simpler O(<em>n2</em>) approach. This highlights a key lesson in software development: the overall performance of a system is often determined by its least efficient component.</p><p><em>Project Architecture</em></p><p>The project is structured in a three-layer architecture, ensuring a clear separation of concerns from input parsing to the final output.</p><pre>┌─────────────────────────────────────────────────────────┐<br>│ INPUT LAYER                                             │<br>│ • Argument validation &amp; parsing                         │<br>│ • Integer conversion &amp; duplicate checking               │<br>│ • Ranking system (normalize numbers to a 1-n range)     │<br>└─────────────────────────────────────────────────────────┘<br>                              │<br>                              ▼<br>┌─────────────────────────────────────────────────────────┐<br>│ ALGORITHM LAYER                                         │<br>│ • Strategy selection based on input size                │<br>│ • Recursive chunk-based sorting algorithm               │<br>│ • Pre-computed move sequences for optimal routing       │<br>└─────────────────────────────────────────────────────────┘<br>                              │<br>                              ▼<br>┌─────────────────────────────────────────────────────────┐<br>│ OUTPUT LAYER                                            │<br>│ • Operation recording &amp; optimization                    │<br>│ • Redundant move elimination &amp; merging                  │<br>│ • Final sequence of operations is printed               │<br>└─────────────────────────────────────────────────────────┘</pre><p>This modular design makes the code easier to manage, debug, and understand. Each layer has a distinct responsibility.</p><p><em>Core Data Structures</em></p><p>The foundation of the project rests on a few key data structures defined in includes/stack.h.</p><p>The Stack: An Array-Based Circular Buffer</p><p>A crucial design decision was how to represent the stacks. Instead of a traditional linked list, a dynamic array was chosen.</p><pre>typedef struct s_stack<br>{<br> int *array; // Dynamic array for elements<br> int top; // Index of the top element<br> int bottom; // Index of the bottom element<br> int size; // Maximum capacity<br>} t_stack;</pre><p>🤔 Question: Why use an array instead of a linked list for a stack?</p><p>This choice comes down to performance and the specific constraints of the problem.</p><p>Cache Performance: Arrays store data in a contiguous block of memory. When we access an element, the CPU often loads nearby elements into its cache, making subsequent accesses much faster.</p><p>Memory Overhead: Linked lists require an extra pointer for every single element, which can add up significantly for large inputs.</p><p>Known Size: We know the maximum number of elements from the start (<em>argc</em>), so we can allocate all the necessary memory at once.</p><p>To handle rotations (<em>ra, rra</em>) efficiently, the array is implemented as a circular buffer. Instead of shifting all elements an <em>O(n)</em> operation — we simply move the top and bottom pointers. This turns a costly data shift into a lightning fast <em>O(1) </em>index calculation.</p><p><em>The Master Structure: The Right Tool for Each Job</em></p><p>The main structure holds the two stacks and a list of operations performed.</p><pre>typedef struct s_push_swap<br>{<br> t_stack stack_a; // Embedded stack A<br> t_stack stack_b; // Embedded stack B<br> t_list *opr_list; // Operations linked list<br> bool record_opr; // Toggle for recording operations<br>} t_ps;</pre><p>🤔 Question: Why use different data structures arrays for stacks and a linked list for operations?</p><p>This is a classic example of choosing the right tool for the job.</p><p>Stacks: Have a fixed maximum size and benefit from the random access and cache performance of arrays.</p><p>Operations List: The final number of sorting operations is unknown. A linked list is perfect here because it can grow dynamically as needed without overallocating memory.</p><p><strong><em>The Stack System</em></strong></p><p>This part of the project handles input validation, data normalization, and the low-level mechanics of the circular buffer.</p><p>The Power of Normalization: The Ranking System</p><p>To make the sorting algorithm generic, the raw input numbers (e.g., -17, 0, 42, 999) are converted into a simple sequence of ranks (e.g., 1, 2, 3, 4).<br>C</p><p>// Example Transformation:<br>// Input: [42, -17, 999, 0, 55]<br>// Ranks: [3, 1, 5, 2, 4]</p><p>🤔 Reader Question: Why convert numbers to ranks?</p><p>Predictable Range: The algorithm knows it’s always dealing with numbers from 1 to n. This simplifies pivot selection and boundary checks.</p><p>Algorithm Independence: The sorting logic doesn’t care about the original values, only their relative order.</p><p>The initial implementation of this ranking system uses nested loops, resulting in O(n2) complexity. A more performant alternative for larger inputs would be an O(nlogn) approach, such as sorting a temporary array of value-index pairs.</p><p>Robust Input Validation</p><p>The program must handle various invalid inputs gracefully, such as non-numeric arguments, duplicates, or numbers that exceed an integer’s limits. A key technique used here is parsing the number into a long long int first. This allows us to check if the value is outside the INT_MAX or INT_MIN range before an overflow occurs.</p><p>A Subtle Edge Case in the Circular Buffer</p><p>Calculating the current size of a circular buffer requires careful logic, especially for detecting an empty state. The initial logic checked if array[top] == 0 to see if the stack was empty. This works because ranks are 1-based, so a rank of 0 will never appear. However, this is an assumption. A more robust solution would be to maintain a separate current_count variable that is incremented on push and decremented on pop.</p><p><strong><em>The Sorting Engine</em></strong></p><p>This is the heart of the project, where the actual sorting takes place.</p><p>Strategy Dispatcher: One Size Doesn’t Fit All</p><p>The main sort function acts as a dispatcher, choosing the best algorithm based on the number of elements.<br>C</p><pre>void sort(t_ps *data)<br>{<br> if (/* already sorted */)<br>   return;<br> else if (size == 3)<br>   sort_three_a(data); // Hardcoded optimal solution<br> else if (size == 5)<br>   sort_five_a(data); // Push smallest two to B, sort 3, push back<br> else<br>   chunk_sort(data); // General-purpose recursive algorithm<br> <br> post_sort_optimization(data); // Clean up the final instruction list<br>}</pre><p>Size 3: All 6 permutations can be solved with a maximum of 2 operations. A simple if/else if structure handles each case optimally.</p><p>Size 5: A common strategy is to isolate the two smallest numbers (ranks 1 and 2) by pushing them to stack B. Then, the remaining three are sorted on stack A, and the two are pushed back in order.</p><p>Larger Sizes: A recursive “divide and conquer” algorithm is used.</p><p>The Recursive Heart: A 3-Way Chunk Sort</p><p>The general-purpose algorithm is a recursive function that splits a “chunk” of numbers into three smaller groups based on pivots: small, medium, and large.</p><p>🤔 Question: Why a 3-way split instead of a 2-way split like in a standard Quicksort?</p><p>In a typical Quicksort, swaps are cheap. In Push_Swap, operations (ra, pb, etc.) are the resource we want to minimize. A 3-way split reduces the depth of the recursion (from <em>log2​(n)</em> to <em>log3​(n)</em>), which can lead to fewer overall moves.</p><p>Conclusion &amp; Key TakeawaysThe algorithm uses the concept of virtual chunks. Instead of physically separating the data, we simply track the location (<strong>TOP_A, BOTTOM_B,</strong> etc.) and size of each logical group of numbers.</p><p>The recursion proceeds as follows:</p><p>Split the current chunk into three smaller ones (e.g., push small numbers to the top of B, large numbers to the bottom of B, and keep medium numbers in A).</p><p>Recurse on the large chunk.</p><p>Recurse on the medium chunk.</p><p>Recurse on the small chunk.</p><p>The base cases for the recursion are chunks of size 3 or less, which are handled by the specialized small-sort functions.</p><p>The Optimizer: Cleaning Up the Mess</p><p>After the sorting algorithm generates a list of operations, a final optimization pass cleans it up.</p><p>Elimination: It removes redundant pairs, like a ra followed by a rra, which cancel each other out.</p><p>Merging: It combines adjacent operations into more efficient ones, like changing ra and rb into a single rr.</p><p>This post-processing step can significantly reduce the final operation count. The logic is also careful not to cancel operations that are separated by an instruction that changes the stack state (e.g., ra, pb, rra cannot be optimized, because the pb changes what rra would affect).</p><p><strong><em>The Checker Program</em></strong></p><p>The project also includes a checker program. Its job is to read a list of numbers and a sequence of operations from standard input. It applies the operations to the stack and then prints “OK” if the numbers are sorted and stack B is empty, or “KO” otherwise.</p><p>This is a crucial tool for verification. By piping the output of push_swap into checker, you can confirm that your sorting algorithm works correctly.</p><p>$&gt; ./push_swap 4 2 3 1 | ./checker 4 2 3 1<br>OK</p><p>To ensure consistency, the checker reuses the exact same stack data structures and operation functions from the main push_swap program.</p><p><strong><em>Performance Deep Dive</em></strong></p><p>Let’s look at the project’s performance from two angles: time complexity and memory usage.</p><p>Time Complexity Analysis</p><p>Component Time Complexity Space Complexity Notes<br>Input Parsing O(n) O(n) Optimal.<br>Ranking System O(n2) O(n) The main performance bottleneck for large inputs.<br>Core Sorting O(nlogn) O(logn) Efficient and scales well.<br>Post-optimization O(n) O(1) A fast, linear pass over the operations list.<br>Overall O(n2) O(n) Limited by the ranking system.</p><p>Memory Usage</p><p>The memory footprint is quite small. For an input of n numbers:</p><p>Stack Arrays: 2×n×sizeof(int)</p><p>Operations List: Varies, but roughly $0.5 \times n \times \text{sizeof(t_list_node)}$</p><p>Recursion Stack: $\log_3(n) \times \text{function_call_size}$</p><p>For n=500, the total memory usage is around 10KB, making it a very lightweight program.</p><p><strong><em>Conclusion &amp; Key Takeaways</em></strong></p><p>Working on Push_Swap is a journey through algorithm design, data structures, and optimization. Here are some of the key takeaways from this implementation:</p><p>The Right Data Structure Matters: The choice between an array-based circular buffer and a linked list had significant performance implications. Using both where they fit best (arrays for stacks, linked lists for operations) was a key architectural decision.</p><p>Bottlenecks Can Be Deceiving: An efficient O(nlogn) core algorithm can still be held back by a single, less-performant O(n2) setup step. Always analyze the complexity of your entire pipeline.</p><p>Pre-computation and Abstraction are Powerful: The concepts of “virtual chunks” and pre-computing move sequences allowed the algorithm to reason about groups of numbers without complex runtime calculations.</p><p>Optimization is a Multi-Step Process: Sometimes, the cleanest solution is to generate a decent sequence of operations first and then refine it with a dedicated post-processing step.</p><p>This project is a perfect example of how theoretical computer science concepts — like complexity analysis and algorithm design — intersect with practical software engineering to create an efficient and robust solution.</p><p>📚 Table of Contents</p><p>Choosing the Right Algorithm</p><p>Project Architecture</p><p>Core Data Structures</p><p>The Stack System</p><p>The Sorting Engine</p><p>The Checker Program</p><p>Performance Deep Dive</p><p>Conclusion &amp; Key Takeaways</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=977a8292aebb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>