<?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 Edward Zhou on Medium]]></title>
        <description><![CDATA[Stories by Edward Zhou on Medium]]></description>
        <link>https://medium.com/@edward.zhou?source=rss-694e30e2a597------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2gAccocDBFTPEZrY.jpg</url>
            <title>Stories by Edward Zhou on Medium</title>
            <link>https://medium.com/@edward.zhou?source=rss-694e30e2a597------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:48:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edward.zhou/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[Edward on Java with Leetcode: 5. Longest Palindromic Substring]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-5-longest-palindromic-substring-8075e6ffd312?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/8075e6ffd312</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[palindrome]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 21:24:00 GMT</pubDate>
            <atom:updated>2023-12-10T21:24:00.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FEhAJEV1bf9Dci4Q" /><figcaption>Photo by <a href="https://unsplash.com/@ampalmer?utm_source=medium&amp;utm_medium=referral">Andrew Palmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p>Problem description is available at <a href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring</a></p><h3>Algorithm</h3><p>I have an algorithm using DP (dynamic programming) <a href="http://5. Longest Palindromic Substring — Graphically Explained Python3 Solution">here</a>. But here I’m going to save some brain cells using a more straightforward way.</p><p>By palindrome definition, it should either center a char in the string or center a char and its precedent char (if they are the same), and then extend its wings from 2 different directions. That makes a perfect forloop.</p><h3>Java Solution</h3><p>Codes look like below.</p><pre>class Solution {<br>    public String longestPalindrome(String s) {<br>        /*<br>        For each charactor, it can be the center chararactor of a palindrome<br>        or as the right side (except the first one) of a palindrome.<br>        */<br>        String longest = &quot;&quot;;<br>        int len = s.length();<br>        for (int i = 0; i &lt; len; i++){<br>            int wing = 0;<br>            while(i - wing &gt;= 0 &amp;&amp; i + wing &lt; len){<br>                if (s.charAt(i - wing) != s.charAt(i + wing)) {                    <br>                    break;<br>                }<br>                if (wing * 2 + 1 &gt; longest.length()) <br>                    longest = s.substring(i - wing, i + wing + 1);<br>                wing++;<br>            }        <br><br>            if ( i == 0 ) continue;<br><br>            int j = i - 1;<br>            wing = 0;<br>            while(j - wing &gt;= 0 &amp;&amp; i + wing &lt; len){<br>                if (s.charAt(j - wing) != s.charAt(i + wing)) {                    <br>                    break;<br>                }<br>                if (wing * 2 + 2 &gt; longest.length())0<br>                    longest = s.substring(j - wing, i + wing + 1);<br>                wing++;<br>            }            <br>        }<br>        return longest;<br>    }<br>}</pre><h3>Java Knowledge</h3><ol><li>Java String’s substring function.</li></ol><h4>Syntax</h4><pre>public String substring(int begIndex, int endIndex);</pre><h4>Parameters</h4><ul><li><strong>beginIndex : </strong>the begin index, <strong>inclusive</strong>.</li><li><strong>endIndex : </strong>the end index, <strong>exclusive</strong>.</li></ul><p>2. In case of printing debug information, below code can be used.</p><pre>System.out.println(aVariable);</pre><p>If I want to print more than 1 integers in the same row</p><pre>System.out.println(aInt + &quot;&quot; + bInt);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8075e6ffd312" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-5-longest-palindromic-substring-8075e6ffd312">Edward on Java with Leetcode: 5. Longest Palindromic Substring</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edward on Java with Leetcode: 4. Median of Two Sorted Arrays]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-4-median-of-two-sorted-arrays-1eb9c48a01f3?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eb9c48a01f3</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[array-median]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 18:36:29 GMT</pubDate>
            <atom:updated>2023-12-10T18:36:29.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lYrgL8VT3-e2x3uW" /><figcaption>Photo by <a href="https://unsplash.com/@mcgilllibrary?utm_source=medium&amp;utm_medium=referral">McGill Library</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p>Problem description is available at <a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">4. Median of Two Sorted Arrays</a>.</p><h3>Algorithm</h3><p><a href="https://www.youtube.com/watch?v=ScCg9v921ns">This video</a> (audio in Chinese) explains very clear how to solve the problem. I’m just going to explain in English with my own words.</p><p>First go to the foundamental thing: what needs to be done exactly? To find the middle value(s) of the merged array (imaging I merge them). Assume the lengths of array 1 and 2 is L1 and L2, therefore total length is L=L1+L2, if the total number is even, I should find L/2th and (L/2+1)th numbers; if the total number is odd, I should find (L/2+1)th.</p><p>Now let me use K to represent L/2 (in case of even) or (L/2+1). If I can pick totally smallest K numbers from the merged array, and n1 from nums1 while n2 from nums2, then the median is</p><p><strong>max(nums1[n1–1], nums2[n2–1])</strong> <em>in case L is odd</em></p><p>or</p><p><strong>(max(nums1[n1–1], nums2[n2–1]) + min(nums1[n1], nums2[n2]))</strong> <em>in case L is even</em></p><p>Certainly n1 can be either 0 (indicating no numbers from nums1 is seleted into the set of K due to either it’s empty or every number in nums1 is larger than the maximum of nums2) or L1 (meaning all numbers from nums1 is seleted into the set of K). Same thing can happen to n2. In those corner cases, n1–1, n2–1 and etc. need to be carefully inspected to make sure when they are used as an array index, array boundary will not be crossed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IodptN7xi5w0WxwgIp1C-g.png" /><figcaption>cut1, cut2 indicates the cutting line (not inclued themselves)</figcaption></figure><p>Binary search is used to determine the postion of cut1and cut2can be concluded from using K-cut1 so that required time complexity (Olog(L1+L2)) can be met.</p><h3>Java Solution</h3><p>In above #2, I mention the “fast forward the left side” which means if the right side now is charactor X, I want to see what’s the position of X in the existing window [left, right). The easiest way to achieve that is if I have a <a href="https://en.wikipedia.org/wiki/Hash_table">hashmap</a> whose keys are charactors and values are positions.</p><pre>class Solution {<br>    public double findMedianSortedArrays(int[] nums1, int[] nums2) {<br>        int L1 = nums1.length;<br>        int L2 = nums2.length;<br>        <br>        if (L1 &gt; L2) return findMedianSortedArrays(nums2, nums1);<br><br>        int L = L1 + L2;<br>        /*<br>            Thanks to https://www.youtube.com/watch?v=ScCg9v921ns <br>            (audio in Chinese).<br>            if L is even, I need to find the (L/2)th and (L/2+1)th;<br>            if L is odd, I need to find the (L/2+1)th<br>            use K to represent L/2 (in case of even) or (L/2+1)<br>            if I can pick totally smallest K numbers from both nums1 and nums2,<br>            then the biggest one is the answer or the first part of the answer<br>        */<br>        int K = ( L % 2 == 1) ? L/2+1 : L/2;<br>        int start1 = 0, end1 = L1;<br>        while(start1 &lt;= end1){<br>            int cut1   = (start1 + end1) / 2;<br>            int left1  = (cut1 == 0) ? Integer.MIN_VALUE : nums1[cut1 - 1];<br>            int right1 = (cut1 &lt; L1) ? nums1[cut1] :Integer.MAX_VALUE; <br>            int cut2   = K - cut1;<br>            int left2  = (cut2 &lt;= 0) ? Integer.MIN_VALUE : nums2[cut2 - 1];<br>            int right2 = (cut2 &lt; L2) ? nums2[cut2] :Integer.MAX_VALUE; <br><br>            if (left1 &lt;= right2 &amp;&amp; left2 &lt;= right1){<br>                int val1 = Math.max(left1, left2);<br>                return ( L % 2 == 1) ? val1 : <br>                  ((double)(Math.min(right1, right2) + val1)) /2;<br>            }<br>            else{<br>                if (left1 &gt; right2) end1 = cut1 - 1;<br>                if (left2 &gt; right1) start1 = cut1 + 1;<br>            }<br>        }<br><br>        //If we run here, either L1 = 0 or nums1[0] &gt; nums2[the last one]<br>        return ( L % 2 == 1) ? nums2[L/2] : <br>          ((double)(nums2[L/2-1] + nums2[L/2])/2);<br>    }<br>}</pre><h3>Java Knowledge</h3><ol><li>It’s pretty confusing but Java.String has a method called length()while an array’s size can be retrieved by using lengthproperty.</li><li>Java has an embeded package called Math. In above, I use Math.minto get the minimum of two.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eb9c48a01f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-4-median-of-two-sorted-arrays-1eb9c48a01f3">Edward on Java with Leetcode: 4. Median of Two Sorted Arrays</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edward on Java with Leetcode: 3. Longest Substring Without Repeating Characters]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-3-longest-substring-without-repeating-characters-a4d56bcefe39?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d56bcefe39</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[substring]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 04:25:33 GMT</pubDate>
            <atom:updated>2023-11-28T04:25:33.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GzVeaaN2kavmGXRE" /><figcaption>Photo by <a href="https://unsplash.com/@anritikhon?utm_source=medium&amp;utm_medium=referral">Andrey Tikhonovskiy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p>Problem description is available at <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">3. Longest Substring Without Repeating Characters</a>.</p><h3>Algorithm</h3><p>In a nutshell, I need to find out a maximum window that contains no repeating characters. This is a typical slide window problem. Assume a 2D window that can move along an 1D array, I can</p><ol><li>fix the left side and keep moving the right side until there is a duplication.</li><li>I will move the left side till no repeat. Or even better if I can fast forward the left side without moving one place at a time.</li><li>Repeat #1 till the end of the array</li></ol><h3>Java Solution</h3><p>In above #2, I mention the “fast forward the left side” which means if the right side now is charactor X, I want to see what’s the position of X in the existing window [left, right). The easiest way to achieve that is if I have a <a href="https://en.wikipedia.org/wiki/Hash_table">hashmap</a> whose keys are charactors and values are positions.</p><pre>class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int len = s.length();<br>        if (len == 0)<br>            return 0;<br>        int maxLen = 0;<br>        int left=0, right=0;<br>        Map&lt;Character, Integer&gt; map = new HashMap();<br>        while(right &lt; len){<br>            //check if s[right] is in map and its position &gt;= left<br>            char cur = s.charAt(right);<br>            int curExistingPos = map.getOrDefault(cur, -1);<br>            if (curExistingPos != -1 &amp;&amp; curExistingPos&gt;= left){<br>                //run into a repeating<br>                //calculate the window size and update the max value<br>                maxLen = Math.max(maxLen, right - left);<br>                //fast forward the left<br>                left = curExistingPos + 1;                <br>            }<br>            map.put(cur, right);<br>            right++;<br>        }<br>        return Math.max(maxLen, right - left);<br>    }<br>}</pre><h3>Java Knowledge</h3><ol><li>Java String has a length() method to get its length, which is different from length attribute of an array (see <a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-1-two-sum-524570caedc2)">my previous post</a> for more details).</li><li>String manipulation is very common and that’s why I want to read the official doc <a href="https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html">here </a>. I cannot use s[index]but have to use s.charAt().</li><li>In my <a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-1-two-sum-524570caedc2)">my previous post</a>, I introduce some key functions of a Mapbut forget to mention getOrDefaultbut it does worth some attention.</li><li>Now comes with something new: Math.According to <a href="https://javahungry.blogspot.com/2022/10/import-math-class-java.html">this article</a>, Mathclass is included in java.langso I don’t need to explicitly import it. Here is <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html">the official doc</a> which again worth a glimpse.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d56bcefe39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-3-longest-substring-without-repeating-characters-a4d56bcefe39">Edward on Java with Leetcode: 3. Longest Substring Without Repeating Characters</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edward on Java with Leetcode: 2. Add Two Numbers]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-2-add-two-numbers-e9f1e197c3d6?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f1e197c3d6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 16:11:58 GMT</pubDate>
            <atom:updated>2023-11-25T16:11:58.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem</h3><p>Problem description is available at <a href="https://leetcode.com/problems/add-two-numbers/">2. Add Two Numbers</a>.</p><h3>Java Solution</h3><p>The algorithm is straightforward: since a list is a reversed representation of a number and adding should also start from a number’s lower end, I just need to add the corresponding digits from both lists and then move on to the next place until both lists end (if one ends first, its digit will be deemed as 0).</p><p>However there are some pitfalls to be aware of:</p><ol><li>carry needs to be counted in <strong>from the begining </strong>( see below<strong> while </strong>loop in code), especially if both lists end, the loop may still continue if carry (from last adding) is not 0.</li><li>in each iteration, a new node is created (<strong>result </strong>in below code) and its predecent node (<strong>prev </strong>in below code) is required to link to the new node, and shortly after <strong>result </strong>becomes <strong>prev </strong>(in the eyes of next iteration) it makes sense to have a <strong>head </strong>that points to the first node and hence return <strong>head.next</strong> as the final result. In this case, the head is actually a dummy head or a placeholder.</li></ol><pre>/**<br> * Definition for singly-linked list.<br> * public class ListNode {<br> *     int val;<br> *     ListNode next;<br> *     ListNode() {}<br> *     ListNode(int val) { this.val = val; }<br> *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }<br> * }<br> */<br>class Solution {<br>    public ListNode addTwoNumbers(ListNode L1, ListNode L2) {         <br>        ListNode head = new ListNode();<br>        ListNode prev = head;<br>        int carry = 0;<br>        while(L1 != null || L2 != null || carry != 0){<br>            int op1 = 0;<br>            int op2 = 0;<br>            if (L1 != null) {<br>                op1 = L1.val;<br>                L1 = L1.next;<br>            }<br>            if (L2 != null) {<br>                op2 = L2.val;<br>                L2 = L2.next;<br>            }<br>            int sum = op1 + op2 + carry;<br>            carry = sum / 10;<br>            ListNode result = new ListNode(sum - carry * 10); <br>            prev.next = result;<br>            prev = result;<br>        }<br>        return head.next;<br>    }<br>}</pre><h3>Java Knowledge</h3><ol><li>Logical operator: <strong>&amp;&amp;</strong> and <strong>||</strong>, for representing “and” and “or” respectively. Also, in Python, I used to use <strong>if (X)</strong> to judge if <strong>X </strong>is <strong>None </strong>or not. In Java, I have to use <strong>if(X != null)</strong>.</li><li>Offical doc <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html">Java arithmetic operators</a> definitely worths a read, it includes basic but complete illustrations including operators like <br>Modulus or Remainder (%), Increment (++) and decrement (--) and some handy <em>compound assignments </em>like<em> </em><strong>x+=1</strong><em>.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f1e197c3d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-2-add-two-numbers-e9f1e197c3d6">Edward on Java with Leetcode: 2. Add Two Numbers</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edward on Java with Leetcode]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-a0436421b3bf?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0436421b3bf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[two-sum]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 06:25:49 GMT</pubDate>
            <atom:updated>2023-11-25T16:13:37.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcumOLWzsEw9-x1Oj5oRfA.png" /><figcaption>Learning-Java-with-LeetCode-Problems-by-ChatGPT</figcaption></figure><h3>Why I’m doing this</h3><p>I’m not new to Java but haven’t been using it for many years. Now I’d like to brush up my Java skills like a beginner — I assume Java world changes a lot since the time I stopped.</p><p>This article will serve as an index of all such articles. My initial thought is to conqure 30 LeetCode algorithm problems within the year of 2023 (the date I wrote this one is 11/24/2023). I may stop if that can give me enough confidence of basic Java knowledge: syntax, common library/class usage and etc. Certainly the activity may continue if I determine otherwise.</p><p>An article will be published along with each problem I solve which includes codes, related Java knowledge I learn from solving the problem, a brief or detailed illustration of the algorithm (depending on my understanding of the algorith, if I know it well or feel it straightforwrd, I may make it concise since the key point is to learn the programming language), and a possible Youtube video.</p><p>There may be many such activities but I treat this as a learning practice which forces me to learn, summarize, prove (by giving outputs) and reflect (by future inspection). If I cannot elaborate, I may not really understand; if I can note something down, it will be marked deeper in my mind.</p><h3>Index</h3><p>11/25/2023 <a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-1-two-sum-524570caedc2">1. Two Sum</a></p><p>11/25/2023 <a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-2-add-two-numbers-e9f1e197c3d6">2. Add Two Numbers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0436421b3bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-a0436421b3bf">Edward on Java with Leetcode</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edward on Java with Leetcode: 1. Two Sum]]></title>
            <link>https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-1-two-sum-524570caedc2?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/524570caedc2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 06:23:58 GMT</pubDate>
            <atom:updated>2023-11-25T06:23:58.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDVpB01vHcat2d1ds5qZTg.png" /></figure><h3>Problem</h3><p>Problem description is available at <a href="https://leetcode.com/problems/two-sum/">Two Sum</a>.</p><h3>Java Solution</h3><p>The algorithm is pretty simple, use a <a href="https://en.wikipedia.org/wiki/Hash_table">hashmap </a>to remember each visited number and its index in the form of “number:index”. When coming to a new number, mark it as <strong>x</strong>, and looking in the hashmap if <strong>y</strong> (equals to <strong>target-x</strong>) exists, if <strong>y </strong>is already in the hashmap, that means a previous visited <strong>y</strong>+<strong>x</strong> = <strong>target</strong>. Then basing on the requirement, the index of <strong>x</strong> and <strong>y</strong> should be returned.</p><pre>class Solution {<br>    public int[] twoSum(int[] nums, int target) {<br>        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            int x = nums[i];<br>            int y = target - nums[i];<br>            if (map.containsKey(target - nums[i])) {<br>                return new int[] {map.get(y), i};<br>            }<br>            map.put(x, i);<br>        }<br><br>        return null;<br>    }<br>}</pre><h3>Java Knowledge</h3><p>I have learned or reminded myself (since I use Python more often) the below points:</p><ol><li>Java variable needs a type and needs to end with “;”</li></ol><p>Instead of “x=1”, I should write “<strong>int </strong>x=1<strong>;</strong>”.</p><p>2. Java use “<strong>null</strong>” to represent nothing rather than Python’s “None” .</p><p>3. Java’s hashmap is defined in <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html">java.util.HashMap</a>as</p><pre>public class HashMap&lt;K,V&gt;<br>extends AbstractMap&lt;K,V&gt;<br>implements Map&lt;K,V&gt;, Cloneable, Serializable</pre><p>That’s why the below line can compile (note that <strong>map </strong>is a <strong>Map </strong>while the “new” class is <strong>HashMap&lt;&gt;</strong>.</p><pre>Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br><br>//below are also correct<br>Map&lt;Integer, Integer&gt; map = new HashMap();<br>Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();</pre><p>BTW, one should read the doc of <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html">java.util.HashMap</a>, as it gives more insights of HashMap class. For example, it mentions HashMap is not thread safe:</p><blockquote><strong>Note that this implementation is not synchronized.</strong> If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it <em>must</em> be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be &quot;wrapped&quot; using the <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collections.html#synchronizedMap(java.util.Map)">Collections.synchronizedMap</a> method. This is best done at creation time, to prevent accidental unsynchronized access to the map:</blockquote><blockquote>Map m = Collections.synchronizedMap(new HashMap(...));</blockquote><p>4. Hashmap functions (not a complete list but a frequent one)</p><p>void put(K, V)</p><p>V get(K)</p><p>V remove(K)</p><p>int size()</p><p>boolean containsKey()</p><p>boolean containsValue()</p><p>Set&lt;K&gt; keySet()</p><p>5, Java Array</p><pre>int[] a={}<br>a.length //represent an array&#39;s length, note &quot;length&quot; is not a function</pre><p><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html">This </a>is a good introduction of Java array. Some key excerpts:</p><blockquote>An <em>array</em> is an object of reference type which contains a fixed number of components of the same type; the length of an array is immutable. Creating an instance of an array requires knowledge of the length and component type. Each component may be a primitive type (such as byte, int, or double), a reference type (such as <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html">String</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html">Object</a>, or <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/CharBuffer.html">java.nio.CharBuffer</a>), or an array. Multi-dimensional arrays are really just arrays which contain components of array type.</blockquote><blockquote>Arrays are implemented in the Java virtual machine. The only methods on arrays are those inherited from <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html">Object</a>. The length of an array is not part of its type; arrays have a length field which is accessible via <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Array.html#getLength-java.lang.Object-">java.lang.reflect.Array.getLength()</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524570caedc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edward-on-java-with-leetcode/edward-on-java-with-leetcode-1-two-sum-524570caedc2">Edward on Java with Leetcode: 1. Two Sum</a> was originally published in <a href="https://medium.com/edward-on-java-with-leetcode">Edward on Java with Leetcode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload iPad Video to NAS server]]></title>
            <link>https://medium.com/@edward.zhou/upload-ipad-video-to-nas-server-8040e93c72ce?source=rss-694e30e2a597------2</link>
            <guid isPermaLink="false">https://medium.com/p/8040e93c72ce</guid>
            <category><![CDATA[upload-ios-video]]></category>
            <category><![CDATA[nas-server]]></category>
            <category><![CDATA[ios-shortcuts]]></category>
            <dc:creator><![CDATA[Edward Zhou]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 05:26:41 GMT</pubDate>
            <atom:updated>2023-01-14T23:24:35.965Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 1 of a journey to automoate video archiving and publishment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Luv7c7fvOLk1oC24" /><figcaption>Photo by <a href="https://unsplash.com/@alexcpl?utm_source=medium&amp;utm_medium=referral">Alex Cheung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is part of a journey of automating my video publishment from iPad to Youtube, WeChat and etc. The whole solution background is available at <a href="https://medium.com/tech-life-fun/video-publishment-automation-935d5120dc9b">https://medium.com/tech-life-fun/video-publishment-automation-935d5120dc9b</a>.</p><h3>Environment Involved</h3><p>1, an iPad with shortcuts availabe.</p><p>Shortcuts need to be able to delete files without confirmation.</p><p>2, a NAS server (I’m using a Synology NAS). Certainly it can be any Linux server.</p><h3>Steps (how-tos)</h3><p>1. In the NAS server, set up a HTTP file server that supports upload using POST.</p><p>The simple upload server I use is:</p><p><a href="https://github.com/mayth/go-simple-upload-server">GitHub - mayth/go-simple-upload-server: Simple HTTP server to save artifacts</a></p><p>I have deployed its docker image into my NAS with below settings:</p><p>a) Execution Command</p><p>Please note that I set upload_limit to be 500MB+ since video files are usually big.</p><pre>/usr/local/bin/app -token &lt;my-token&gt; -upload_limit 52428800000 /video</pre><p>b) Map an external port (here is 25479) to container port 25478.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0tmPhHY5CdZUGnIS9zwUw.png" /></figure><p>c) Mount a local folder to /video which is used in the execution command as an argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*uBbKqf8vVxm9JFHEfXNX4Q.png" /></figure><p>d) Now if I copy a file named test.txt to the local folder, I should be able to use http://&lt;NAS-IP&gt;:25479/files/test.txt?toke=&lt;my-token&gt;</p><p>2. Write a iOS shortcut to allow video(s) selection; the shortcut can then upload the video(s) to the file server and delete those videos.</p><p>Since I’m a beginner of iOS shortcut programming, I actually learn from an existing shortcut mentioned at <a href="https://www.reddit.com/r/shortcuts/comments/9klkcs/a_shortcut_to_upload_camera_roll_media_to_your/">https://www.reddit.com/r/shortcuts/comments/9klkcs/a_shortcut_to_upload_camera_roll_media_to_your/</a>.</p><p>Anyway, below is my shortcut which can be opened in an iOS device (iPad for example):</p><p><a href="https://www.icloud.com/shortcuts/b83a133b316845bb91ea630fe8df96f1">https://www.icloud.com/shortcuts/b83a133b316845bb91ea630fe8df96f1</a></p><p>For a quick glimpse, here is a screenshot. “[var]” needs to be replaced with actual value. For example, if in above step “token” is set to be “my-token” then “[token]” needs to be replaced with “my-token”. <strong>Please be aware there are 2 “Get contents” actions and both actions should go through the replacement process.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiW-5cWxtq9VlGTF3ztXTA.png" /></figure><h3>Appendix — Detours</h3><p>1, While above steps may look (hopefully) straightforward, I actaully do not figure them out in the beginning.</p><p>When designing/implementing a solution, there are always some detours in the journey. Below are some thoughts that are not working well but that do take me several hours to learn/realize.</p><p>At first I thought about using SFTP so I just go ahead and enable it in Synology DSM like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*E-qcGcSu3NDIeC5uyPuKiA.png" /></figure><p>Also, I grant my daughter’s account SFTP access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiGcT2iivAWt1L__YYOJ3Q.png" /></figure><p>It does work when I try to use a SFTP client to upload files. However, Apple Shortcuts do not offer SFTP out of the box so I have to refer to SSH script. SSH script needs to be run inside Synology NAS and that’s where I run into a problem: my daughter’s account doesn’t belong to an admin group and that means it cannot SSH into my NAS!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi_IRm7sl8cZ-nFecyKw9g.png" /></figure><p>Only after that I’m aware that I should look for a simple file server (with upload support via POST ideally) and come across <a href="https://hub.docker.com/r/mayth/simple-upload-server">https://hub.docker.com/r/mayth/simple-upload-server</a>.</p><p>2, I had a hard time (~2 hours) to get iOS shortcuts to upload files to my upload server.</p><p>Below link gives me a lot help (the most important part is: use <strong>Form </strong>instead of <strong>File </strong>as the request body and “file” as the form field name).</p><p><a href="https://heydingus.net/blog/2021/6/shortcuts-tips-uploading-images-to-imagekit-for-blogging">Shortcuts Tips: Uploading Images to a CDN for Blogging</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8040e93c72ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Video Publishment Automation]]></title>
            <link>https://medium.com/tech-life-fun/video-publishment-automation-935d5120dc9b?source=rss-694e30e2a597------2</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-694e30e2a597------2</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-694e30e2a597------2</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>
    </channel>
</rss>