<?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 hiimdaosui on Medium]]></title>
        <description><![CDATA[Stories by hiimdaosui on Medium]]></description>
        <link>https://medium.com/@hiimdaosui?source=rss-ab5adfe347af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*63qY91CIUCIn-7RJreIafw.png</url>
            <title>Stories by hiimdaosui on Medium</title>
            <link>https://medium.com/@hiimdaosui?source=rss-ab5adfe347af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:15:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiimdaosui/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[Remove Linked List Elements]]></title>
            <link>https://medium.com/@hiimdaosui/remove-linked-list-elements-6ec6b7560327?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ec6b7560327</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Thu, 19 Jul 2018 13:41:35 GMT</pubDate>
            <atom:updated>2018-07-19T13:41:35.777Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Remove all elements from a linked list of integers that have value <strong><em>val</em></strong>.</blockquote><blockquote><strong>Example:</strong></blockquote><pre><strong>Input:</strong>  1-&gt;2-&gt;6-&gt;3-&gt;4-&gt;5-&gt;6, <strong><em>val</em></strong> = 6<br><strong>Output:</strong> 1-&gt;2-&gt;3-&gt;4-&gt;5</pre><p>This problem asks us to remove all nodes in a singly linked list whose val is equal to another input val. This turns out to be a very straightforward question. We will also propose both iterative and recursive solutions here.</p><ul><li><strong>Iterative Solution</strong></li></ul><p>To solve this problem iteratively, we can simply traverse the list once, extracting the node whose value is different from val and delete others.</p><p>Since this is quite obvious, there are only two things that I think are worth noticing is that we’d better use a dummy head as a holder to hold the filtered valid nodes. It’s also mainly because the head might be deleted, so this makes our implementation more convenient.</p><p>Second, at the end of traversal, make sure that the last node in our result list is pointing to NULL to indicate the end of the list. What problem would occur if we don’t do that? Imagine the case where we need to remove the last element in the input list. Then it will not be added to our result list but it is the only node whose next pointer points to NULL, which means that the last element in our result list must not point to NULL, but some random address in the memory. And it could be very risky and dangerous. So make sure to set it empty.</p><pre>ListNode* removeElements(ListNode* head, int val) {<br>    ListNode dummy(0), *it = &amp;dummy;<br>    while (head) {<br>        if (head-&gt;val == val) {<br>            ListNode* toDel = head;<br>            head = head-&gt;next;<br>            delete toDel;<br>        } else {<br>            it-&gt;next = head;<br>            head = head-&gt;next;<br>            it = it-&gt;next;<br>        }<br>    }<br>    it-&gt;next = NULL;<br>    <br>    return dummy.next;<br>}</pre><p>Also, note that in C++, we need to delete the node and free the memory if they are not used any more. It’s not a problem in Java or Python and etc., which have automatic garbage collection.</p><p>Let’s go through an example whose last element needs to be removed:</p><pre>Suppose that we are given a list:</pre><pre>1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL, val = 1</pre><pre>Initialization: dummy -&gt; 1, it = dummy</pre><pre>Current List:       1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>Result List:        dummy-&gt;NULL<br>1st Iteration:      head points to the first 1, remove<br>                    move head to 2<br>                    delete the first 1</pre><pre>Current List:       2-&gt;1-&gt;3-&gt;1<br>Result List:        dummy-&gt;NULL<br>2nd Iteration:      head points to 2, keep<br>                    add 2 to result<br>                    move it to 2<br>                    move head to the second 1<br>                    <br>Current List:       2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>Result List:        dummy-&gt;2-&gt;(1-&gt;3-&gt;1)<br>1st Iteration:      head points to the second 1, remove<br>                    move head to 2<br>                    delete the second 1</pre><pre>Current List:       2-&gt;, 3-&gt;1<br>Result List:        dummy-&gt;2-&gt;<br>2nd Iteration:      head points to 3, keep<br>                    add 3 to result<br>                    move it to 3<br>                    move head to the last 1<br>                    <br>Current List:       2-&gt;3-&gt;1<br>Result List:        dummy-&gt;2-&gt;3-&gt;(1)<br>1st Iteration:      head points to the last 1, remove<br>                    move head to NULL<br>                    delete the last 1</pre><pre>Current List:       2-&gt;3-&gt;<br>Result List:        dummy-&gt;2-&gt;3-&gt;</pre><pre>Post Process:       Point it (3) to NULL</pre><pre>Result List:        dummy-&gt;2-&gt;3-&gt;NULL</pre><pre><strong>return dummy.next = 2</strong></pre><p><strong>Time Complexity: O(n) </strong>— We need to go through the list for once, so the time complexity is apparently linear.</p><p><strong>Space Complexity: O(1)</strong> — Only a dummy head and a few additional pointers are used in this implementation, so the space cost is constant.</p><ul><li><strong>Recursive Solution</strong></li></ul><p>Still, we can try to use recursion to solve this problem since it could be easily broken down into multiple sub-problems. Note that the sub-problem is quite intuitive. We can simply recursively call the list starting from the next node and obtain the post result. Then in the current function, we decide if we keep or remove the current list node.</p><p>So the recursive rule is supposed to be:</p><ol><li>Base Case: The input list is empty.</li><li>Recursive Rules: 1) Get the result from the sub-list starting from the next node. 2) Determine if the current should be kept or removed. If it is kept, then connect it with the result returned from the following list. Otherwise, discard the current node and return the subsequent result.</li></ol><pre>ListNode* removeElements(ListNode* head, int val) {<br>    if (!head) {<br>        return NULL;<br>    }<br>    ListNode* post = removeElements(head-&gt;next, val);<br>    if (head-&gt;val != val) {<br>        head-&gt;next = post;<br>        return head;<br>    }<br>    <br>    delete head;<br>    return post;<br>}</pre><p>The code just straightly demonstrates the algorithm that we described above. post is the result we obtain from the subsequent list. It should contain all the nodes whose values are not equal to val. Also, note that if the current head’s value is the same as val, remember to delete the current node to avoid memory leak.</p><p>Let’s run the same example as the one in the iterative solution:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In Main Function:           call removeElements(1)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(1):       call removeElements(2)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(2):       call removeElements(1)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(1):       call removeElements(3)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(3):       call removeElements(1)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(1):       call removeElements(NULL)</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(NULL):    hit base case<br>                            return NULL</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;1-&gt;NULL<br>In removeElements(1):       get NULL<br>                            1 is equal to 1<br>                            delete 1<br>                            return NULL</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;3-&gt;, NULL<br>In removeElements(3):       get NULL<br>                            3 is not equal to 1<br>                            point 3 to NULL<br>                            return 3</pre><pre>Current List:               1-&gt;2-&gt;1-&gt;, 3-&gt;NULL<br>In removeElements(1):       get 3<br>                            1 is equal to 1<br>                            delete 1<br>                            return 3</pre><pre>Current List:               1-&gt;2-&gt;, 3-&gt;NULL<br>In removeElements(2):       get 3<br>                            2 is not equal to 1<br>                            point 2 to 3<br>                            return 2</pre><pre>Current List:               1-&gt;2-&gt;3-&gt;NULL<br>In removeElements(1):       get 2<br>                            1 is equal to 1<br>                            delete 1<br>                            <strong>return 2</strong></pre><pre>Current List:       2-&gt;3-&gt;NULL<br>In Main Function:   get 2</pre><p><strong>Time Complexity: O(n) </strong>— Same as the iterative solution, we need to go through the list for once, so the time complexity is apparently linear.</p><p><strong>Space Complexity: O(n)</strong> —Every time we need to call the recursion for the next node, so for each node there will be an individual call to handle. So the cost of call stacks is linear. In each function, we only use a couple of local pointers, which are constant. So the entire space complexity is O(n).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ec6b7560327" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Nodes in k-Group]]></title>
            <link>https://medium.com/@hiimdaosui/reverse-nodes-in-k-group-9d232e4a70a7?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d232e4a70a7</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Wed, 18 Jul 2018 18:56:02 GMT</pubDate>
            <atom:updated>2018-07-18T18:58:12.919Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Given a linked list, reverse the nodes of a linked list <em>k</em> at a time and return its modified list.</blockquote><blockquote><em>k</em> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <em>k</em> then left-out nodes in the end should remain as it is.</blockquote><blockquote><strong>Example:</strong></blockquote><blockquote>Given this linked list: 1-&gt;2-&gt;3-&gt;4-&gt;5</blockquote><blockquote>For <em>k</em> = 2, you should return: 2-&gt;1-&gt;4-&gt;3-&gt;5</blockquote><blockquote>For <em>k</em> = 3, you should return: 3-&gt;2-&gt;1-&gt;4-&gt;5</blockquote><blockquote><strong>Note:</strong></blockquote><blockquote>Only constant extra memory is allowed.</blockquote><blockquote>You may not alter the values in the list’s nodes, only nodes itself may be changed.</blockquote><p>This problem asks us to reverse a segment of a linked list with <em>k</em> nodes at a time, which is quite similar to a problem we solved before. Recall that we have dealt with a problem that asked us to reverse the sub-list from the <em>m</em>th node and the <em>n</em>th node in a list. And this one is just to do such operation multiple times. We will also introduce both iterative and recursive solutions for this question.</p><ul><li><strong>Iterative Solution</strong></li></ul><p>The iterative solution could be confusing because it always needs to manipulate a great number of pointers in this type of problems. However, though the implementation may seem a bit messed up, if we are clear what specific steps that we need to accomplish, then this is actually a straightforward problem.</p><p>Very much like that former partial list reversal problem, we need to find the range that we are going to reverse, then reverse the list, and put it back to the correct position. Remember that since we are working on a singly linked list, the four nodes at both sides’ connections are very pivotal. So we always need keep track of those four nodes so that after the reversal, we can splice the reversed sub-list back to the correct place.</p><p>So let’s make a list of what we need to do to fully reverse the entire list <em>k</em> nodes at a time:</p><ol><li>Note that if the subsequent list from head does not contain <em>k</em> nodes, nothing needs to be changed. So we definitely need to check if there are still <em>k </em>nodes left. If there are, we proceed. Otherwise, the algorithm can halt.</li><li>Reverse the subsequent <em>k </em>consecutive nodes. In the meanwhile, keep track of the information of four nodes, the node before head, head, tail, and the node after tail.</li><li>At last, put the reversed sub-list back to the correct position, in between the the node before head (former head) and the node after the tail (former tail).</li><li>Move forward to reverse the next sub-list.</li></ol><p>So after we list all the things we need to do, the logic is quite clear, isn’t it? Next, let’s take a look at the implementation.</p><pre>ListNode* reverseKGroup(ListNode* head, int k) {<br>    if (!head || !head-&gt;next || k &lt;= 1) {<br>        return head;<br>    }<br>    <br>    ListNode dummy(0), *prev = &amp;dummy;<br>    prev-&gt;next = head;<br>    <br>    while (true) {<br>        ListNode* it = prev-&gt;next;<br>        int count = 0;<br>        while (it) {<br>            ++count;<br>            if (count == k) {<br>                break;<br>            }<br>            it = it-&gt;next;<br>        }<br>        if (count &lt; k) {<br>            break;<br>        }<br>        <br>        ListNode* nextPrev = prev-&gt;next;<br>        <br>        ListNode* prev2 = NULL, *cur = prev-&gt;next, *next = NULL;<br>        for (int i = 0; i &lt; k; ++i) {<br>            next = cur-&gt;next;<br>            cur-&gt;next = prev2;<br>            prev2 = cur;<br>            cur = next;<br>        }<br>        <br>        prev-&gt;next = prev2;<br>        nextPrev-&gt;next = cur;<br>        <br>        prev = nextPrev;<br>    }<br>    <br>    return dummy.next;<br>}</pre><p>In terms of the implementation, the code is actually not so straightforward as the algorithm. It is mainly because there are a bunch of pointers that we need to reassign and redirect.</p><p>At first, as usual, let’s check the corner cases. If the input list is empty or it only contains one element, we definitely need to do nothing on it. Also, if <em>k</em> is less than or equal to 1, the input list does not need to change, either. Next, we use the dummy head trick to make our code simpler. Why does it help in this case? The obvious answer is that the head of the input list may change, and if we keep track of the head while we are running our other logic, the algorithm may become very intractable. Moreover, note that we need to reverse the sub-list that contains head. If we want to reverse a sub-list, those four critical nodes at the connections are very important. If we do not have a dummy node here, our head actually has no precedent node, so our algorithm may become hard to code.</p><p>Then, let’s get into the iteration and reverse <em>k </em>nodes at at time. In each iteration, the first thing we need to check is if the list still has at least <em>k</em> subsequent nodes. So a linear scan for at most <em>k </em>nodes is not avoidable. This may seems slightly costly, but we can do a lot more things in this first scan. First, if we find that the traverse reaches the end of the list, we could directly return the current result since no more reversal is needed. Otherwise, we need to keep proceeding. Note that we also need to keep track of those pivotal four connection nodes. Which of them we can already get and store at this moment? Clearly, we can store the precedent node of the head prev and the head node prev-&gt;next now. And after the first iteration, we can also get the last two nodes, but in my implementation, I didn’t store them in advance, because in our reversal step, the cur node will reach the successive node of the last node, right? And prev2 is the old tail and the new head. So we don’t necessarily need to store them previously.</p><p>Then, we can proceed the reversal. Note that we only need to do <em>k</em> times. So be careful about the condition in the loop. At last, we connect those four connections nodes and goes to the next iteration.</p><p>Let’s go through a simple example:</p><pre>Suppose that we are given a list:</pre><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, k = 2</pre><pre>Initialization:     dummy -&gt; 1, prev = dummy</pre><pre>Current List:       dummy-&gt;1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>First Iteration:    let it point to 1<br>                    increase count for 1, becomes 1<br>                    let it point to 2<br>                    increase count for 1, becomes 2</pre><pre>                    there are at least 2 nodes left</pre><pre>                    set nextPrev to 1</pre><pre>                    reverse from 1 to 2</pre><pre>                    let 1 point to NULL<br>                    let 2 point to 1</pre><pre>                    prev2 is 2<br>                    cur is 3</pre><pre>                    let prev (dummy) point to prev2 (2)<br>                    let nextPrev (1) point to cur (3)</pre><pre>                    move prev (dummy) to nextPrev (1)</pre><pre>Current List:       dummy-&gt;2-&gt;1-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Second Iteration:   let it point to 3<br>                    increase count for 1, becomes 1<br>                    let it point to 4<br>                    increase count for 1, becomes 2</pre><pre>                    there are at least 2 nodes left</pre><pre>                    set nextPrev to 3</pre><pre>                    reverse from 3 to 4</pre><pre>                    let 3 point to NULL<br>                    let 4 point to 3</pre><pre>                    prev2 is 4<br>                    cur is 5</pre><pre>                    let prev (1) point to prev2 (4)<br>                    let nextPrev (3) point to cur (5)</pre><pre>                    move prev (1) to nextPrev (3)</pre><pre>Current List:       dummy-&gt;2-&gt;1-&gt;4-&gt;3-&gt;5-&gt;NULL<br>Second Iteration:   let it point to 5<br>                    increment count for 1, becomes 1<br>                    let it point to NULL</pre><pre>                    there is only 1 node left</pre><pre>                    halt<br>                    <br><strong>return dummy.next = 2</strong></pre><p><strong>Time Complexity: O(n) </strong>— Basically, we need to iterate the list twice overall. First, in each iteration, we have to first look ahead to check if there are <em>k</em> nodes left. If there are, we need reverse them, which is another linear scan. So the total time complexity is still linear.</p><p><strong>Space Complexity: O(1)</strong> — The only main data structure we have been using in this implementation are still pointers, so the space cost is constant.</p><ul><li><strong>Recursive Solution</strong></li></ul><p>We’ve gone through the iterative solution. Now, it’s turn for the recursion, as well.</p><p>Initially, we still need to think about how could we break down the big problem into smaller ones. So in this problem, we are asked to reverse <em>k </em>nodes at a time, so what we are going to do is to reverse first <em>k </em>nodes, then the second set of <em>k </em>nodes and so on, until we reach the end of the list. So in each iteration, we are going to make a <em>k-</em>time reversal and jump to the next round. Thus, if we can do that reversal in the current function call, and then somehow directly obtain a reversed result for the subsequent linked list, and connect them correctly, the problem should be solved. Note that “directly obtain a reversed result for the subsequent linked list” requires us to use the same strategy to reverse a smaller list, so this is the sub-problem that we are looking for.</p><p>Next, let’s talk about the specific recursive rule:</p><ol><li>Base case: The list has less than <em>k</em> nodes.</li><li>Recursive Rules: 1) Recursively reverse the list beginning from <em>k+1-</em>th node. 2) Reverse the <em>k</em> nodes starting from current head, and connect the new reversed sub-list to the post result.</li></ol><p>For the base case, I’d say it’s not that intuitive since so many questions have base cases that could be solved in a constant time. But here, note that to detect if the function call hits the base case or not, it requires at least a scan for <em>k</em> nodes. But we can also do multiple things in this first scan, i.e. get the starting node for the next recursive call, which is supposed to be the <em>k+1</em>-th node.</p><p>Next, we can make the next recursive call to reverse the subsequent list, and in the current function, we will do the local reversal and then connect the new reversed list to the post result we obtain from the sub-problem. Then everything is done.</p><pre>ListNode* reverseKGroup(ListNode* head, int k) {<br>    ListNode* it = head;<br>    int count = 0;<br>    while (it) {<br>        ++count;<br>        if (count == k) {<br>            break;<br>        }<br>        it = it-&gt;next;<br>    }<br>    if (count &lt; k)<br>        return head;<br>    <br>    ListNode* post = reverseKGroup(it-&gt;next, k);<br>    <br>    ListNode* prev = NULL, *cur = head, *next = NULL;<br>    for (int i = 0; i &lt; k; ++i) {<br>        next = cur-&gt;next;<br>        cur-&gt;next = prev;<br>        prev = cur;<br>        cur = next;<br>    }<br>    <br>    head-&gt;next = post;<br>    <br>    return prev;<br>}</pre><p>The structure of the code is quite similar to the iterative solution. We just need to let the subsequent recursive calls to handle all those sub-problems. Our focus in each function call is just to reverse the current <em>k</em> nodes starting from the input head.</p><p>Again, let’s try an example:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, k = 2</pre><pre>Current List:           1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In Main Function:       call reverseKGroup(1)</pre><pre>Current List:           1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In reverseKGroup(1):    let it point to 1<br>                        increase count for 1, becomes 1<br>                        let it point to 2<br>                        increase count for 1, becomes 2</pre><pre>                        there are at least 2 nodes</pre><pre>                        call reverseKGroup(3)</pre><pre>Current List:           1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In reverseKGroup(3):    let it point to 3<br>                        increase count for 1, becomes 1<br>                        let it point to 4<br>                        increase count for 1, becomes 2</pre><pre>                        there are at least 2 nodes</pre><pre>                        call reverseKGroup(5)</pre><pre>Current List:           1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In reverseKGroup(5):    let it point to 5<br>                        increase count for 1, becomes 1</pre><pre>                        there is only 1 node left<br>                        hit base case</pre><pre>                        return 5</pre><pre>Current List:           1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In reverseKGroup(3):    get 5 from reverseKGroup(5)<br>                        <br>                        reverse from 3 to 4</pre><pre>                        let 3 point to 5</pre><pre>                        return 4</pre><pre>Current List:           1-&gt;2-&gt;4-&gt;3-&gt;5-&gt;NULL<br>In reverseKGroup(1):    get 4 from reverseKGroup(3)</pre><pre>                        reverse from 1 to 2<br>                        <br>                        let 1 point to 3<br>                        <strong>return 2</strong></pre><pre>Current List:           2-&gt;1-&gt;4-&gt;3-&gt;5-&gt;NULL<br>In Main Function:       get 2</pre><p><strong>Time Complexity: O(n) </strong>— Same as the iterative solution. It is because that in each function call, we need to first check if there are <em>k</em> nodes left starting from input head, and if there is, we have to reverse them. So two linear scans are still necessary.</p><p><strong>Space Complexity: O(n / k)</strong> — With recursion, we need to take the cost of call stacks into consideration. For every <em>k </em>nodes, we are supposed to recursively call the function for once. So the total number of recursive calls is <em>n / k</em>. Within each function, we are still using a couple of pointers only in this algorithm, so they are constant cost. Thus, the total space complexity is O(<em>n / k</em>)<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d232e4a70a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Tree Upside Down]]></title>
            <link>https://medium.com/@hiimdaosui/binary-tree-upside-down-77af203c79af?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/77af203c79af</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 05:09:54 GMT</pubDate>
            <atom:updated>2018-07-17T06:26:58.723Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.</blockquote><blockquote><strong>Example:</strong></blockquote><pre><strong>Input: </strong>[1,2,3,4,5]</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre><strong>Output:</strong> return the root of the binary tree [4,5,2,#,#,3,1]</pre><pre>   4<br>  / \<br> 5   2<br>    / \<br>   3   1</pre><p>This is a little bit complicated problem at my first glance. But still, let’s break down the big problem and have a list of things to do, then let’s hope this question could be easier.</p><p>The goal is to make the tree upside down. How do we accomplish this more specifically? Note that if a node has left child, its left child will become the new root and the current root’s right child and the current root will become the new root’s left and right children, respectively. So let’s make a list:</p><ol><li>If the current root has left child, make the left child right point to the current root.</li><li>If the current root has left child, make the left child left point to the current root.</li><li>Repeat the operations above until the current root does not have left child.</li></ol><p>But how do we actually implement this idea? Note that in the example above,</p><p>at the very beginning, we will make node 2 left point to 1 and right point to 3, but then the subtrees of node 2 are lost, so its really hard to keep track of those information.</p><p>So let’s try to think a little bit differently. First, if we ignore the existence of right subtrees, what could we get in this scenario? In the example above,</p><pre>    1                   1<br>   / \                 /<br>  2   3    -----&gt;     2 <br> / \                 /<br>4   5               4</pre><p>What does this new tree look like? It’s literally equivalent to a singly linked list, isn’t it? If node 1 is the root of this binary tree, then it is also the head of this list, as well. And we can also consider the left pointer of a node the next pointer in a list node. Hence, we can easily transform this problem into linked list reversal problem, and the only additional issue is to connect correctly for the right subtrees.</p><p>In terms of connecting right subtrees, let’s make some observations. Again, in that example, there are two right subtree connections we need to make. First, we need to left point node 2 to the right subtree of 1, which is node 3. 2-&gt;3. The second one is that we need to point node 4 to node 5, which is the right child of 2. 4-&gt;5. So the only thing we need to do here, is just to left point the new root to the right child on the previous level. Therefore, we can simply save its information in the last round of iteration and use it in the current round.</p><ul><li><strong>Iterative Solution</strong></li></ul><pre>TreeNode* upsideDownBinaryTree(TreeNode* root) {<br>    if (!root || !root-&gt;left) {<br>        return root;<br>    }<br>    <br>    TreeNode* prev = NULL<br>    TreeNode* cur = root; <br>    TreeNode* next = NULL; <br>    TreeNode* lastRight = NULL;<br>    <br>    while (cur) {<br>        next = cur-&gt;left;<br>        <br>        cur-&gt;left = lastRight;<br>        lastRight = cur-&gt;right;<br>        <br>        cur-&gt;right = prev;<br>        <br>        prev = cur;<br>        cur = next;<br>    }<br>    <br>    return prev;<br>}</pre><p>First, we will do the sanity check. Then, we will just simulate the algorithm of singly linked list reversal along the left subtree track. We can do such analogy,</p><pre>╔═══════════╦═══════════════════════╦════════════════════╗<br>║ Variables ║      Binary Tree      ║ Singly Linked List ║<br>╠═══════════╬═══════════════════════╬════════════════════╣<br>║ prev      ║ parent node           ║ previous node      ║<br>║ cur       ║ current node          ║ current node       ║<br>║ next      ║ left child node       ║ next node          ║<br>║ lastRight ║ last right child node ║                    ║<br>╚═══════════╩═══════════════════════╩════════════════════╝</pre><p>Thus, we can summarize the algorithms in a few steps that are easier to understand:</p><ol><li>Store the next root, the left child of the current node.</li><li>Flip. Left point the current node to the right subtree on the last level, and right point the current node to its parent.</li><li>Update the previous, the current and the last right node for next iteration. Note that the current’s right node is supposed to be the last right node in the next round, but we modified it in step 2, so we can store that value in advance or update it between the two flip operations (as it shows in the code).</li></ol><p>Let’s go through the example above:</p><pre>Suppose that we are given a binary tree:<br>    <br>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>Initialization:     prev = NULL, cur = 1, next = NULL, lastRight = NULL</pre><pre>1st Iteration:      store 2 in next<br>                    let 1 left point to NULL (lastRight)<br>                    store 3 in lastRight<br>                    let 1 right point to NULL (prev)<br>                    move prev to 1 (cur)<br>                    move cur to 2 (next)</pre><pre>Binary Tree:            <br>    <br>    1<br>    <br>  2   3<br> / \<br>4   5</pre><pre>Data Structure:     prev = 1, cur = 2, next = 2, lastRight = 3</pre><pre>2nd Iteration:      store 4 in next<br>                    let 2 left point to 3 (lastRight)<br>                    store 5 in lastRight<br>                    let 2 right point to 1 (prev)<br>                    move prev to 2 (cur)<br>                    move cur to 4 (next)</pre><pre>Binary Tree:            <br>    <br>    1<br>   /<br>  2 - 3<br>  <br>4   5</pre><pre>Data Structure:     prev = 2, cur = 4, next = 4, lastRight = 5</pre><pre>2nd Iteration:      store NULL in next<br>                    let 4 left point to 5 (lastRight)<br>                    store NULL in lastRight<br>                    let 4 right point to 2 (prev)<br>                    move prev to 4 (cur)<br>                    move cur to NULL (next)</pre><pre>Binary Tree:            <br>    <br>    1<br>   /<br>  2 - 3<br> / <br>4 - 5</pre><pre>Data Structure:     prev = 4, cur = NULL, next = NULL, lastRight = NULL</pre><pre><strong>return prev = 4</strong></pre><p><strong>Time Complexity: O(n) </strong>— <em>n </em>represents the length of the path stretching from root all the way down to its left children.</p><p><strong>Space Complexity: O(1)</strong> — The only main data structure we use in this implementation are those four pointers, which is definitely constant space complexity.</p><ul><li><strong>Recursive Solution</strong></li></ul><p>We already compared this problem to the simple linked list reversal problem, so it’s also supposed to be viable to be solved by recursion. Recall the linked list problem, we first recursively call the sub-problem and try to get the final head of the reversed result list. And then in current call, we make the current node last one in the list. Similarly, we can definitely use the same strategy. First, we don’t think too much, which means that we can directly call the sub-problem and try to get the eventual new root from those recursive calls. Next, we make the current root as the right child of its left child, and the current root’s right child as the left child of the root’s left child. The wording is a bit confusing, but the logic is almost the same as the list problem.</p><p>Now, let’s analyze the recursive rules:</p><ol><li>Base case: When the input root is empty or it does not have left child.</li><li>Recursive Rule: 1) Retrieve the final new root from recursive calls. 2) Make the current node and its right child be the children of the current node’s left child. More specifically, Left point the left child to the current root’s right child and right point the left child to the current node.</li></ol><pre>TreeNode* upsideDownBinaryTree(TreeNode* root) {<br>    if (!root || !root-&gt;left) {<br>        return root;<br>    }<br>    <br>    TreeNode* newRoot = upsideDownBinaryTree(root-&gt;left);<br>    root-&gt;left-&gt;left = root-&gt;right;<br>    root-&gt;left-&gt;right = root;<br>    root-&gt;left = NULL;<br>    root-&gt;right = NULL;<br>    <br>    return newRoot;<br>}</pre><p>We can also compare this recursive solution to the linked list reversal problem’s one. The base case is that when the input root is empty or it does not have left child, we can directly return the root. Note that the empty case here is also a corner case instead of the base case since if the tree is not empty, we will never reach the case that the recursive call gets a NULL pointer. This is also because we need to return the final new root to the former function calls, so we have to return the last node but not the empty one. If the current root has no left child, it will be the eventual new root after flip, so we return that one.</p><p>For the recursive rule, note that in the linked list problem, we directly go fetch the final result in the subsequent sub-list. Here, we can definitely apply the same strategy to fetch the final result at first, and then complete the task in our current function. Recall that in that list problem, in each function, we set the current node to the last node in the list. Now, in a binary tree, we need to set the current node and its right child to the last level in the tree. And everything is almost the same. We let the left child point to the current root and its right child, and then set the children of the current root to empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a504fe571e6a7bcfe5a3cf03816182b/href">https://medium.com/media/5a504fe571e6a7bcfe5a3cf03816182b/href</a></iframe><p>It’s time to go through the example:</p><pre>Suppose that we are given a binary tree:<br>    <br>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>In Main Function:               call upsideDownBinaryTree(1)</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>In upsideDownBinaryTree(1):     call upsideDownBinaryTree(2)</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>In upsideDownBinaryTree(2):     call upsideDownBinaryTree(4)</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>In upsideDownBinaryTree(4):     hit base case<br>                                return 4</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / \<br>4   5</pre><pre>In upsideDownBinaryTree(2):     let 4 left point to 5<br>                                let 4 right point to 2<br>                                let 2 left point to NULL<br>                                let 2 right point to NULL<br>                                return 4</pre><pre>Binary Tree:</pre><pre>    1<br>   / \<br>  2   3<br> / <br>4 - 5</pre><pre>In upsideDownBinaryTree(1):     let 2 left point to 3<br>                                let 2 right point to 1<br>                                let 1 left point to NULL<br>                                let 1 right point to NULL<br>                                <strong>return 4</strong></pre><pre>Binary Tree:</pre><pre>    1<br>   / <br>  2 - 3<br> / <br>4 - 5</pre><pre>In Main Function:               get 4</pre><p><strong>Time Complexity: O(n) </strong>— The time complexity is the same as the iterative solution since we also need to dive into the deepest node on the most straight left path from root.</p><p><strong>Space Complexity: O(n)</strong> — With recursion we need to consider the usage of call stacks, so in this problem the space complexity is also O(n) since we need n levels of call stacks for the deepest recursion path.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77af203c79af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Linked List II]]></title>
            <link>https://medium.com/@hiimdaosui/reverse-linked-list-ii-976b1d0dfcfa?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/976b1d0dfcfa</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Sun, 15 Jul 2018 05:19:19 GMT</pubDate>
            <atom:updated>2018-07-16T21:08:19.651Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Reverse a linked list from position <em>m</em> to <em>n</em>. Do it in one-pass.</blockquote><blockquote><strong>Note: </strong>1 ≤ <em>m</em> ≤ <em>n</em> ≤ length of list.</blockquote><blockquote><strong>Example:</strong></blockquote><pre><strong>Input:</strong> 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, <em>m</em> = 2, <em>n</em> = 4<br><strong>Output:</strong> 1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;NULL</pre><p>This question is quite similar to the list reverse problem that we’ve done before. This time, our aim is not to reverse the entire list any more. We are given a range represented by two indices and we need to reverse the partial list between that range, inclusively.</p><p>Since the question asks us to do it in one-pass, we will just focus on the iterative solution here.</p><ul><li><strong>Iterative Solution</strong></li></ul><pre>ListNode* reverseBetween(ListNode* head, int m, int n) {<br>    if (!head || !head-&gt;next || !m) {<br>        return head;<br>    }<br>    <br>    ListNode dummy(0), *it = &amp;dummy;<br>    it-&gt;next = head;<br>    <br>    for (int i = 0; i &lt; m - 1; ++i) {<br>        it = it-&gt;next;<br>    }<br>    <br>    ListNode* front = it;            <br>    ListNode* last = it-&gt;next; <br>    <br>    ListNode* prev = NULL, *cur = it-&gt;next, *next = NULL;<br>    for (int i = m; i &lt;= n; ++i) {<br>        next = cur-&gt;next;<br>        cur-&gt;next = prev;<br>        prev = cur;<br>        cur = next;<br>    }<br>    <br>    front-&gt;next = prev;<br>    last-&gt;next = cur;<br>    <br>    return dummy.next;<br>}</pre><p>We will break down this problem into a few steps. First, we need to find the mth node. Then starting from that position, we can apply the normal iterative linked list reversal algorithm until we reach the nth node. Hence, the range between m and n is reversed. Next, we need to splice the reversed list back to its correct position. So we also need to keep track of the side nodes, i.e. the m-1th and the n+1th node.</p><p>We can have a list of steps to make things more clear:</p><ol><li>Find the m-1th and the mth node in the list.</li><li>Begin reversing from themth node till the nth one.</li><li>Connect the old mth node to the n+1th one, and connect the old nth node after m-1th one.</li></ol><p>More specifically, for the first step, note that since m could be 1 so the head of the list may change. Thus, we choose to create a dummy head in the front to create a dummy m-1th node and also make our implementation more succinct. For step two, we could just use the three-pointer strategy to reverse the sub-list in that range. At last, to keep track of the m-1th, themth, thenth and then+1th node, note that when we iteratively reverse the partial list, our prev pointer will stop at the new head which was the nth node, and cur is at the n+1th one. So we could directly make use of them. But for the m-1th and the mth ones, we may lose the track of them once our reversal begins. So before the reversing operation starts, we use two variables to store those two important nodes. In my code, front is the m-1th one, and last is the mth one. And at last, we embed the reversed sub-list into its position between front and cur.</p><p>It’s time for a simple example:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, m = 2, n = 4</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Initialization:     dummy -&gt; 1, it = dummy</pre><pre>1st Step:           move it to 1<br>                    let front store 1    // the m-1th node<br>                    let last store 2     // the mth node</pre><pre>Current List:       dummy-&gt;1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Data Structure:     front = 1, last = 2</pre><pre>2nd Step:           reverse 2-&gt;3-&gt;4</pre><pre>Current List:       dummy-&gt;1, 2&lt;-3&lt;-4, 5-&gt;NULL<br>Data Structure:     prev = 4, cur = 5, next = 5</pre><pre>3rd Step:           let front point to prev<br>                    let last point to cur</pre><pre>Current List:       dummy-&gt;1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;NULL</pre><pre><strong>return dummy -&gt; next = 1</strong></pre><p><strong>Time Complexity: O(n) </strong>— We need to at least iterate the list till the nth node, so for the when case when n is equal to the size of the list, we have to traverse the entire list.</p><p><strong>Space Complexity: O(1)</strong> — We barely use any auxiliary data structures except multiple pointers, so the space complexity is constant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=976b1d0dfcfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swap Nodes in Pairs]]></title>
            <link>https://medium.com/@hiimdaosui/swap-nodes-in-pairs-67b311fd02f7?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b311fd02f7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Sat, 14 Jul 2018 19:57:30 GMT</pubDate>
            <atom:updated>2018-07-16T21:08:52.269Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Given a linked list, swap every two adjacent nodes and return its head.</blockquote><blockquote><strong>Example:</strong></blockquote><blockquote>Given 1-&gt;2-&gt;3-&gt;4, you should return the list as 2-&gt;1-&gt;4-&gt;3.</blockquote><blockquote><strong>Note:</strong></blockquote><blockquote>Your algorithm should use only constant extra space.</blockquote><blockquote>You may <strong>not</strong> modify the values in the list’s nodes, only nodes itself may be changed.</blockquote><p>Like many other linked list problems, we can solve this problem with both iterative and recursive strategies.</p><ul><li><strong>Iterative Solution — Swap Each Pair From Head To Tail</strong></li></ul><pre>ListNode* swapPairs(ListNode* head) {<br>    if (!head || !head-&gt;next) {<br>        return head;<br>    }<br>    <br>    ListNode dummy(0), *it = &amp;dummy;<br>    it-&gt;next = head;<br>    while (it-&gt;next &amp;&amp; it-&gt;next-&gt;next) {<br>        ListNode* post = it-&gt;next-&gt;next-&gt;next;<br>        ListNode* last = it-&gt;next;<br>        <br>        it-&gt;next-&gt;next-&gt;next = it-&gt;next;<br>        it-&gt;next = it-&gt;next-&gt;next;<br>        last-&gt;next = post;<br>        <br>        it = last;<br>    }<br>    <br>    return dummy.next;<br>}</pre><p>For this first iterative solution, our idea is to swap each pair from the head of the list until we reach the end of the list or there is only one element left so we could stop.</p><p>Note that the sanity check is also not necessary here since in our main logic, as soon as the number of nodes left is less than two, we will stop our algorithm and return the result.</p><p>Here, note that after the swaps, the head of our list may change if the size of the input list is larger than one, so we are using a dummy head as a placeholder to splice our result list. In this way, we can begin with the dummy head with a list iterator (pointer) and check if there exist two subsequent list node after the current pointer, where it represents the tail of the former part of the list which is already swapped. If there are two, our job is to swap them and then move to the next pair.</p><p>To accomplish this, note that when we swap the current pair, the second one needs to point to its previous node, so we may lose the track of the subsequent list. That’s why we are using a post pointer to store the head of the following sub-list. The next step is apparently to make swap. We will split this operation into two steps. First, we literally swap those two nodes by pointing the second node in the pair to the first one. Next, we have to splice the new swapped pair into its correct position. To do this, we need to concatenate the new front node in the pair to the tail of the previous swapped list and splice the subsequent list to the new second node in the pair. At last, note that the variable it represents the tail of the swapped part of the list, so we should move it to the new tail. So what is actually the new tail node? The answer is apparently the old first node in the pair, since after the swap operation, it goes to the end. So we could just let it point to that old first node (the new second node) and keep the loop continuing.</p><p>Let’s try a small example:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Initialization:     dummy -&gt; 1, it = dummy</pre><pre>1st Iteration:      There are two nodes after it<br>                    let post store 3<br>                    point 2 to 1<br>                    point it to 2<br>                    point 1 to 3<br>                    move it to 1</pre><pre>Current List:       dummy-&gt;2-&gt;1-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Data Structure:     it = 1</pre><pre>2nd Iteration:      There are two nodes after it<br>                    let next store 5<br>                    point 4 to 3<br>                    point it to 4<br>                    point 3 to 5<br>                    move it to 3</pre><pre>Current List:       dummy-&gt;2-&gt;1-&gt;4-&gt;3-&gt;5-&gt;NULL<br>Data Structure:     it = 3</pre><pre>3rd Iteration:      There is only one node after it<br>                    stop</pre><pre>Current List:       dummy-&gt;2-&gt;1-&gt;4-&gt;3-&gt;5-&gt;NULL<br>Data Structure:     it = 3</pre><pre><strong>return dummy -&gt; next = 2</strong></pre><p><strong>Time Complexity: O(n) </strong>— We need to traverse the entire list once. So the time cost is linear.</p><p><strong>Space Complexity: O(1)</strong> — The only auxiliary memory we have used is to maintain a few local pointers, which should end up with constant space complexity.</p><ul><li><strong>Recursive Solution</strong></li></ul><p>Next, let’s look at the recursion implementation.</p><pre>ListNode* swapPairs(ListNode* head) {<br>    if (!head || !head-&gt;next)<br>        return head;<br>    <br>    ListNode* post = swapPairs(head-&gt;next-&gt;next);<br>    ListNode* res = head-&gt;next;<br>    res-&gt;next = head;<br>    head-&gt;next = post;<br>    <br>    return res;<br>}</pre><p>For this problem, we can also try to divide the big problem into small ones. Note that given the head of a list, what basic operations we are going to do in one iteration? In each iteration, we were attempting to swap the current pair of nodes and then move on to the next ones. Therefore, in the recursive solution, we could also manage to only swap one pair at a time, and connect to the swapped result for the entire subsequent list via recursive calls.</p><p>Now, let’s analyze the recursive rules:</p><ol><li>Base Case: The input linked list is empty or it contains only one single node which is its head.</li><li>Recursive Rule: 1) Swap all pairs in the following sub-list. 2) Swap current pair and splice them correctly with the result retrieved from the subsequent list.</li></ol><p>First, for the base case, we have to cover two scenarios, since as long as the number of nodes in the input list is less than two, we don’t need to swap anymore, so we directly return the head.</p><p>Then, in terms of the recursive calls, we need to skip the current two nodes since we will swap them within current function call. Thus, we will pass the third node as head into the next recursive call and retrieve the swapped result from it. After getting the result from sub-problem, we will just swap the current pair and splice it to the front of that sub-problem result.</p><p>Let’s go through the same example as above:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In Main Function:   call swapList(1)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In swapList(1):     call swapList(3)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In swapList(3):     call swapList(5)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In swapList(5):     hit base case<br>                    return 5</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>In swapList(2):     get 5 from swapList(5)<br>                    let 4 point to 3<br>                    let 3 point to 5<br>                    return 4</pre><pre>Current List:       1-&gt;2-&gt;4-&gt;3-&gt;5-&gt;NULL<br>In swapList(1):     get 4 from swapList(2)<br>                    let 2 point to 1<br>                    let 1 point to 4<br>                    <strong>return 2</strong></pre><pre>Current List:       2-&gt;1-&gt;4-&gt;3-&gt;5-&gt;NULL</pre><pre>In Main Function:   get 2</pre><p><strong>Time Complexity: O(n) </strong>— We have to call a linear times of recursive calls for the entire list, and in each function call, we have a constant time cost for swap operation so the entire time complexity is O(n).</p><p><strong>Space Complexity: O(n)</strong> — Since we need to make a linear times of recursive calls, the call stack usage is O(n). Within each function call, we only need to maintain a finite number of pointers, so in each function the space cost is constant. Thus, the entire space complexity is O(n).</p><p>Since recursion works for this problem, we could definitely use a stack to simulate the process of recursion. We are not going to implement that method, but note that it’s always viable to use a stack to make such simulation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b311fd02f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Linked List]]></title>
            <link>https://medium.com/@hiimdaosui/reverse-linked-list-ca8be5651326?source=rss-ab5adfe347af------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8be5651326</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[hiimdaosui]]></dc:creator>
            <pubDate>Sat, 14 Jul 2018 08:32:14 GMT</pubDate>
            <atom:updated>2018-07-16T21:09:21.757Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Reverse a singly linked list.</blockquote><blockquote>Example:</blockquote><pre>Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL<br>Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;NULL</pre><blockquote>Follow up:</blockquote><blockquote>A linked list can be reversed either iteratively or recursively. Could you implement both?</blockquote><p>This is one of the most basic linked list problem. We are given a singly linked list and our goal is to reverse it and return the head of the new list.</p><p>We are going to use three different approaches to implement this simple algorithm.</p><ul><li><strong>Iterative Solution — Reverse From Head To Tail</strong></li></ul><pre>ListNode* reverseList(ListNode* head) {<br>    if (!head || !head-&gt;next) {<br>        return head;<br>    }<br>    <br>    ListNode* prev = NULL, *cur = head, *next = NULL;<br>    while (cur) {<br>        next = cur-&gt;next;<br>        cur-&gt;next = prev;<br>        prev = cur;<br>        cur = next;<br>    }<br>    <br>    return prev;<br>}</pre><p>First, we will do the sanity check. If the input list is empty or it has only one node, we will directly return itself since the reversed result would be the same. Note that here, if we do not include those sanity check, the code would still work. But it’s just my own habit to do it since sometimes you may overlook the occurrence of some corner cases.</p><p>Next, our idea is to iterate the node from the head to its tail one by one. In each iteration, we will redirect the next pointer of the current node to its previous one, thus the list from its head till the current iteration should be reversed already. Therefore, we naturally need two iterators (pointers) cur and prev in our algorithm to track the current node and its previous one. Moreover, note that for each node, when we redirect its next pointers to its previous one, the old next pointer is lost, so we lose the track of the subsequent list. Hence, before the redirection, we need to store the head of the following list, and that’s why we need to use the third pointer nexthere.</p><p>The loop ends when our main iterator cur reaches the end of the list, meaning that all nodes have their next pointers redirected to the previous nodes. And at this moment, the prev pointer points to the last node, which is supposed to be the head of the reversed list. Therefore, prev is the final return value in this implementation.</p><p>Now, it’s time for an simple example:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;NULL</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>Initialization:     prev -&gt; NULL, cur -&gt; 1, next -&gt; NULL</pre><pre>1st Iteration:      let next store 2<br>                    point 1 to NULL <br>                    move prev to 1<br>                    move cur to 2</pre><pre>Current List:       NULL&lt;-1-&gt;2-&gt;3-&gt;NULL<br>Data Structure:     prev -&gt; 1, cur -&gt; 2, next -&gt; 2</pre><pre>2nd Iteration:      let next store 3<br>                    point 2 to 1 <br>                    move prev to 2<br>                    move cur to 3</pre><pre>Current List:       NULL&lt;-1&lt;-2-&gt;3-&gt;NULL<br>Data Structure:     prev -&gt; 2, cur -&gt; 3, next -&gt; 3</pre><pre>3rd Iteration:      let next store NULL<br>                    point 3 to 2<br>                    move prev to 3<br>                    move cur to NULL</pre><pre>Current List:       NULL&lt;-1&lt;-2&lt;-3<br>Data Structure:     prev -&gt; 3, cur -&gt; NULL, next -&gt; NULL</pre><pre><strong>return prev = 3</strong></pre><p><strong>Time Complexity: O(n) </strong>— We simply iterate through the entire list once, so the time cost is apparently linear.</p><p><strong>Space Complexity: O(1)</strong> — The only main data structure we use in this implementation are three pointers, which is apparently constant space cost.</p><ul><li><strong>Recursive Solution</strong></li></ul><pre>ListNode* reverseList(ListNode* head) {<br>    if (!head || !head-&gt;next) {<br>        return head;<br>    }<br>    <br>    ListNode* res = reverseList(head-&gt;next);<br>    <br>    head-&gt;next-&gt;next = head;<br>    head-&gt;next = NULL;<br>    <br>    return res;<br>}</pre><p>In the first solution, the algorithm is quite intuitive, we iterate the list from its head to its tail, redirect the next pointer for each of them and then go to the next one in the following sub-list. However, compared to this head-to-tail method, could we solve this problem in the opposite way? Now, the only obstacle seems to be that if we are given a list node, we cannot obtain its previous node in a quick fashion since the input is a singly linked list. Imagine that if our data structure is an array or any type that supports random access, then reversing that data structure would be very trivial. Thus, in this scenario, a very powerful tool for us to use is recursion, since we can simply divide this big problem into multiple smaller sub-problems and make use of the results of those smaller problems.</p><p>Imagine that given the head of a linked list, what we could do immediately is to check if the head has a next node. If it does, we can directly make its next node point to the head. Note that what if everything in the subsequent list has already been reversed, and once we reverse the next node of the head, the algorithm is done. Thus, to get a reversed subsequent linked list becomes our new problem, which is in a smaller scale. How could we get a reversed subsequent list? Our reverse function could definitely do the work again, and this is where recursion and call stack could help us retrieve the result of sub-problems.</p><p>Now, let’s analyze the recursive rules:</p><ol><li>Base Case: The input linked list contains only one single node which is its head.</li><li>Recursive Rule: 1) Reverse all nodes after the input head. 2) Make the head last node in the list.</li></ol><p>First, in terms of the base case, in our code, we actually handle two different types of cases. One is the input head is NULL, the other one is head does not have a following node, which means there is only one node in the list so we could directly return it. Note that they are not both base cases. Suppose that we are given a non-empty list, what should be the result head after the entire list is reversed? The answer is apparently the last node in the current list. Hence, as long as the input list is not empty, our algorithm will hit base case when there is exactly one node left in the list, and will straightly return that node to the previous function call to indicate the result head. We will discuss about that later again, but now, just note that in our implementation, only !head-&gt;next represents the base case, since if the input list is not empty, we will never hit the case that head is NULL in the recursion call. On the other hand, !head could be considered a corner case to our problem, which means that the input list is just an empty one, and we will not go through any complicated logic and return NULL directly.</p><p>Next, for the recursive rule, from our previous discussion, we know that at current level, we can reverse the next node of the current head, and if we could get the reversed result of all nodes after the current one, then the problem is solved. Hence, in our implementation, after the sanity check and the base case check, we immediately recursively call the same function with the next node as parameter. By doing this, we can retrieve the head of the reversed result of the subsequent list. So the first part of the recursive rule is done. Then, we need to set the current head to be the last node in the list. To accomplish that, note that in the list returned from the recursive function, its last node is just head-&gt;next since it is the parameter we passed into the recursive call. Thus, we only need to concatenate the current head after its next, that’s why we have head-&gt;next-&gt;next = head. And at last, remember that the last node in a list has to point to NULL to show its the end of the list. Actually, that line of code is only necessary for the first node in our list since the pointers of the following nodes will be overwritten in their previous functions calls, but since the first node needs it to make it the end, we have to add that line of code.</p><p>Let’s go through the same example as the first solution:</p><pre>Suppose that we have an input list:</pre><pre>1-&gt;2-&gt;3-&gt;NULL</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>In Main Function:   call reverse(1)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>In reverse(1):      call reverse(2)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>In reverse(2):      call reverse(3)</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>In reverse(3):      hit base case<br>                    return 3</pre><pre>Current List:       1-&gt;2-&gt;3-&gt;NULL<br>In reverse(2):      get 3 from reverse(3)<br>                    let 3 point to 2<br>                    let 2 point to NULL<br>                    return 3</pre><pre>Current List:         NULL<br>                       ^<br>                       |      <br>                    1-&gt;2&lt;-3 <br>In reverse(1):      get 3 from reverse(2)<br>                    let 2 point to 1<br>                    let 1 point to NULL<br>                    <strong>return 3</strong></pre><pre>Current List:       NULL&lt;-1&lt;-2&lt;-3</pre><pre>In Main Function:   get 3</pre><p><strong>Time Complexity: O(n) </strong>— We have to make a linear times of recursive calls for each node in the list. So the time cost is definitely O(n).</p><p><strong>Space Complexity: O(n)</strong> — We barely need to maintain any data structure in this implementation, but note that for each node visit, we have to make a recursive call, which the operating system will allocate a call stack for each of those functions to reach the base case. So the space complexity is also linear with respect to the size of the list.</p><ul><li><strong>Iterative Solution — Simulate recursion with stack</strong></li></ul><p>Note that recursive calls are quite similar to the LIFO behavior of stacks, the function called last will return first. That’s why the memory section to maintain those function calls is named call stack. Thus, for almost every recursion implementation, we could always switch it to a iterative solution with a use of stacks.</p><p>For this problem specifically, we could just use a stack to store all the list nodes in a reverse order, then pop them in turns and concatenate them in the reverse order.</p><pre>ListNode* reverseList(ListNode* head) {<br>    if (!head || !head-&gt;next) {<br>        return head;<br>    }<br>    <br>    ListNode dummy(0), *it = &amp;dummy;<br>    stack&lt;ListNode*&gt; s;<br>    while (head) {<br>        s.push(head);<br>        head = head-&gt;next;<br>    }<br>    <br>    while (!s.empty()) {<br>        it-&gt;next = s.top();<br>        s.pop();<br>        it = it-&gt;next;<br>    }<br>    it-&gt;next = NULL;<br>    <br>    return dummy.next;<br>}</pre><p><strong>Time Complexity: O(n) </strong>— Every node has to be pushed into the stack once and popped from the stack once, so the time complexity is linear.</p><p><strong>Space Complexity: O(n)</strong> — We need to push the entire list into an additional stack. So the space complexity is also linear.</p><p>Note that in the last two solutions, the pivot is to find a mapping from a node to its previous node so that we can reconnect them. Therefore, we can also use a hashmap unordered_map&lt;ListNode*, ListNode*&gt; to keep the relationship between a node and its previous one. We are not coding that solution here, but it’s definitely another viable choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8be5651326" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>