<?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[Tech Life &amp; Fun - Medium]]></title>
        <description><![CDATA[Sharing computer technology related news, thoughts, experience and certainly funs! - Medium]]></description>
        <link>https://medium.com/tech-life-fun?source=rss----b45a68ec22db---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Tech Life &amp;amp; Fun - Medium</title>
            <link>https://medium.com/tech-life-fun?source=rss----b45a68ec22db---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 09:20:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tech-life-fun" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Video Publishment Automation]]></title>
            <link>https://medium.com/tech-life-fun/video-publishment-automation-935d5120dc9b?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/935d5120dc9b</guid>
            <category><![CDATA[youtube-automation]]></category>
            <category><![CDATA[youtube-publishment]]></category>
            <category><![CDATA[video-publishers]]></category>
            <category><![CDATA[video-publishing]]></category>
            <category><![CDATA[wechat-video-publishment]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 23:54:55 GMT</pubDate>
            <atom:updated>2023-01-04T05:27:40.325Z</atom:updated>
            <content:encoded><![CDATA[<p>From iPad to Youtube, WeChat and more with one click ONLY!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pl6du74dNfg1cp7v" /><figcaption>Photo by <a href="https://unsplash.com/@gabrielbenois?utm_source=medium&amp;utm_medium=referral">Gabriel Benois</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>From time to time, my daughter reads short kid’s English books with an iPad and publishes the videos through Apps. The reading is pleasant but the publishment is tedious. Various Apps (Youtube and others) need to be installed on the iPad and manual work and waitings are needed for publishment. In addition, archiving those videos (for memory and for uploading to any future platform) also becomes an issue since the iPad has 32GB storage only.</p><h3>Solution Disassembly</h3><p>Step by step, I’m going to build a solution to tackle all problems mentioned in above.</p><p>1, upload iPad video to NAS server</p><p>Here iPad can be any iOS devices like an iPhone as long as <a href="https://support.apple.com/guide/shortcuts/welcome/ios">shortcut</a> is available. Also a NAS server can be any Linux server that is accessible regardless its location (but ideally a home server considering network speed and stable accessibility).</p><p>Detailed Steps in :</p><p><a href="https://medium.com/@edward.zhou/upload-ipad-video-to-nas-server-8040e93c72ce">Upload iPad Video to NAS server</a></p><p>2, processing the video.</p><p>2.1 transform the video format (default is Apple’s MOV) to MP4: needed?</p><p>2.2 use AI tools to determine the video’s title / tags</p><p>2.3 add an opening and water mark to the video</p><p>Detailed Steps in : &lt;Article Link to be posted&gt;</p><p>3, publishment</p><p>Publish the video to different platforms. Per configuration, publishment is scheduled in a way that any channel of any platform will release a video at a given time.</p><p>Detailed Steps in : &lt;Article Link to be posted&gt;</p><h3>Channels in case you are interested</h3><p>Kid’s Book Reading in English:</p><p><a href="https://www.youtube.com/channel/UC-bKYyvCA6ocNZKql1uAJPg">https://www.youtube.com/channel/UC-bKYyvCA6ocNZKql1uAJPg</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935d5120dc9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/video-publishment-automation-935d5120dc9b">Video Publishment Automation</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 1551. Minimum Operations to Make Array Equal— Graphically Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leetcode-1551-minimum-operations-to-make-array-equal-graphically-explained-python3-solution-99a6f71bbeec?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/99a6f71bbeec</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 20:49:32 GMT</pubDate>
            <atom:updated>2021-04-06T20:49:32.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x6GZ8zL-HJF6AB1N" /><figcaption>Photo by <a href="https://unsplash.com/@cdc?utm_source=medium&amp;utm_medium=referral">CDC</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 &lt;= i &lt; n).</p><p>In one operation, you can select two indices x and y where 0 &lt;= x, y &lt; n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array <strong>equal</strong>. It is <strong>guaranteed</strong> that all the elements of the array can be made equal using some operations.</p><p>Given an integer n, the length of the array. Return <em>the minimum number of operations</em> needed to make all the elements of arr equal.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> n = 4<br><strong>Output:</strong> 4<br><strong>Explanation:</strong> arr = [1, 3, 5, 7]<br>First 3 operations choose x = 3 and y = 0, this leads arr to be [4, 3, 5, 4]<br>Now take 1 operation choose x = 2 and y = 1, thus arr = [4, 4, 4, 4].</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> n = 7<br><strong>Output:</strong> 12</pre><h3>Solution</h3><p>BTW, don’t be frightened by the word “minimum” :)</p><p>To start with, just use a simple example like [1,3,5] (where n=3).</p><p>As the below picture shows, when n=3, the quickest way to make all elements equal is to</p><ol><li>increase array[0] by 1 and decrease array[2] by 1</li><li>repeat #1</li></ol><p>So the minimum operation is 2. This is not strict prove and the philosophy behind is to make all values increase/decrease towards the median value since, in each operation, I will have one value increase by 1 and the other decrease by 1, it will be natural to do that against mirrored elements in each end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qE63DNcsaFe5YR_eCYfrAw.png" /></figure><p>Now, look at other examples shown above like n=4 and 6. Mirrored elements will be taken by operations in X times where X=1,3,5,…, n/2 if n % 2 == 0. For n % 2 ==1, X will be 2,4,6,…,n-1.</p><p>OK, so the number of operations is the sum of an array</p><blockquote>1,3,5,…, n/2 if n % 2 == 0</blockquote><blockquote>2,4,6,…,n-1 if n % 2 == 1</blockquote><p>This is basically a math question now. The sum of an array like below is (start + end) * size_of_array / 2 = (start + start + size_of_array * 2–2) * size_of_array / 2 = (start + size_of_array -1) * size_of_array</p><blockquote><em>start, start +2, start +4, …, end</em></blockquote><p>Translating above illustration will lead to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12ec0ded8ca8535550f18ff8bc23ec5/href">https://medium.com/media/f12ec0ded8ca8535550f18ff8bc23ec5/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>Since I just put n in a formula to calculate the end result, the time complexity is O(1) meaning no matter how n gets change (for example, from 10 to 100 or to 1000000), the run time will not grow along with it.</p><p>Space complexity will be O(1) as well since no extra space(like an auxiliary array) is used.</p><h3>Extended Reading</h3><p>Python3 cheatsheet:</p><p><a href="https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549">https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a6f71bbeec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leetcode-1551-minimum-operations-to-make-array-equal-graphically-explained-python3-solution-99a6f71bbeec">Leetcode 1551. Minimum Operations to Make Array Equal— Graphically Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 623. Add One Row to Tree — Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leetcode-623-add-one-row-to-tree-explained-python3-solution-8ef2420d27b0?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ef2420d27b0</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[tree-traversal]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 22:52:27 GMT</pubDate>
            <atom:updated>2021-03-09T22:52:27.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 623. Add One Row to Tree — Explained Python3 Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MX5DTMx8VD7ormrw" /><figcaption>Photo by <a href="https://unsplash.com/@trevmepix?utm_source=medium&amp;utm_medium=referral">trevor pye</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>Given the root of a binary tree, then the value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.</p><p>The adding rule is: given a positive integer depth d, for each NOT null tree nodes N of depth d-1, create two tree nodes with value v as N&#39;s left subtree root and right subtree root. And N&#39;s <strong>original left subtree</strong> should be the left subtree of the new left subtree root, its <strong>original right subtree</strong> should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value <strong>v</strong> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> <br>A binary tree as following:<br>       4<br>     /   \<br>    2     6<br>   / \   / <br>  3   1 5   </pre><pre><strong>v = 1</strong></pre><pre><strong>d = 2</strong></pre><pre><strong>Output:</strong> <br>       4<br>      / \<br>     1   1<br>    /     \<br>   2       6<br>  / \     / <br> 3   1   5</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> <br>A binary tree as following:<br>       4<br>     /   \<br>    2     6<br>   / \   / <br>  3   1 5</pre><pre><strong>v = 1</strong></pre><pre><strong>d = 1</strong></pre><pre><strong>Output:</strong> </pre><pre>         1<br>        /<br>       4<br>     /   \<br>    2     6<br>   / \   / <br>  3   1 5</pre><h3>Solution</h3><p>The key to this problem is that I need to:</p><p>1, know what’s the current depth for a node I visit now.</p><p>2, when current depth == d-1, I need to create 2 new children nodes and ask the left child’s left pointing to the current node’s left and the right child’s right pointing to the current node&#39;s right.</p><p>One corner case is what if d ==1. The problem description mentions that during an interview one may be expected to ask in the first place. So it may be a good practice to not look at the examples after reading the problem description; instead, think about the possible examples (to cover as many as possible scenarios) and then read further on provided examples to compare and reflect.</p><p>With the above explanation, hopefully below 2 solutions make more sense.</p><h4>Recursive (DFS) Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8722f158c15ba50ec01b777e99c024c9/href">https://medium.com/media/8722f158c15ba50ec01b777e99c024c9/href</a></iframe><h4>Non-recursive(BFS) Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80f14b3ad56fc35464998e8b080bc08/href">https://medium.com/media/f80f14b3ad56fc35464998e8b080bc08/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>For both above solutions, assuming if there are N nodes, in general, the nodes I need to visit are directly related to N. Therefore the time complexity is also O(N).</p><p>When it comes to space complexity:</p><ol><li>The recursive solution requires O(1) space <strong>if</strong> the function calling stack is not calculated; otherwise, it’s O(N) since the more nodes you have, on average, the deeper you need to go.</li><li>The non-recursive solution needs to store one layer of nodes so it is O(x) where x is the maximum possible nodes in a layer of the tree.</li></ol><h3>Extended Reading</h3><p>Python3 cheatsheet:</p><ul><li><a href="https://medium.com/tech-life-fun/python3-cheatsheet-continuously-updated-66d652115549">Python3 Cheatsheet (continuously updated)</a></li><li><a href="https://medium.com/tech-life-fun/algorithm-cheatsheet-continuously-updated-a95ef9b530b">Algorithm Cheatsheet (continuously updated)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef2420d27b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leetcode-623-add-one-row-to-tree-explained-python3-solution-8ef2420d27b0">LeetCode 623. Add One Row to Tree — Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leetcode-23-merge-k-sorted-lists-graphically-explained-python3-solution-d0e77419956c?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0e77419956c</guid>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[merge-list]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sun, 24 Jan 2021 20:56:10 GMT</pubDate>
            <atom:updated>2021-01-24T21:00:06.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2AOX3cB-pcxDcTAs" /><figcaption>Photo by <a href="https://unsplash.com/@clayton_cardinalli?utm_source=medium&amp;utm_medium=referral">Clayton Cardinalli</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.</p><p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p><p><strong>Example:</strong></p><pre><strong>Input:</strong> lists = [[1,1,5],[1,3,4],[2,6]]<br><strong>Output:</strong> [1,1,1,2,3,4,5,6]<br><strong>Explanation:</strong> The linked-lists are:<br>[<br>  1-&gt;1-&gt;5,<br>  1-&gt;3-&gt;4,<br>  2-&gt;6<br>]<br>merging them into one sorted list:<br>1-&gt;1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6</pre><h3>Solution</h3><h4>Obvious Solution</h4><p>The obvious (and brute force) way is to navigate ALL list items, save them into an array and then sort. The time complexity is: O(kN + kNLog(kN)) since for for total k Lists (each one with average N elements), I need to visit them all and the quick sort on final array takes kNLog(kN). The space complexity is O(kN) as all values will be saved.</p><h4>Best Solution (to me)</h4><p>Since each list is already sorted, I can definitely leverage that. To start with, let me use this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*ZRv8WVq2QqNDUMlvzhf4GQ.png" /></figure><p>To show it more clearer, let me put some twists (showing only the leftmost element of each list):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*tF4hiBoR6BA4uA7mSo0Hbg.png" /></figure><p>You can see from above, for all current leftmost elements, “1” (doesn’t matter which “1”, so I just pick the one in the first list) is the smallest element. Although I haven’t looked into all other elements, I’m pretty sure it’s the smallest element of ALL elements. Why? The reason is, within current smallest elemements (of all lists), it’s the smallest: smallest among the smallest :).</p><p>So “1” will be picked up as current smallest element and its next element (if any) will become current like below right part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*cFU4yjO1hdyTap5bgVwJeQ.png" /></figure><p>Then I can repeat the process until all elements are visited.</p><h4>Additional Tips:</h4><p>There are 2 additional tips (which I use in the source code):</p><ol><li>Dummy head of linked list</li></ol><p>Detailed illustration can be found within below <strong>Cheatsheet </strong>article (search “dummy” in it). I recommend reading it before checking following source code.</p><p><a href="https://medium.com/tech-life-fun/python3-cheatsheet-continuously-updated-66d652115549">Python3 Cheatsheet (continuously updated)</a></p><p>2. Heapq (priority queue)</p><p>Detailed illustration of heapq can be found in above <strong>Cheatsheet</strong> article (search “heapq” in it). I recommend reading it before continue reading.</p><p>The heapq is used in source code to achieve O(1) complexity to get smallest element out of a bunch elements. A detail to know for Python3 heaqp is: when I heappush a tuple, by default, tuple[0] will be used to compare with existing tuples’ tuple[0], if there is equal pair, tuple[1] will be used.</p><p>So below code may report “<strong>TypeError: ‘&lt;’ not supported between instances of ‘ListNode’ and ‘ListNode&#39;</strong>”, since (1,n1)[0] == (1,n2)[0] and Python3 will compare n1 and n2 but “&lt;” operator may not be implemented in ListNode class.</p><pre>import heapq<br>h = []<br>n1 = ListNode(1)<br>n2 = ListNode(1)<br>heapq.heappush(h, (1, n1))<br>heapq.heappush(h, (1, n2)) #TypeError: &#39;&lt;&#39; not supported ...</pre><p>To avoid that, I add a unique counter to the tuple like:</p><pre>import heapq<br>h = []<br>n1 = ListNode(1)<br>n2 = ListNode(1)<br>cnt = 0<br>heapq.heappush(h, (1, cnt, n1))<br>cnt +=1<br>heapq.heappush(h, (1, cnt, n2)) </pre><h4>Time &amp; Space Complexity</h4><p>Per above illustration and techniques, all elements will be visited once only and for each element, there will be a Heapq push ( O(LogN) where N is the size of heap) and pop (O(1)). Assuming there are k lists and each one has N elements on average, the total elements are kN, and each element will be processed in heapq by O(Logk), the final time complexity is O(kN Logk).</p><p>Since I use a heap size of k, the space complexity is O(k).</p><h4>Source Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8690504f70c4ba6cef80cff696cf3ab1/href">https://medium.com/media/8690504f70c4ba6cef80cff696cf3ab1/href</a></iframe><p>Thanks for reading and if you feel this article is helpful, <strong>please clap for it and follow me in Medium</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e77419956c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leetcode-23-merge-k-sorted-lists-graphically-explained-python3-solution-d0e77419956c">LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leet Code 82. Remove Duplicates from Sorted List II — Graphically Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leet-code-82-remove-duplicates-from-sorted-list-ii-graphically-explained-python3-solution-ba7672f12ca?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba7672f12ca</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 04:02:56 GMT</pubDate>
            <atom:updated>2021-01-06T04:02:56.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leet Code 82. Remove Duplicates from Sorted List II — Graphically Explained Python3 Solution</h3><p><em>Reaching Medium article limit? You can also read my aticle at </em><a href="https://myleetcodejourney.blogspot.com/"><em>https://myleetcodejourney.blogspot.com/</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fiXvBWzGnFa4j8a1" /><figcaption>Photo by <a href="https://unsplash.com/@nelly13?utm_source=medium&amp;utm_medium=referral">Nelly Antoniadou</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>Given the head of a sorted linked list, <em>delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list</em>. Return <em>the linked list </em><strong><em>sorted</em></strong><em> as well</em>.</p><p><strong>Example 1:</strong></p><p>Input: 1-&gt;1-&gt;2-&gt;2</p><p>Output: &lt;empty&gt;</p><p><strong>Example 2:</strong></p><p>Input: 1-&gt;2-&gt;2-&gt;3</p><p>Output: 1-&gt;3</p><h3>Solution</h3><p>The most fun (or puzzling) part of this problem is: when you come to a node that is different in value with its previous one, you don’t know whether it’s a duplicate one until you go to its next node.</p><p>To me, there is a <strong>pattern </strong>here: during an iteration, I cannot make a decision on current element before I get to following elments. Normally I can use <strong>stack </strong>for this pattern. The key is: somehow I store elements in stack (so that I can retrieve them in a reversed or original order) for now and fetch them later basing on situations.</p><p>So assume I have an input linked list like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*28v23wLhPBBTjlw8A5E13Q.png" /></figure><h4>Step by step walk-through</h4><ol><li>When I iterate the list using a pointer (p) and first I see “1” in the beginning. Since I don’t know whether there will be more ‘1’ along the road (yet), I will just put it in the stack.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*X5xwNMJsjWWtLv0X5JqK_w.png" /></figure><p>2. Now I move p to the second node and I see another “1”. This time I actually know “1” is duplicate but in case there are more “1” following, I will just throw it into the stack as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*gmfbV8OvQQoz_w_wsf0j5w.png" /></figure><p>3. Here p points to the third node “2”, since it’s not equal to the top item of the stack (which is “1” as shown in previous step) and this is an ascending linked list, I know a duplication list of “1” ends so I will just clear the stack. And for current node “2”, again I don’t know whether it’s duplicate so I have to push it to the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*FCWi1hjPO8ZzgDbZXFH4Kw.png" /></figure><p>4. Like #2, I add the last node to the stack and move p to its next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*qsoEADfu_66ErtMBYVMC3g.png" /></figure><p>5. Finally I reach the end of input linked list and since the stack contains more than 2 elements (and for sure they have duplicate values), I will discard them as well. In the end, I will return an empty list (None in Python).</p><h4>Another tip: a dummy header</h4><p>In above example, there is actually nothing left in the result. Consider another example 1-&gt;2-&gt;2-&gt;3, similiarly, when I visit the second node which has a different value than stack[-1] and len(stack) == 1, it means the one in the stack is a <strong>unique</strong> one, I need to put it in final result link. A little tedious handling is: normally I need to see if this unique one is the first unique one and write separate codes to tackle yes/no situations like:</p><pre>if len(stack)==1 and stack[-1].val != p.val:<br>  if resultHeader == None:<br>    resultHeader = stack.pop()<br>    preNode = resultHeader<br>  else:<br>    preNode.next = stack.pop()<br>    preNode = preNode.next<br>....<br>#finally return resultHeader<br>return resultHeader</pre><p>It would be beautiful if I can use the same set of codes for both situations! And actually there is a way like:</p><pre>resultHeader = ListNode() #this is a dummy header<br>preNode = resultHeader</pre><pre>if len(stack)==1 and stack[-1].val != p.val:<br>  preNode.next = stack.pop()<br>  preNode = preNode.next<br>....</pre><pre>#finally return resultHeader.next<br>return <strong>resultHeader.next</strong></pre><h4>Source Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d8c9a3040c7ee0eb63ecd1d6174a2d1/href">https://medium.com/media/2d8c9a3040c7ee0eb63ecd1d6174a2d1/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>All nodes will be visited once so time complexity is O(N). Stack may contain all nodes in worst case (for example, all elements are distinct) and in that case, space complexity will be O(N).</p><h3>Extended Reading</h3><p>Python3 cheatsheet:</p><p><a href="https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549">https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7672f12ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leet-code-82-remove-duplicates-from-sorted-list-ii-graphically-explained-python3-solution-ba7672f12ca">Leet Code 82. Remove Duplicates from Sorted List II — Graphically Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leet-code-84-largest-rectangle-in-histogram-graphically-explained-python3-solution-df7e0d37ae4d?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/df7e0d37ae4d</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 03:41:49 GMT</pubDate>
            <atom:updated>2021-01-11T06:10:09.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Al0HL-q5tP535vvs" /><figcaption>Photo by <a href="https://unsplash.com/@pabels?utm_source=medium&amp;utm_medium=referral">Pablo Hermoso</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>Given <em>n</em> non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*v8I_ihXb8BuYTPaY.png" /></figure><p>Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*7Lj_p_VWVjh1HdTO.png" /></figure><p>The largest rectangle is shown in the shaded area, which has area = 10 unit.</p><p><strong>Example:</strong></p><pre><strong>Input:</strong> [2,1,5,6,2,3]<br><strong>Output:</strong> 10</pre><h3>Solution</h3><h4>Obvious Solution</h4><p>The obvious (and brute force) way is to use 2 pointers: left and right. Let left points to index 0 ~ N-1 and then right to left and N-1. For each left and right pair, I can calculate the area[left, right] using (right-left+1) * min(heights[left], heights[left+1],heights[left+2],…,heights[right]). Its time complexity is at least be O(N²).</p><h4>Best Solution (to me)</h4><p><strong>[Credit]</strong> This is described by @<a href="https://leetcode.com/TravellingSalesman">TravellingSalesman</a> in disucssion area (<a href="https://leetcode.com/problems/largest-rectangle-in-histogram/solution/">https://leetcode.com/problems/largest-rectangle-in-histogram/solution/</a>) and here I just try to illustrate it further.</p><p>Take the example of heights array [2,1,5,6,2,3], each area must be in the height of any element within heights. In other words, the maximum area will either be an area with height=2, or an area with height=1, or an area with height=5 and etc. So instead of using 2 pointers like mentioned in above section, here I can use height central perspective: if I want to use heights[2] (=5) as the height of a candidate area, how to get its width? Not surprisingly, I need to look to its left to find the first (leftmost) height (its index referenced as <strong>L</strong> in following) that is smaller than 5 and rightmost height (its indexreferenced as <strong>R</strong> in following) that is smaller than 5: yellow arrows in below graph (Pic 1) illustrate the boundaries. With that the width=(R-L)-1=4–1–1=2 and hence the area = width * height = 2 * 5 = 10 (as shown in yellow rectangle).</p><p>What if a height is the samllest one so there is no valid L, R? For example, for heights[1]=1, obviously the area of heights[1]=1 will has the width=6 (the length of the heights array). Logically, I can assume L = -1 while R=size-of-heights. Similar logic applies to an element that seems has only a valid L or R: for example, red rectangle indicates an area with the heights[5] and it’s L=4 and R=6 so its width=R-L-1=6–4–1=1 and its area = 1 * 3=3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*xuoVIlHs5USIYrShpm8oQw.png" /><figcaption><strong>Pic 1</strong></figcaption></figure><p>There is a smat way to implement above algorithm: using a stack that stores ascending elements. When I iterate the array, if the top of the stack (as referenced as stack[-1] in Python) is larger than current element, for<strong> the one on the top of the stack</strong>, we actually find its R; its L is actually the second to the top: with this, I can conclude the area with the height corresponding to the top of the stack; if the top of the stack (as referenced as stack[-1] in Python) is smaller or equal than current element, that means I still don’t know what’s the R for current top element in the stack, so I will just push current element to the stack.</p><p>Sounds dizzy? Let me walk through the algorithm with the example [2,1,5,6,2,3]. To simplify writing, I use Area[i] to denote the area whose height is height[i].</p><p>0, first I run into index=0 (height=2). It’s the first one and I know its L = -1 but am not sure the value of R, so I just put its index (so that later I can get its index for width calculation and in the same time get its value for height through heights[index]) in the stack. Now stack=[0].</p><p>1, now I come to index=1(height=1). It’s less than current top of stack’s value since heights[1] &lt; heights[stack[-1]]. So I find heights[stack[-1]] (aka heights[0])’s R= current index. So for the area of heights[0] (illustrated by green vertical lines in Pic 1) is (R-L-1) * heights[0] = (1-(-1)-1)*2=2. <strong>So I have Area[0] calculated. </strong>I will pop up index 0 from stack since its area is calcuated; but for index 1, its corresponding area is not yet calculated (I don’t know its R although its L is -1), so I push it to stack and now stack=[1].</p><p>2, now I come to index=2(height=5). Since heights[2] &gt; heights[stack[-1]], for stack[-1], I cannot decide its R, just push current index to stack and makes stack=[1,2].</p><p>3, now I come to index=3(height=6). Same as #2 and now stack=[1,2,3].</p><p>4,now I come to index=4(height=2). Now heights[4] &lt;heights[stack[-1]], it means for index stack[-1] (aka index 3), I find its R and therefore <strong>Area[3]= (R-L-1)*heights[3]=(4-heights[stack[-2])*heights[3]=(4–2–1)*6=6</strong>. Now I pop up the top of the stack and the stack=[1,2]. Notice stack[-1]=2 and heights[2] &gt;heights[4], it indicates heights[2]’s R=4 as well. So similarly I can have <strong>Area[2]= (R-L-1)*heights[2]=(4-heights[stack[-2])*heights[3]=(4–1–1)*5=10 </strong>and pop up the stack to get stack=[1]. Now stack[-1]=1 and heights[1] &lt; heights[4] so heights[1]’s R is not yet decided and hence it stays at the stack. Now stack=[1,4].</p><p>5,now I come to index=5(height=3) and similar to #3 now stack=[1,4,5].</p><p>6, now I go beyond the array. Remember there is a default R=size-of-array=6? So for everyone remaining in the stack, its R is the index after it (except for the last one, it’s 6) and its L is the index before it(except for the first one, it’s -1). Bear in mind that heights array is [2,1,5,6,2,3] and I will have</p><p><strong>Area[5]= (6–4–1) * height[5] = 3</strong></p><p><strong>Area[4]=(6–1–1) * height[4] = 8</strong></p><p><strong>Area[1]=(6-(-1)-1)* height[1] = 6</strong></p><p>7, looking at Area[x] where x in 0~5, the largest one will be the answer.</p><h3>Source Code</h3><p>Slightly different from above walk-through, I add a “-1” to the stack in the beginning (serving as default <strong>L</strong>). In the end, an extra checking (corresponding to #6 in above) is performed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c62181ef9b521d69baa3828644c2b5/href">https://medium.com/media/22c62181ef9b521d69baa3828644c2b5/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>As illustrated above, I only need to travse the heights array once and when visiting an element, although there is a need to do while loop against the stack, each element will just be inside the stack for once. Therefore, the time complexity is O(N) and so is space complexity.</p><h3>Extended Reading</h3><p>Python3 cheatsheet:</p><p><a href="https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549">https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df7e0d37ae4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leet-code-84-largest-rectangle-in-histogram-graphically-explained-python3-solution-df7e0d37ae4d">Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leet Code 91. Decode Ways — Graphical Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leet-code-91-decode-ways-graphical-explained-python3-solution-60d97a0852c8?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/60d97a0852c8</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[decode-ways]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 22:56:05 GMT</pubDate>
            <atom:updated>2020-12-27T23:11:42.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leet Code 91. Decode Ways — Graphically Explained Python3 Solution</h3><p>Reaching Medium article limit? You can also read my aticle at <a href="https://myleetcodejourney.blogspot.com/">https://myleetcodejourney.blogspot.com/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HxhkyiLst3VmhcCr" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>A message containing letters from A-Z is being encoded to numbers using the following mapping:</p><pre>&#39;A&#39; -&gt; 1<br>&#39;B&#39; -&gt; 2<br>...<br>&#39;Z&#39; -&gt; 26</pre><p>Given a <strong>non-empty</strong> string containing only digits, determine the total number of ways to decode it. The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> s = &quot;12203&quot;<br><strong>Output:</strong> 2<br><strong>Explanation:</strong> It could be decoded as &quot;ABTC&quot; (1,2,20,3) or &quot;LTC&quot; (12,20,3).</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> s = &quot;20103&quot;<br><strong>Output:</strong> 1<br><strong>Explanation:</strong> It could be decoded as &quot;TJC&quot; (20, 10, 3).</pre><p><strong>Example 3:</strong></p><pre><strong>Input:</strong> s = &quot;2030&quot;<br><strong>Output:</strong> 0<br><strong>Explanation:</strong> 30 could be decoded.</pre><h3>Solution</h3><h4>Obvious Solution</h4><p>The obvious (and brute force) way is to try every possible way. The solution looks like below tree and I will calculate final valid path number as the result. For example 1, it’s like a DFS way: first I can decode “1” or “12”, and then under “1”, I can have the choice of decoding “2” and “22”, and then under “2”, I can decode “2” only or “22” and etc. From below grahp, I can see there are some obvious duplicate calculations (like run into ‘0’ and ‘03’ decoding many times).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imUIJ-oSRdK4aouhq7CWtw.png" /></figure><h4>Best Solution (to me)</h4><p>I can use <strong>Dynamic Programming</strong> to solve this. The idea comes from following thoughts: assuming there is a string X(for example, ‘12’) and I know the ways to decode it is 2 ([1,2] or [12]). Now let me append one more char(for example, ‘3’). Obviously, for the new string, the decode way is 2 (by decode 3 to ‘C’ and get [1,2,3] or [12,3]) + 1 (by decode 3 with its previous char ‘2’, and then use adopt the decode ways for ‘1’ which is 1) = 3. So in general, if I use dp[i] for the decode ways of the string ending at index i, I will have</p><blockquote>dp[i] = dp[i-1] + dp[i-2] (if 0 &lt; s[i-1] + s[i] ≤ 26)</blockquote><p>Above is a raw idea and there are some details to figure out as below.</p><ol><li>If s[i] is ‘0’, it must combine with its previous char since ‘0’ cannot be decoded; so in this case, there should be a previous char and it should be either ‘1’ or ‘2’. If s[i] is not ‘0’, then dp[i] = dp[i-1].</li><li>if dp[i] is 0, then I need to immediately return 0 which means it’s impossible to decode the whole string. Think about the example like ‘123012592329’, when I iterate to calculate dp[3], the ‘0’ (at index = 3) itself cannot be decoded and even it gets combined with previous char (‘3’), it cannot produce an valid decoded char and hence it makes no sense to continue.</li><li>To make sure dp[i-1] and dp[i-2] are always valid, I initiliaze dp=[1,1] and use dp[-1] and dp[-2] instead of dp[i-1] and dp[i-2]. The values of 1s assume there are always 1 way to decode (if not running to “return 0”).</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/563293e4cb791f9d5a94373223df81da/href">https://medium.com/media/563293e4cb791f9d5a94373223df81da/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>It takes only one iteration of all input (assuming there are N letters) so the time complexity is O(N).</p><p>I use an array to store up to N+1 values (for an initialization value and decode ways of s[:0], s[:1], s[:2] and etc.) so the space needed is propotional to N and hence the space complexity is O(N) as well.</p><h3>Extended Reading</h3><p>Python3 cheatsheet:</p><p><a href="https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549">https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d97a0852c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leet-code-91-decode-ways-graphical-explained-python3-solution-60d97a0852c8">Leet Code 91. Decode Ways — Graphical Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm Cheatsheet (continuously updated)]]></title>
            <link>https://medium.com/tech-life-fun/algorithm-cheatsheet-continuously-updated-a95ef9b530b?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/a95ef9b530b</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 22:27:02 GMT</pubDate>
            <atom:updated>2022-04-11T04:08:16.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NY6f8057f1Ez-G0t" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Purpose:</h3><p>This is a continuous updated post to summarize typical algorithms in Python3 templates. My expectation is to train my <strong>muscle memory</strong> to these <strong>Python3 algorithm implemetations</strong> so that whenever I need them in problem solving, I don’t need to think too much (just apply those <strong>algorithm implemetation templates</strong>) and make little (if not zero) mistakes.</p><h3>Python3 Templates for Typical Algorithms</h3><ol><li>Typical DFS Python3 template</li></ol><pre>#params are normally those will change in each round of dfs<br>#for example, a position that something inside dfs will start with<br>#I&#39;d suggest a more meaningful name to use than &quot;dfs&quot;<br>#like rollFrom(postion)</pre><pre>visited = []</pre><pre>def dfs(current_node):<br>  #processing current_node to generate more leads(nodes)<br>  nodes = processing of current_node<br>  visited.append(current_node)<br>  for node in nodes:<br>    if node not in visited:<br>      dfs(params_turning_from_branch_info)</pre><pre>dfs(start_node) #kick start dfs</pre><p>Above template will check each path one by one, but sometimes I will need to abort the checking if an answer is found in some path. In that case, the template can be slightly modified to be:</p><pre>#params are normally those will change in each round of dfs<br>#for example, a position that something inside dfs will start with<br>#I&#39;d suggest a more meaningful name to use than &quot;dfs&quot;<br>#like rollFrom(postion)</pre><pre>visited = []</pre><pre>def dfs(current_node):<br>  #processing current_node to generate more leads(nodes)<br>  nodes = processing of current_node<br>  visited.append(current_node)</pre><pre>  #during above processing, some required criteria are met<br>  if(criteria are met):<br>    return True<br>  for node in nodes:<br>    if node not in visited:<br>      if dfs(node): <br>        return True<br>  return False</pre><pre>return dfs(start_node) #kick start dfs</pre><p>2. Typical BFS Python3 template<br>Similarly to DFS, I may use BFS to find ALL possible answers (which means I need to navigate all nodes). Also, I may just stop by the first answer, which below template applies to.</p><p>Also, below template is not using recursive calls.</p><pre>visited = []<br>toVisit = [start_node]</pre><pre>while(len(toVisit) &gt; 0):<br>  toVisitInNextLayer = []</pre><pre>  for current_node in toVisit:  <br>    #processing node to generate more leads(nodes)<br>    nodes = processing of current_node<br>    visited.append(current_node)<br>  <br>    #during above processing, some required criteria are met<br>    if(criteria are met):<br>      return True</pre><pre>    for node in nodes:<br>      if node not in visited:<br>        toVisitInNextLayer.append(node)<br>   <br>  toVisit = toVisitInNextLayer</pre><pre>return False</pre><h3>Extended Reading</h3><ol><li>Python3 cheatsheet:</li></ol><p><a href="https://medium.com/tech-life-fun/python3-cheatsheet-continuously-updated-66d652115549">Python3 Cheatsheet (continuously updated)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a95ef9b530b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/algorithm-cheatsheet-continuously-updated-a95ef9b530b">Algorithm Cheatsheet (continuously updated)</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python3 Cheatsheet (continuously updated)]]></title>
            <link>https://medium.com/tech-life-fun/python3-cheatsheet-continuously-updated-66d652115549?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/66d652115549</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 22:26:49 GMT</pubDate>
            <atom:updated>2021-01-24T20:59:37.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SPHuX8qSoOKMubwb" /><figcaption>Photo by <a href="https://unsplash.com/@mgmaasen?utm_source=medium&amp;utm_medium=referral">Michael Maasen</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Useful Build-in Functions</h3><ol><li>zip</li></ol><p>A quick show of what it can do:</p><blockquote>a = (“John”, “Charles”)<br>b = (“Jenny”, “Christy”)</blockquote><blockquote>x = zip(a, b)</blockquote><blockquote>#use the tuple() function to display a readable version of the result:</blockquote><blockquote>print(tuple(x)) #print ((‘John’, ‘Jenny’), (‘Charles’, ‘Christy’))</blockquote><p>Detailed explanation is available at <a href="https://www.w3schools.com/python/ref_func_zip.asp">https://www.w3schools.com/python/ref_func_zip.asp</a></p><p>2. sorted</p><p>This is useful to sort any collection(list, dictionary). A simple example looks like:</p><pre><strong>&gt;&gt;&gt; </strong>sorted([5, 2, 3, 1, 4])<br>[1, 2, 3, 4, 5]</pre><p>In addition, there is an optional parameter “key” which serves as a function that can take one input (it will be one element of the collection) and return whatever you want for sorting purpose. Certainly, I can put a lambda expression there. An example looks like:</p><pre><strong>&gt;&gt;&gt; </strong>sorted([5, 2, 3, 1, 4], key=lambda x:-x)<br>[5, 4, 3, 2, 1]<br>#when 5 is used to compare, I actaully make it -5 so it will be the smallest number and hence it will be the first one.</pre><p>Detailed explanation is available at</p><p><a href="https://docs.python.org/3/howto/sorting.html">Sorting HOW TO - Python 3.8.5 documentation</a></p><p>3. any</p><p>Refer to <a href="https://www.programiz.com/python-programming/methods/built-in/any">https://www.programiz.com/python-programming/methods/built-in/any</a>:</p><blockquote>The any() function returns True if any element of an iterable is True. If not, any() returns False.</blockquote><pre><strong>&gt;&gt;&gt; </strong>any([0,1])<br>True<br>#since 1 is True<br><strong>&gt;&gt;&gt; </strong>any([1,0])<br>True<br>#since 1 is True<br><strong>&gt;&gt;&gt; </strong>any([0,None])<br>False<br>#since not element is True</pre><p>4. enumerate()</p><p>This function is pretty handy when I want to get both index and value for a list (or key and value for a dict).</p><pre>names    = [&#39;ant&#39;, &#39;maven&#39;, &#39;gradle&#39;]<br>versions = [&#39;1.0&#39;, &#39;2.0&#39;, &#39;3.0&#39;]</pre><pre>for i, v in enumerate(names):<br>    full_name = v + &#39;-&#39; + versions[i]<br>    print(full_name)</pre><pre><em><br>&#39;&#39;&#39;<br>Output: <br>   ant-1.0   <br>   maven-2.0<br>   gradle-3.0<br>&#39;&#39;&#39;</em></pre><p><a href="https://book.pythontips.com/en/latest/enumerate.html">I</a>n addition, I can add an optional parameter which specifies the starting index, an example from <a href="https://book.pythontips.com/en/latest/enumerate.html">https://book.pythontips.com/en/latest/enumerate.html</a> looks like:</p><pre>my_list = [&#39;apple&#39;, &#39;banana&#39;, &#39;grapes&#39;, &#39;pear&#39;]<br>counter_list = list(enumerate(my_list, 1))<br>print(counter_list)<br><em># Output: [(1, &#39;apple&#39;), (2, &#39;banana&#39;), (3, &#39;grapes&#39;), (4, &#39;pear&#39;)]</em></pre><p>5, initilize a multidimensional array</p><p>a) To get a one dimension array with all 0, below both ways will do:</p><pre>&gt;&gt;&gt; f = [ 0 for _ in range(2) ]<br>&gt;&gt;&gt; f<br>[0, 0]</pre><p>OR</p><pre>&gt;&gt;&gt; f = [ 0 ] * 2 <br>&gt;&gt;&gt; f<br>[0, 0]</pre><p>But per <a href="https://stackoverflow.com/questions/4056768/how-to-declare-array-of-zeros-in-python-or-an-array-of-a-certain-size">this link</a>, c<strong>areful </strong>— <a href="https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list">the second technique doesn’t generalize to multidimensional arrays or lists of lists</a>. Which leads to the <a href="https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly">List of lists changes reflected across sublists unexpectedly</a> problem.</p><p>b) to get a multidimensional array</p><pre>&gt;&gt;&gt; f = [ [0 for _ in range(2) ] for _ in range(2)]<br>&gt;&gt;&gt; f<br>[[0, 0], [0, 0]]<br>&gt;&gt;&gt; f[0][0]=3<br>&gt;&gt;&gt; f<br>[[3, 0], [0, 0]]</pre><h3>Lambda Expression</h3><p>Lambda expression is actaully an anonymous function. It’s pretty handy when I need a small function (one line of code) while I don’t want to take the trouble to write a formal one.</p><p>Assume I want a function that can return the value of the input integer minus 2 if input is positive, I can write:</p><pre>def decreaseByTwo(x):<br>    return x-2 if x &gt; 0 else x</pre><pre>x = decreaseByTwo(x)</pre><p>While using lambda expression, it will be</p><pre>decreaseByTwo = lambda x: x-2 if x &gt; 0 else x<br>x = decreaseByTwo(x)</pre><p>Lambda expression can be very useful wherever a function is needed to be a input parameter.</p><p>Detailed explanation is available at</p><p><a href="https://www.w3schools.com/python/python_lambda.asp">https://www.w3schools.com/python/python_lambda.asp</a></p><h3>Nested Function</h3><p>Nested function is a function inside a function. It’s handy when you need to reuse a batch of codes but that reuse only make sense to your current function. At that moment, you can create a nested function inside your current function.</p><p>This is an example of a nested function. Inside parent(), a nested function child() is defined and can be invoked after its definition (but still inside parent()).</p><h4>Introducing nonlocal</h4><p>The function child() can read or assign a variable‘s value like</p><pre>def parent():<br>  a = 3<br>  b = 9</pre><pre>  def child():<br>    print(a) #will print 3<br>    print(b) #will print 9</pre><pre>  child()</pre><p>However, there is a situation that child() may want to change the value of a variable that is defined in parent() like below.</p><pre>def parent():<br>  a = 3</pre><pre>  def child():<br>    print(a) #will print 3<br>    a = 5    <br>    print(a) # will print 5<br>  <br>  child()<br>  print(a) #will still print 3 although in child() it&#39;s set to 5</pre><p>However, in above example, when <em>a=5</em> is called, Python3 actually creates a local (only valid within child()) variable which is also named ‘a’ and shadows the external a in following executions within child(). But outside child(), a will still refer to outside one.</p><p>To ensure the ‘a’ inside child() using the outside one, I need to put “<strong>nonlocal</strong>” as below.</p><pre>def parent():<br>  a = 3</pre><pre>  def child():<br>    print(a) #will print 3<br>    <strong>nonlocal a</strong><br>    a = 5    <br>    print(a) # will print 5<br>  <br>  child()<br>  print(a) #will print 5 since in child() it&#39;s set to 5</pre><p>One possible confusing part is what if I want to change an outside dict/list/other objects inside a nest function, do I need to claim “nonlocal” first? The answer is not since, like child() in below example shows, changing part of variable a is not a new assignment; but in child2(), I use “nonlocal” to <strong>completely</strong> change outside a instead of partially.</p><pre>def parent():<br>  a = {&#39;parent&#39;:3}</pre><pre>  def child():<br>    a[&#39;child&#39;] = 2<br>    print(a) </pre><pre>  def child2():<br>    <strong>nonlocal a</strong><br>    a = {1:2}<br>    print(a) #will print {1:2}</pre><pre>  print(a) #will print {&#39;parent&#39;:3}<br>  child()<br>  print(a) #will print {&#39;parent&#39;:3, &#39;child&#39;: 2}<br>  child2()<br>  print(a) #will print {1:2}<br>  child()<br>  print(a) #will print {1:2, &#39;child&#39;: 2}</pre><h3>Collections</h3><p>There are quite a lot of useful classes inside <a href="https://docs.python.org/3/library/collections.html">Python3 collection module</a>. Per official doc, collections module</p><blockquote>implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, <a href="https://docs.python.org/3/library/stdtypes.html#dict">dict</a>, <a href="https://docs.python.org/3/library/stdtypes.html#list">list</a>, <a href="https://docs.python.org/3/library/stdtypes.html#set">set</a>, and <a href="https://docs.python.org/3/library/stdtypes.html#tuple">tuple</a>.</blockquote><p>What does that mean? Let me use 2 examples to explain:</p><h4>1. defaultdict</h4><p>Note: the first letter is in lowercase.</p><p>Assume I need to have a hashmap to count how many times a letter appears in a string. I can write below code.</p><pre>s = &#39;123ab&#39;<br>m = {}<br>for c in s:<br>  if m.get(c) == None: #because c may not be an existing key in m<br>    m[c] = 0   #I need to initialize it first to avoid exception<br>  m[c] += 1  </pre><p>However, it’s a little bit clumsy. Let me show the <strong>defaultdict </strong>version:</p><pre>from collections import defaultdict</pre><pre>s = &#39;123ab&#39;<br>m = defaultdict(int)<br>for c in s:<br>  #if c is not yet a valid key, m[c]=0 will be called first<br>  m[c] += 1</pre><h4>2. Counter</h4><p>For the example of generating a hashmap to count how many times a letter appears in a string, there is actually another more easy way as below.</p><pre>from collections import Counter<br>s = &#39;123ab&#39;<br>counter_s = Counter(s)<br>counter_s # print Counter({&#39;1&#39;: 1, &#39;2&#39;: 1, &#39;3&#39;: 1, &#39;a&#39;: 1, &#39;b&#39;: 1})<br>counter_s[&#39;z&#39;] #print 0 since there is no &#39;z&#39; key</pre><p>Since Counter is a subclass of <a href="https://docs.python.org/3/library/stdtypes.html#dict">dict</a>, I can easily use it to access each key and its value.</p><h3>Useful Data Structures</h3><h4>1. Hashmap/Dictionary</h4><p>In Python 3, a dict actually performs like a hashmap. A dict is composed of multiple key/value pairs in the format of key:value, a comman(,) is used to separate each pair. The dict can be initilized like</p><blockquote>a={1:2,’strKey’:’strValue’}</blockquote><p>Any hashable type can be key. Please note that list (like [1,2,3,4]) and dict (like {‘1’:2}) are not hashabel.</p><p>It’s easy to add a key/value pair, just</p><blockquote>a[(1,2)]=(3,4)</blockquote><p>And easy to remove a pair</p><blockquote>del a[(1,2)]</blockquote><p>For time complexity, adding or removing and accessing are all O(1) operations.</p><p><strong>Iteration of dict elements:</strong></p><pre>d = {&#39;parent&#39;:3, &#39;child&#39;: 4}</pre><pre>#access keys and then use key to access value<br>for key in d:<br>  print(key, d[key]) #each time a key/value pair of d is printed</pre><pre>#access key/value<br>for key, value in d.items():<br>  print(key, value) #each time a key/value pair of d is printed</pre><pre>#Typical <strong><em>incorrect</em></strong> ways to access key/value<br>for key, value in d:<br>  print(key, value)<br>for key, value in enumerate(d):<br>  print(key, value)</pre><h4>2. Tuple</h4><p>According to <a href="https://www.tutorialspoint.com/python/python_tuples.htm#:~:text=Selected%20Reading-,Python%20%2D%20Tuples,whereas%20lists%20use%20square%20brackets.">Python — Tuples — Tutorialspoint</a>:</p><blockquote>A <strong>tuple</strong> is a collection of objects which ordered and immutable. <strong>Tuples</strong> are sequences, just like lists. The differences between <strong>tuples</strong> and lists are, the <strong>tuples</strong> cannot be changed unlike lists and <strong>tuples</strong> use parentheses, whereas lists use square brackets.</blockquote><p>Tuple is very handy whenI need to just group a series of objects, for example, I can use a (x,y) tuples to represent a two dimension point while (x,y,z) to a three dimension point. It looks very logically and elegant.</p><p>As mentioned above, a tuple is immutable which means it can not be changed once defined. Look at below example:</p><pre>a = (1,0)<br>print(a[0]) #this will print 1<br>a[0] = 2 #this will throw an error</pre><h4>3. List/Stack</h4><p>A list is a collection of objects which are NOT immutable. Please compare below codes to the codes in above <strong>tuple</strong> section and note that square brackets ‘[]’ are used here in <strong>list</strong> definition while parentheses ‘()’ are used in tuple definition.</p><pre>a = [1,0]<br>print(a[0]) #this will print 1<br>a[0] = 2 <br>print(a[0]) #this will print 2</pre><p>Very often, list in Python3 is used as a <strong>stack</strong>. Data can be <strong>pushed</strong> to a stack or <strong>popped</strong> up. The only magic here is the first pushed data will be the last one to pop up (often referred as “first in last out” FILO). The next to-be-popped data stays at the top of stack. Normally a <strong>peek</strong> function is expected to take a look at the data at the top of stack without actually popping it up. Look at this example to get more understanding:</p><pre>s = []<br>s.append(1) #here I use append to serve as push<br>print(s) #this will print [1]<br>s.append(2) #now s becomes [1,2]<br>s.append(3) #now s becomes [1,2,3]<br>a = s.pop()<br>print(a)  # it will print 3, which last in but first out<br>print(s)  # since 3 is popped, s is [1,2]<br>s.append(3) #now s becomes [1,2,3] again<br>print(s[-1]) # print 3, s[-1] is equal to peek<br>print(s)  # print [1,2,3], peek(unlike pop) will not change a stack</pre><h4>4, Heap Queue</h4><p>Please note that this is a summary and extention with example of official document <a href="https://docs.python.org/3/library/heapq.html">https://docs.python.org/3/library/heapq.html</a>.</p><p>Within Python’s heapq, all elements are placed in a binary tree where any element’s value will be less than or equal to any of its children. Not surprisely, the root of the tree contains smallest value. So Python’s heapq is actually <strong>min heap </strong>which means on the top of the heap is <strong>always </strong>the smallest element.</p><p>Another fact is that an element can be a integer as well as a basic data structure like tuple. Actually, whatever data structure (like string) I can put inside a list can be an element’s type in heap. That’s why it can be used as <strong>Priority Queue</strong> as below example illustrates:</p><pre><strong>&gt;&gt;&gt; from heapq import *<br>&gt;&gt;&gt; </strong>h = []<br><strong>&gt;&gt;&gt; </strong>heappush(h, (5, &#39;write code&#39;))<br><strong>&gt;&gt;&gt; </strong>heappush(h, (7, &#39;release product&#39;))<br><strong>&gt;&gt;&gt; </strong>heappush(h, (1, &#39;write spec&#39;))<br><strong>&gt;&gt;&gt; </strong>heappush(h, (3, &#39;create tests&#39;))<br><strong>&gt;&gt;&gt; </strong>heappop(h)<br>(1, &#39;write spec&#39;)</pre><p>A heap queue can be initialized in 2 ways:</p><ol><li>use a empty list (see above example)</li><li>use heapq.heapify(list)</li></ol><pre><strong>&gt;&gt;&gt; from heapq import *<br>&gt;&gt;&gt; </strong>h = [(5, &#39;write code&#39;),(1, &#39;write spec&#39;)]<br><strong>&gt;&gt;&gt; </strong>heapify(h)<br><strong>&gt;&gt;&gt; </strong>heappop(h) <br>(1, &#39;write spec&#39;)<br><strong>&gt;&gt;&gt; </strong>heappop(h)<br>(5, &#39;write code&#39;)</pre><p>Pleaes note that each time heappush/heappop is called (when a new element is added or removed), the heap is adjusted internally to againt ensure itself a min heap (therefore, each element is equal to or less than its children, and smallest one on the top).</p><p>There are 2 very useful functions in heapq:</p><blockquote>heapq.nlargest(<em>n</em>, <em>iterable</em>, <em>key=None</em>)</blockquote><blockquote>heapq.nsmallest(<em>n</em>, <em>iterable</em>, <em>key=None</em>)</blockquote><p>where key is a function of one argument that is used to extract a comparison key from each element in <em>iterable</em>. An example looks like below.</p><pre><strong>&gt;&gt;&gt; from heapq import *<br>&gt;&gt;&gt; </strong>h = [(1,4),(2,3)]<br><strong>&gt;&gt;&gt; </strong>heapify(h)<br>&gt;&gt;&gt; nsmallest(2,a,key=lambda p:p[1])<br>[(2, 3), (1, 4)]<br>&gt;&gt;&gt; nsmallest(2,a)<br>[(1, 4), (2, 3)]</pre><p>Major heapq operations (heapify, heappush, heappop) has O(N) time complexity while some (nsmallest, nlargest) has O(1).</p><p>Some Leetcode problems (which aim to find top K smallest/largest elements) can be easily solved by using heap:</p><ul><li><a href="https://leetcode.com/problems/top-k-frequent-elements/">Top K Frequent Elements - LeetCode</a></li><li><a href="https://leetcode.com/problems/k-closest-points-to-origin/">K Closest Points to Origin - LeetCode</a></li></ul><h4><strong>5. Dummy head of Linked List</strong></h4><p>In many cases, if I want to append a node to a linked list(which may not exist), I need to have an if/else like:</p><pre>  head = None<br>  ...<br>  if head == None: <br>    header = ListNode()<br>  else:<br>    preNode.next = ListNode()<br>  preNode = curNode<br>  ...<br>  return <strong><em>head</em></strong></pre><p>The reason is preNode can be None if the linked list does not yet exist. To make above code more concise and beautiful, there is a technique called <strong>dummy head</strong>: I don’t create the linked list when needed, instead, I will just go ahead and create the <strong>head</strong> and have preNode pointing to it so that preNode is <strong>always </strong>valid. Accordingly, I should remember the real data starts on head.next instead of head since the head is just a dummy placeholder. Compare below code snippet with the previous one to get a understanding of that.</p><pre>  head = ListNode()<br>  preNode = head<br>  ...<br>  preNode.next = <br>  preNode = curNode<br>  ...<br>  return <strong><em>head.next</em></strong></pre><p>To connect this technique to real world examples, I attach 2 practices of it as below.</p><ul><li><a href="https://medium.com/tech-life-fun/leet-code-82-remove-duplicates-from-sorted-list-ii-graphically-explained-python3-solution-ba7672f12ca">Leet Code 82. Remove Duplicates from Sorted List II — Graphically Explained Python3 Solution</a></li><li><a href="https://medium.com/tech-life-fun/leetcode-23-merge-k-sorted-lists-graphically-explained-python3-solution-d0e77419956c">LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66d652115549" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/python3-cheatsheet-continuously-updated-66d652115549">Python3 Cheatsheet (continuously updated)</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leet Code 560. Subarray Sum Equals K — Explained Python3 Solution]]></title>
            <link>https://medium.com/tech-life-fun/leet-code-560-subarray-sum-equals-k-explained-python3-solution-31ab6262615e?source=rss----b45a68ec22db---4</link>
            <guid isPermaLink="false">https://medium.com/p/31ab6262615e</guid>
            <category><![CDATA[leetcode-560]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 22:25:35 GMT</pubDate>
            <atom:updated>2020-07-12T20:51:48.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leet Code 560. Subarray Sum Equals K — Explained Python3 Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mTRRu_XlkJB8qtj0" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Paweł Czerwiński</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Description</h3><p>Given an array of integers and an integer <strong>k</strong>, you need to find the total number of continuous subarrays whose sum equals to <strong>k</strong>.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong>nums = [2,2,3,0,4,-1,1,6], k = 7<br><strong>Output:</strong> 3</pre><h3>Solution</h3><h4>Obvious Solution</h4><p>There is certainly a brute force way. Iterarte the whole list, check the sum of (currentElement to currentElement+1), (currentElement to currentElement + 2), pesudo code looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*ygMoDvxYX_BsmQ1L4-hIgg.png" /></figure><p>In total, there are 3 loops and make the time complexity O(N³). It should work but definitely not an efficient way. There are ways to optimize this since there are many duplication of computation and the complexity can be decreased to O(N²).</p><h4>Best Solution (to me)</h4><p>Obviously, each subarray will end up with some index. Let me use i to represent that <em>some index</em>. And sum(0 to i) is very easy (and cheap — just take O(N)) to get.</p><p>Look at below example at i = 4, sum(0 to 4)= X + K. That means sum(0 to 4) can be broken to 2 parts, the second part is what I desire(with the sum of K), the first part X is actaully another sum which accumulate from 0 to 1. Now there is some light: if I have sum(0 to i), I can assume there is an index j (where j&lt;i) , check if sum(0 to i) - K occurs in previous sum(0 to 0), sum(0 to 1), sum(0 to 2)…sum(0 to i-1), and increase the counter when an occurance is found. The value of the counter is the number of subarrays ending with index i that qualify the sume of K. In below example for index = 4, only sum(0 to 1) + K = sum(0 to 4), then there is only 1 qualified subarray which is [3,0,4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doj1MTvLz6fTtgRR01kfaw.jpeg" /><figcaption>Leet Code 560. Subarray Sum Equals K Ilustation</figcaption></figure><p>Please note that in some case, there could be more than 1 qualified subarray.</p><p>Again look into another example as followed. For subarrays that ending at index 5, there are 2 cases:</p><blockquote>sum(0 to 2) + sum(3 to 5)</blockquote><blockquote>sum(0 to 1) + sum(2 to 5)</blockquote><p>And sum(0 to 2) and sum(0 to 1) are equal (both to 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hn7ywdLRcfgRiSjEtZDxeA.png" /></figure><p>Therefore, I need a <strong>Hashmap </strong>to record all sum(0 to x) (as the key) and its occurance (as the value). When I have sum(0 to i), I can check in the hasmap the value of sum(0 to i)-K to get the occurance number, and that number will the subarrays that ending with index i.</p><p>There is one trick however, again with my first example, what if sum(0 to i) itself is already equal to K like below the qualified subarray [2,2,3]? At this moment, the breakdown is : sum(0 to 2) = 0 + sum(0 to 2). The trick I play is add {0:1} to the hashmap saying for sum of 0, there is by default 1 occurance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doj1MTvLz6fTtgRR01kfaw.jpeg" /><figcaption>Leet Code 560. Subarray Sum Equals K Ilustation</figcaption></figure><p>Alright, now here comes the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8ce1f9c5ef43b94574e6a9f5bee8de4/href">https://medium.com/media/d8ce1f9c5ef43b94574e6a9f5bee8de4/href</a></iframe><h3>Time &amp; Space Complexity</h3><p>As above illustration/code shows, the time complexity is O(N): it just goes through each element in the input array for once only and with the loop each operation is O(1).</p><p>When it comes to space complexity: there is a hashmap which can scale (in worse case) with the size of input array, so it can take up to O(N) space and hence the space complexity is O(N).</p><h3>Python 3 knowledge points</h3><p>Within the solution, hashmap is used. I put together a post Python Cheatsheet with a section hashmap. Click <a href="https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549">https://medium.com/@edward.zhou/python3-cheatsheet-continuously-updated-66d652115549</a> to view more cheats :)</p><h3>Extended Reading/Thinking</h3><p>What if you are asked to return all subarrays?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ab6262615e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-life-fun/leet-code-560-subarray-sum-equals-k-explained-python3-solution-31ab6262615e">Leet Code 560. Subarray Sum Equals K — Explained Python3 Solution</a> was originally published in <a href="https://medium.com/tech-life-fun">Tech Life &amp; Fun</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>