<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>O(n) Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/on/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/on/</link>
	<description></description>
	<lastBuildDate>Sun, 13 Dec 2020 22:02:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>O(n) Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/on/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1689-partitioning-into-minimum-number-of-deci-binary-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1689-partitioning-into-minimum-number-of-deci-binary-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Dec 2020 21:54:18 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7803</guid>

					<description><![CDATA[<p>A decimal number is called&#160;deci-binary&#160;if each of its digits is either&#160;0&#160;or&#160;1&#160;without any leading zeros. For example,&#160;101&#160;and&#160;1100&#160;are&#160;deci-binary, while&#160;112&#160;and&#160;3001&#160;are not. Given a string&#160;n&#160;that represents a positive decimal&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1689-partitioning-into-minimum-number-of-deci-binary-numbers/">花花酱 LeetCode 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A decimal number is called&nbsp;<strong>deci-binary</strong>&nbsp;if each of its digits is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>&nbsp;without any leading zeros. For example,&nbsp;<code>101</code>&nbsp;and&nbsp;<code>1100</code>&nbsp;are&nbsp;<strong>deci-binary</strong>, while&nbsp;<code>112</code>&nbsp;and&nbsp;<code>3001</code>&nbsp;are not.</p>



<p>Given a string&nbsp;<code>n</code>&nbsp;that represents a positive decimal integer, return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of positive&nbsp;<strong>deci-binary</strong>&nbsp;numbers needed so that they sum up to&nbsp;</em><code>n</code><em>.</em></p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = "32"
<strong>Output:</strong> 3
<strong>Explanation:</strong> 10 + 11 + 11 = 32
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = "82734"
<strong>Output:</strong> 8
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = "27346209830709182346"
<strong>Output:</strong> 9
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n.length &lt;= 10<sup>5</sup></code></li><li><code>n</code>&nbsp;consists of only digits.</li><li><code>n</code>&nbsp;does not contain any leading zeros and represents a positive integer.</li></ul>



<h2><strong>Solution: Return the max digit</strong></h2>



<p>Proof: For a given string, we find the maximum number m, we create m binary strings.<br>for each one, check each digit, if it&#8217;s greater than 0, we mark 1 at that position and decrease the digit by 1.</p>



<p>e.g. 21534<br>max is 5, we need five binary strings.<br>1. 11111: 21534 -> 10423<br>2. 10111: 10423 -> 00312<br>3: 00111: 00312 -> 00201<br>4: 00101: 00201 -> 00100<br>5: 00100: 00100 -> 00000</p>



<p>We can ignore the leading zeros.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minPartitions(string n) {
    return *max_element(begin(n), end(n)) - '0';
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1689-partitioning-into-minimum-number-of-deci-binary-numbers/">花花酱 LeetCode 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1689-partitioning-into-minimum-number-of-deci-binary-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Dec 2020 00:48:31 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7790</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;sorted in&#160;non-decreasing&#160;order. Build and return&#160;an integer array&#160;result&#160;with the same length as&#160;nums&#160;such that&#160;result[i]&#160;is equal to the&#160;summation of absolute differences&#160;between&#160;nums[i]&#160;and all the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/">花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;sorted in&nbsp;<strong>non-decreasing</strong>&nbsp;order.</p>



<p>Build and return&nbsp;<em>an integer array&nbsp;</em><code>result</code><em>&nbsp;with the same length as&nbsp;</em><code>nums</code><em>&nbsp;such that&nbsp;</em><code>result[i]</code><em>&nbsp;is equal to the&nbsp;<strong>summation of absolute differences</strong>&nbsp;between&nbsp;</em><code>nums[i]</code><em>&nbsp;and all the other elements in the array.</em></p>



<p>In other words,&nbsp;<code>result[i]</code>&nbsp;is equal to&nbsp;<code>sum(|nums[i]-nums[j]|)</code>&nbsp;where&nbsp;<code>0 &lt;= j &lt; nums.length</code>&nbsp;and&nbsp;<code>j != i</code>&nbsp;(<strong>0-indexed</strong>).</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,5]
<strong>Output:</strong> [4,3,5]
<strong>Explanation:</strong> Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,6,8,10]
<strong>Output:</strong> [24,15,13,15,21]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= nums[i + 1] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<p>Let s[i] denote sum(num[i] &#8211; num[j]) 0 &lt;= j &lt;= i<br>s[i] = s[i &#8211; 1] + (num[i] &#8211; num[i &#8211; 1]) * i<br>Let l[i] denote sum(nums[j] &#8211; nums[i]) i &lt;= j &lt; n<br>l[i] = l[i + 1] + (nums[i + 1] &#8211; num[i]) * (n &#8211; i &#8211; 1)<br>ans[i] = s[i] + l[i]</p>



<p>e.g. 1, 3, 7, 9<br>s[0] = 0<br>s[1] = 0 + (3 &#8211; 1) * 1 = 2<br>s[2] = 2 + (7 &#8211; 3) * 2 = 10<br>s[3] = 10 + (9 &#8211; 7) * 3 = 16<br>l[3] = 0<br>l[2] = 0 + (9 &#8211; 7) * 1 = 2<br>l[1] = 2 + (7 &#8211; 3) * 2 = 10<br>l[0] = 10 + (3 &#8211; 1) *  3 = 16</p>



<p>ans = [16, 12, 12, 16]</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; getSumAbsoluteDifferences(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; ans(n);    
    for (int i = 1, sum = 0; i &lt; n; ++i)
      ans[i] += (sum += (nums[i] - nums[i - 1]) * i);
    for (int i = n - 2, sum = 0; i &gt;= 0; --i)
      ans[i] += (sum += (nums[i + 1] - nums[i]) * (n - i - 1));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/">花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1629. Slowest Key</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1629-slowest-key/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1629-slowest-key/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Oct 2020 04:22:07 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7549</guid>

					<description><![CDATA[<p>A newly designed keypad was tested, where a tester pressed a sequence of&#160;n&#160;keys, one at a time. You are given a string&#160;keysPressed&#160;of length&#160;n, where&#160;keysPressed[i]&#160;was the&#160;ith&#160;key&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1629-slowest-key/">花花酱 LeetCode 1629. Slowest Key</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A newly designed keypad was tested, where a tester pressed a sequence of&nbsp;<code>n</code>&nbsp;keys, one at a time.</p>



<p>You are given a string&nbsp;<code>keysPressed</code>&nbsp;of length&nbsp;<code>n</code>, where&nbsp;<code>keysPressed[i]</code>&nbsp;was the&nbsp;<code>i<sup>th</sup></code>&nbsp;key pressed in the testing sequence, and a sorted list&nbsp;<code>releaseTimes</code>, where&nbsp;<code>releaseTimes[i]</code>&nbsp;was the time the&nbsp;<code>i<sup>th</sup></code>&nbsp;key was released. Both arrays are&nbsp;<strong>0-indexed</strong>. The&nbsp;<code>0<sup>th</sup></code>&nbsp;key was pressed at the time&nbsp;<code>0</code>,&nbsp;and every subsequent key was pressed at the&nbsp;<strong>exact</strong>&nbsp;time the previous key was released.</p>



<p>The tester wants to know the key of the keypress that had the&nbsp;<strong>longest duration</strong>. The&nbsp;<code>i<sup>th</sup></code>keypress had a&nbsp;<strong>duration</strong>&nbsp;of&nbsp;<code>releaseTimes[i] - releaseTimes[i - 1]</code>, and the&nbsp;<code>0<sup>th</sup></code>&nbsp;keypress had a duration of&nbsp;<code>releaseTimes[0]</code>.</p>



<p>Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key&nbsp;<strong>may not</strong>&nbsp;have had the same&nbsp;<strong>duration</strong>.</p>



<p><em>Return the key of the keypress that had the&nbsp;<strong>longest duration</strong>. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.</em></p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> releaseTimes = [9,29,49,50], keysPressed = "cbcd"
<strong>Output:</strong> "c"
<strong>Explanation:</strong> The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
<strong>Output:</strong> "a"
<strong>Explanation:</strong> The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>releaseTimes.length == n</code></li><li><code>keysPressed.length == n</code></li><li><code>2 &lt;= n &lt;= 1000</code></li><li><code>0 &lt;= releaseTimes[i] &lt;= 10<sup>9</sup></code></li><li><code>releaseTimes[i] &lt; releaseTimes[i+1]</code></li><li><code>keysPressed</code>&nbsp;contains only lowercase English letters.</li></ul>



<h2><strong>Solution: Straightforward</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre lang="C++">
class Solution {
public:
  char slowestKey(vector<int>& releaseTimes, string keysPressed) {
    int l = releaseTimes[0];
    char ans = keysPressed[0];
    
    for (int i = 1; i < releaseTimes.size(); ++i) {
      int t = releaseTimes[i] - releaseTimes[i - 1];
      if (t > l) { 
        ans = keysPressed[i]; 
        l = t;
      } else if (t == l) {
        ans = max(ans, keysPressed[i]);      
      }
    }
    return ans;
  }
};
<pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1629-slowest-key/">花花酱 LeetCode 1629. Slowest Key</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1629-slowest-key/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1413. Minimum Value to Get Positive Step by Step Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1413-minimum-value-to-get-positive-step-by-step-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1413-minimum-value-to-get-positive-step-by-step-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Apr 2020 18:17:06 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6629</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums, you start with an initial&#160;positive&#160;value&#160;startValue. In each iteration, you calculate the step by step sum of&#160;startValue&#160;plus&#160;elements in&#160;nums&#160;(from left to right).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1413-minimum-value-to-get-positive-step-by-step-sum/">花花酱 LeetCode 1413. Minimum Value to Get Positive Step by Step Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers&nbsp;<code>nums</code>, you start with an initial&nbsp;<strong>positive</strong>&nbsp;value&nbsp;<em>startValue</em><em>.</em></p>



<p>In each iteration, you calculate the step by step sum of&nbsp;<em>startValue</em>&nbsp;plus&nbsp;elements in&nbsp;<code>nums</code>&nbsp;(from left to right).</p>



<p>Return the minimum&nbsp;<strong>positive</strong>&nbsp;value of&nbsp;<em>startValue</em>&nbsp;such that the step by step sum is never less than 1.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-3,2,-3,4,2]
<strong>Output:</strong> 5
<strong>Explanation: </strong>If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
<strong>                step by step sum
&nbsp;               startValue = 4 | startValue = 5 | nums
</strong>&nbsp;                 (4 <strong>-3</strong> ) = 1  | (5 <strong>-3</strong> ) = 2    |  -3
&nbsp;                 (1 <strong>+2</strong> ) = 3  | (2 <strong>+2</strong> ) = 4    |   2
&nbsp;                 (3 <strong>-3</strong> ) = 0  | (4 <strong>-3</strong> ) = 1    |  -3
&nbsp;                 (0 <strong>+4</strong> ) = 4  | (1 <strong>+4</strong> ) = 5    |   4
&nbsp;                 (4 <strong>+2</strong> ) = 6  | (5 <strong>+2</strong> ) = 7    |   2
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Minimum start value should be positive. 
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-2,-3]
<strong>Output:</strong> 5
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 100</code></li><li><code>-100 &lt;= nums[i] &lt;= 100</code></li></ul>



<h2><strong>Solution: Prefix sum</strong></h2>



<p>Find the minimum prefix sum, ans = &#8211; min(prefix_sum, 0) + 1</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minStartValue(vector&lt;int&gt;&amp; nums) {
    int min_sum = 0;
    int sum = 0;
    for (int num : nums) {
      sum += num;
      min_sum = min(min_sum, sum);
    }
    return -min_sum + 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1413-minimum-value-to-get-positive-step-by-step-sum/">花花酱 LeetCode 1413. Minimum Value to Get Positive Step by Step Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1413-minimum-value-to-get-positive-step-by-step-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1404. Number of Steps to Reduce a Number in Binary Representation to One</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Apr 2020 07:22:53 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[big integer]]></category>
		<category><![CDATA[binary string]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[medieum]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6578</guid>

					<description><![CDATA[<p>Given a number&#160;s&#160;in their binary representation. Return the number of steps to reduce it to 1 under the following rules: If the current number is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/">花花酱 LeetCode 1404. Number of Steps to Reduce a Number in Binary Representation to One</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a number&nbsp;<code>s</code>&nbsp;in their binary representation. Return the number of steps to reduce it to 1 under the following rules:</p>



<ul><li>If the current number is even, you have to divide it by 2.</li><li>If the current number is odd, you have to add 1 to it.</li></ul>



<p>It&#8217;s guaranteed that you can always reach to one for all testcases.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1101"
<strong>Output:</strong> 6
<strong>Explanation:</strong> "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.&nbsp;
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.&nbsp; 
Step 5) 4 is even, divide by 2 and obtain 2.&nbsp;
Step 6) 2 is even, divide by 2 and obtain 1.&nbsp; 
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.&nbsp; 
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1"
<strong>Output:</strong> 0
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length&nbsp;&lt;= 500</code></li><li><code>s</code>&nbsp;consists of characters &#8216;0&#8217; or &#8216;1&#8217;</li><li><code>s[0] == '1'</code></li></ul>



<h2><strong>Solution: Simulation</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numSteps(string s) {
    int ans = 0;
    int carry = 0;
    // The highest bit must be 1, 
    // process to the 2nd highest bit
    for (int i = s.length() - 1; i &gt; 0; --i) {
      if (s[i] - '0' + carry == 1) {
        ans += 2; // odd: +1, even: / 2
        carry = 1; // always has a carry
      } else {
        ans += 1; // even: / 2
        // carray remains e.g. 1 + 1 = 10, or 0 + 0 = 00
      }
    }
    // If there is a carry, then it's even, one more step.
    return ans + carry;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def numSteps(self, s: str) -&gt; int:
    ans, carry = 0, 0
    for i in range(1, len(s)):
      if ord(s[-i]) - ord('0') + carry == 1:
        ans += 2
        carry = 1
      else:
        ans += 1
    return ans + carry</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/">花花酱 LeetCode 1404. Number of Steps to Reduce a Number in Binary Representation to One</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/bit/leetcode-1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1375. Bulb Switcher III</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1375-bulb-switcher-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1375-bulb-switcher-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 18:54:20 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6415</guid>

					<description><![CDATA[<p>There is a room with&#160;n&#160;bulbs, numbered from&#160;1&#160;to&#160;n, arranged in a row from left to right. Initially, all the bulbs are turned off. At moment&#160;k&#160;(for&#160;k&#160;from&#160;0&#160;to&#160;n -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1375-bulb-switcher-iii/">花花酱 LeetCode 1375. Bulb Switcher III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a room with&nbsp;<code>n</code>&nbsp;bulbs, numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>, arranged in a row from left to right. Initially, all the bulbs are turned off.</p>



<p>At moment&nbsp;<em>k</em>&nbsp;(for&nbsp;<em>k</em>&nbsp;from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>), we turn on the&nbsp;<code>light[k]</code>&nbsp;bulb. A bulb&nbsp;<strong>change&nbsp;color to blue</strong>&nbsp;only if it is on and all the previous bulbs (to the left)&nbsp;are turned on too.</p>



<p>Return the number of moments in&nbsp;which&nbsp;<strong>all&nbsp;turned on</strong>&nbsp;bulbs&nbsp;<strong>are blue.</strong></p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/29/sample_2_1725.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> light = [2,1,3,5,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> All bulbs turned on, are blue at the moment 1, 2 and 4.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> light = [3,2,4,1,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> All bulbs turned on, are blue at the moment 3, and 4 (index-0).
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> light = [4,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> All bulbs turned on, are blue at the moment 3 (index-0).
Bulb 4th changes to blue at the moment 3.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> light = [2,1,4,3,6,5]
<strong>Output:</strong> 3
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> light = [1,2,3,4,5,6]
<strong>Output:</strong> 6
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>n ==&nbsp;light.length</code></li><li><code>1 &lt;= n &lt;= 5 * 10^4</code></li><li><code>light</code>&nbsp;is a permutation of&nbsp;&nbsp;<code>[1, 2, ..., n]</code></li></ul>



<h2><strong>Solution</strong></h2>



<p>Track the right most light l_k, all turned-on lights are blue if and only if the right most one is k, and there are exact k lights on right now.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numTimesAllBlue(vector&lt;int&gt;&amp; light) {    
    int ans = 0;
    int right = 0;
    for (int i = 0; i &lt; light.size(); ++i) {
      right = max(right, light[i]);
      ans += right == i + 1;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1375-bulb-switcher-iii/">花花酱 LeetCode 1375. Bulb Switcher III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1375-bulb-switcher-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1374. Generate a String With Characters That Have Odd Counts</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1374-generate-a-string-with-characters-that-have-odd-counts/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1374-generate-a-string-with-characters-that-have-odd-counts/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 18:19:38 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6412</guid>

					<description><![CDATA[<p>Given an&#160;integer&#160;n,&#160;return a string with&#160;n&#160;characters such that each character in such string occurs&#160;an odd number of times. The returned string must contain only lowercase English&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1374-generate-a-string-with-characters-that-have-odd-counts/">花花酱 LeetCode 1374. Generate a String With Characters That Have Odd Counts</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an&nbsp;integer&nbsp;<code>n</code>,&nbsp;<em>return a string with&nbsp;<code>n</code>&nbsp;characters such that each character in such string occurs&nbsp;<strong>an odd number of times</strong></em>.</p>



<p>The returned string must contain only lowercase English letters. If there are multiples valid strings, return&nbsp;<strong>any</strong>&nbsp;of them. &nbsp;</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4
<strong>Output:</strong> "pppz"
<strong>Explanation:</strong> "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> "xy"
<strong>Explanation:</strong> "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7
<strong>Output:</strong> "holasss"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 500</code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>if n is odd, return n &#8216;a&#8217;s.<br>otherwise, return n -1 &#8216;a&#8217;s and 1 &#8216;b&#8217;</p>



<p>Time complexity: O(n)<br>Space complexity: O(n) or O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string generateTheString(int n) {    
    return n &amp;amp; 1 ? string(n, 'a') : string(n - 1, 'a') + &quot;b&quot;;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def generateTheString(self, n: int) -&amp;gt; str:
    ans = ['a'] * n if n % 2 == 1 else ['a'] * (n - 1) + ['b']
    return ''.join(ans)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1374-generate-a-string-with-characters-that-have-odd-counts/">花花酱 LeetCode 1374. Generate a String With Characters That Have Odd Counts</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1374-generate-a-string-with-characters-that-have-odd-counts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1372. Longest ZigZag Path in a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 08:53:52 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[longest path]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6405</guid>

					<description><![CDATA[<p>Given a binary tree&#160;root, a&#160;ZigZag path for a binary tree is defined as follow: Choose&#160;any&#160;node in the binary tree and a direction (right or left).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/">花花酱 LeetCode 1372. Longest ZigZag Path in a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary tree&nbsp;<code>root</code>, a&nbsp;ZigZag path for a binary tree is defined as follow:</p>



<ul><li>Choose&nbsp;<strong>any&nbsp;</strong>node in the binary tree and a direction (right or left).</li><li>If the current direction is right then move to the right child of the current node otherwise move to the left child.</li><li>Change the direction from right to left or right to left.</li><li>Repeat the second and third step until you can&#8217;t move in the tree.</li></ul>



<p>Zigzag length is defined as the number of nodes visited &#8211; 1. (A single node has a length of 0).</p>



<p>Return&nbsp;the longest&nbsp;<strong>ZigZag</strong>&nbsp;path contained in that tree.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Longest ZigZag path in blue nodes (right -&gt; left -&gt; right).
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,1,1,null,1,null,null,1,1,null,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Longest ZigZag path in blue nodes (left -&gt; right -&gt; left -&gt; right).
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1]
<strong>Output:</strong> 0
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>Each tree has at most&nbsp;<code>50000</code>&nbsp;nodes..</li><li>Each node&#8217;s value is between&nbsp;<code>[1, 100]</code>.</li></ul>



<h2><strong>Solution: Recursion</strong></h2>



<p>For each node return <br>1. max ZigZag length if go left<br>2. max ZigZag length if go right<br>3. maz ZigZag length within the subtree<br><br>ZigZag(root):<br>  ll, lr, lm = ZigZag(root.left)<br>  rl, rr, rm = ZigZag(root.right)<br>return (lr+1, rl + 1, max(lr+1, rl+1, lm, rm))</p>



<p>Time complexity: O(n)<br>Space complexity: O(h)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestZigZag(TreeNode* root) {    
    return get&lt;2&gt;(ZigZag(root));
  }
    
  // Returns {left, right, max}
  tuple&lt;int, int, int&gt; ZigZag(TreeNode* root) {
    if (!root) return {-1, -1, -1};
    auto [ll, lr, lm] = ZigZag(root-&gt;left);
    auto [rl, rr, rm] = ZigZag(root-&gt;right);
    int l = lr + 1;
    int r = rl + 1;
    return {l, r, max({l, r, lm, rm})};
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def longestZigZag(self, root: TreeNode) -&gt; int:
    def ZigZag(node):
      if not node: return (-1, -1, -1)
      ll, lr, lm = ZigZag(node.left)
      rl, rr, rm = ZigZag(node.right)
      return (lr + 1, rl + 1, max(lr + 1, rl + 1, lm, rm))
    return ZigZag(root)[2]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/">花花酱 LeetCode 1372. Longest ZigZag Path in a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 108. Convert Sorted Array to Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Feb 2020 18:54:12 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6244</guid>

					<description><![CDATA[<p>Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/">花花酱 LeetCode 108. Convert Sorted Array to Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 108 Convert Sorted Array to Binary Search Tree - 刷题找工作 EP306" width="500" height="375" src="https://www.youtube.com/embed/O5BSAhg4n0M?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array where elements are sorted in ascending order, convert it to a height balanced BST.</p>



<p>For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of&nbsp;<em>every</em>&nbsp;node never differ by more than 1.</p>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted;crayon:false">Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5</pre>



<h2><strong>Solution: Recursion</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/02/108-ep306.png" alt="" class="wp-image-6261" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/02/108-ep306.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/02/108-ep306-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/02/108-ep306-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Recursively build a BST for a given range.</p>



<p>def build(nums, l, r):<br>  if l &gt; r: return None<br>  m = l + (r &#8211; l) / 2<br>  root = TreeNode(nums[m])<br>  root.left = build(nums, l, m &#8211; 1)<br>  root.right = build(nums, m + 1, r)<br>  return root<br><br>return build(nums, 0, len(nums) &#8211; 1)</p>



<p>Time complexity: O(n)<br>Space complexity: O(logn)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  TreeNode* sortedArrayToBST(vector&lt;int&gt;&amp; nums) {
    function&lt;TreeNode*(int l, int r)&gt; build = [&amp;](int l, int r) {
      if (l &gt; r) return static_cast&lt;TreeNode*&gt;(nullptr);      
      int m = l + (r - l) / 2;
      TreeNode* root = new TreeNode(nums[m]);
      root-&gt;left = build(l, m - 1);
      root-&gt;right = build(m + 1, r);
      return root;
    };
    return build(0, nums.size() - 1);
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public TreeNode sortedArrayToBST(int[] nums) {
    return buildBST(nums, 0, nums.length - 1);
  }
  
  private TreeNode buildBST(int[] nums, int l, int r) {
    if (l &gt; r) return null;
    int m = l + (r - l) / 2;
    TreeNode root = new TreeNode(nums[m]);
    root.left = buildBST(nums, l, m - 1);
    root.right = buildBST(nums, m + 1, r);
    return root;
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def sortedArrayToBST(self, nums: List[int]) -&gt; TreeNode:
    def buildBST(l: int, r: int) -&gt; TreeNode:
      if l &gt; r: return None
      m = l + (r - l) // 2
      root = TreeNode(nums[m])
      root.left = buildBST(l, m - 1)
      root.right = buildBST(m + 1, r)
      return root
    return buildBST(0, len(nums) - 1)</pre>

</div><h2 class="tabtitle">JavaScript</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
var sortedArrayToBST = function(nums) {
  var buildBST = function(l, r) {    
    if (l &gt; r) return null;
    let m = l + Math.floor((r - l) / 2);
    let root = new TreeNode(nums[m]);
    root.left = buildBST(l, m - 1);
    root.right = buildBST(m + 1, r);
    return root;
  }
  return buildBST(0, nums.length - 1);
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/">花花酱 LeetCode 108. Convert Sorted Array to Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 912. Sort an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Feb 2020 17:49:53 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[heapsort]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6226</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/">花花酱 LeetCode 912. Sort an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers&nbsp;<code>nums</code>, sort the array in ascending order.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,2,3,1]
<strong>Output:</strong> [1,2,3,5]
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,1,1,2,0,0]
<strong>Output:</strong> [0,0,1,1,2,5]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 50000</code></li><li><code>-50000 &lt;= nums[i] &lt;= 50000</code></li></ul>



<p>Since n &lt;= 50000, any O(n^2) won&#8217;t pass, we need O(nlogn) or better</p>



<h2><strong>Solution 1: QuickSort</strong></h2>



<p>Time complexity: O(nlogn) ~ O(n^2)<br>Space complexity: O(logn) ~ O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 60 ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    function&lt;void(int, int)&gt; quickSort = [&amp;](int l, int r) {
      if (l &gt;= r) return;      
      int i = l;
      int j = r;
      int p = nums[l + rand() % (r - l + 1)];
      while (i &lt;= j) {
        while (nums[i] &lt; p) ++i;
        while (nums[j] &gt; p) --j;
        if (i &lt;= j)
          swap(nums[i++], nums[j--]);
      }
      quickSort(l, j);
      quickSort(i, r);
    };
    quickSort(0, nums.size() - 1);
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Counting Sort</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(max(nums) &#8211; min(nums))</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 54 ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    auto [min_it, max_it] = minmax_element(begin(nums), end(nums));
    int l = *min_it, r = *max_it;
    vector&lt;int&gt; count(r - l + 1);
    for (int n : nums) ++count[n - l];
    int index = 0;
    for (int i = 0; i &lt; count.size(); ++i)
      while (count[i]--) nums[index++] = i + l;
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: HeapSort</strong></h2>



<p>Time complexity: O(nlogn)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 72ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    priority_queue&lt;int&gt; q(begin(nums), end(nums));
    int i = nums.size();
    while (!q.empty()) {
      nums[--i] = q.top();
      q.pop();
    }
    return nums;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    auto heapify = [&amp;](int i, int e) {
      while (i &lt;= e) {
        int l = 2 * i + 1;
        int r = 2 * i + 2;
        int j = i;
        if (l &lt;= e &amp;&amp; nums[l] &gt; nums[j]) j = l;
        if (r &lt;= e &amp;&amp; nums[r] &gt; nums[j]) j = r;
        if (j == i) break;
        swap(nums[i], nums[j]);
        swap(i, j);
      }
    };
    
    const int n = nums.size();
    
    // Init heap
    for (int i = n / 2; i &gt;= 0; i--)
      heapify(i, n - 1);
    
    // Get min.
    for (int i = n - 1; i &gt;= 1; i--) {
      swap(nums[0], nums[i]);
      heapify(0, i - 1);    
    }
    
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 3: MergeSort</strong></h2>



<p>Time complexity: O(nlogn)<br>Space complexity: O(logn + n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; t(nums.size());
    function&lt;void(int, int)&gt; mergeSort = [&amp;](int l, int r) {
      if (l + 1 &gt;= r) return;
      int m = l + (r - l) / 2;
      mergeSort(l, m);
      mergeSort(m, r);
      int i1 = l;
      int i2 = m;
      int index = 0;
      while (i1 &lt; m || i2 &lt; r)
        if (i2 == r || (i1 &lt; m &amp;&amp; nums[i1] &lt; nums[i2]))
          t[index++] = nums[i1++];
        else
          t[index++] = nums[i2++];      
      std::copy(begin(t), begin(t) + index, begin(nums) + l);
    };
    
    mergeSort(0, nums.size());
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 4: BST</strong></h2>



<p>Time complexity: (nlogn)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    multiset&lt;int&gt; s(begin(nums), end(nums));
    return {begin(s), end(s)};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/">花花酱 LeetCode 912. Sort an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1302. Deepest Leaves Sum</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1302-deepest-leaves-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1302-deepest-leaves-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Feb 2020 07:39:46 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6221</guid>

					<description><![CDATA[<p>Given a binary tree, return the sum of values of its deepest leaves. Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Constraints: The number of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1302-deepest-leaves-sum/">花花酱 LeetCode 1302. Deepest Leaves Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary tree, return the sum of values of its deepest leaves.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
<strong>Output:</strong> 15
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>The number of nodes in the tree is between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>10^4</code>.</li><li>The value of nodes is between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>100</code>.</li></ul>



<h2><strong>Solution 1: Recursion</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int deepestLeavesSum(TreeNode* root) {
    int sum = 0;
    int max_depth = 0;
    function&lt;void(TreeNode*, int)&gt; dfs = [&amp;](TreeNode* n, int d) {
      if (!n) return;
      if (d &gt; max_depth) {
        max_depth = d;
        sum = 0;
      }
      if (d == max_depth) sum += n-&gt;val;
      dfs(n-&gt;left, d + 1);
      dfs(n-&gt;right, d + 1);
    };
    dfs(root, 0);
    return sum;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1302-deepest-leaves-sum/">花花酱 LeetCode 1302. Deepest Leaves Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-1302-deepest-leaves-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 35. Search Insert Position</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-35-search-insert-position/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-35-search-insert-position/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Feb 2020 06:01:52 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6213</guid>

					<description><![CDATA[<p>Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-35-search-insert-position/">花花酱 LeetCode 35. Search Insert Position</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p>



<p>You may assume no duplicates in the array.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,3,5,6], 5
<strong>Output:</strong> 2
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,3,5,6], 2
<strong>Output:</strong> 1
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,3,5,6], 7
<strong>Output:</strong> 4
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,3,5,6], 0
<strong>Output:</strong> 0</pre>



<h2><strong>Solution: Binary Search</strong></h2>



<p>Find the number or upper bound if doesn&#8217;t exist.</p>



<p>Time complexity: O(logn)<br>Space complexity: O1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int searchInsert(vector&lt;int&gt;&amp; nums, int target) {
    int l = 0, r = nums.size();
    while (l &lt; r) {
      int m = l + (r - l) / 2;      
      if (nums[m] == target)
        return m;
      else if (nums[m] &gt; target)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-35-search-insert-position/">花花酱 LeetCode 35. Search Insert Position</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-35-search-insert-position/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 138. Copy List with Random Pointer</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 04:12:20 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6178</guid>

					<description><![CDATA[<p>A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/">花花酱 LeetCode 138. Copy List with Random Pointer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.</p>



<p>Return a&nbsp;<a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank" rel="noreferrer noopener"><strong>deep copy</strong></a>&nbsp;of the list.</p>



<p>The Linked List is represented in the input/output as a list of&nbsp;<code>n</code>&nbsp;nodes. Each node is represented as a pair of&nbsp;<code>[val, random_index]</code>&nbsp;where:</p>



<ul><li><code>val</code>: an integer representing&nbsp;<code>Node.val</code></li><li><code>random_index</code>: the index of the node (range from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n-1</code>) where random pointer points to, or&nbsp;<code>null</code>&nbsp;if it does not point to any node.</li></ul>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/18/e1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/18/e2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/18/e3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = []
<strong>Output:</strong> []
<strong>Explanation:</strong> Given linked list is empty (null pointer), so return null.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>-10000 &lt;= Node.val &lt;= 10000</code></li><li><code>Node.random</code>&nbsp;is null or pointing to a node in the linked list.</li><li>Number of Nodes will not exceed 1000.</li></ul>



<h2><strong>Solution: Hashtable</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  Node* copyRandomList(Node* head) {
    if (!head) return head;

    unordered_map&lt;Node*, Node*&gt; m;    
    Node* cur = m[head] = new Node(head-&gt;val);
    Node* ans = cur;

    while (head) {
      if (head-&gt;random) {
        auto it = m.find(head-&gt;random);
        if (it == end(m))
          it = m.emplace(head-&gt;random, new Node(head-&gt;random-&gt;val)).first;
        cur-&gt;random = it-&gt;second;
      }

      if (head-&gt;next) {
        auto it = m.find(head-&gt;next);
        if (it == end(m))
          it = m.emplace(head-&gt;next, new Node(head-&gt;next-&gt;val)).first;        
        cur-&gt;next = it-&gt;second;
      }

      head = head-&gt;next;
      cur = cur-&gt;next;
    }
    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/">花花酱 LeetCode 138. Copy List with Random Pointer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 03:31:48 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6174</guid>

					<description><![CDATA[<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the&#160;definition of LCA on&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/">花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.</p>



<p>According to the&nbsp;<a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank" rel="noreferrer noopener">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes p and q&nbsp;as the lowest node in T that has both p and q&nbsp;as descendants (where we allow&nbsp;<strong>a node to be a descendant of itself</strong>).”</p>



<p>Given binary search tree:&nbsp; root =&nbsp;[6,2,8,0,4,7,9,null,null,3,5]</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" alt=""/></figure>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
<strong>Output:</strong> 6
<strong>Explanation: </strong>The LCA of nodes <code>2</code> and <code>8</code> is <code>6</code>.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
<strong>Output:</strong> 2
<strong>Explanation: </strong>The LCA of nodes <code>2</code> and <code>4</code> is <code>2</code>, since a node can be a descendant of itself according to the LCA definition.
</pre>



<p><strong>Note:</strong></p>



<ul><li>All of the nodes&#8217; values will be unique.</li><li>p and q are different and both values will&nbsp;exist in the BST.</li></ul>



<h2><strong>Solution: Recursion</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {    
    if (p-&gt;val &lt; root-&gt;val &amp;&amp; q-&gt;val &lt; root-&gt;val) 
      return lowestCommonAncestor(root-&gt;left, p, q);
    if (p-&gt;val &gt; root-&gt;val &amp;&amp; q-&gt;val &gt; root-&gt;val)
      return lowestCommonAncestor(root-&gt;right, p, q);
    return root;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/">花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 257. Binary Tree Paths</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-257-binary-tree-paths/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-257-binary-tree-paths/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 03:19:37 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6171</guid>

					<description><![CDATA[<p>Given a binary tree, return all root-to-leaf paths. Note:&#160;A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-257-binary-tree-paths/">花花酱 LeetCode 257. Binary Tree Paths</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary tree, return all root-to-leaf paths.</p>



<p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong>

   1
 /   \
2     3
 \
  5

<strong>Output:</strong> ["1-&gt;2-&gt;5", "1-&gt;3"]

<strong>Explanation:</strong> All root-to-leaf paths are: 1-&gt;2-&gt;5, 1-&gt;3</pre>



<h2><strong>Solution: Recursion</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n) / output can be O(n^2)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;string&gt; binaryTreePaths(TreeNode* root) {
    vector&lt;string&gt; ans;
    string s;
    function&lt;void(TreeNode*, int)&gt; preorder = [&amp;](TreeNode* node, int l) {
      if (!node) return;
      s += (l &gt; 0 ? &quot;-&gt;&quot; : &quot;&quot;) + to_string(node-&gt;val);
      if (!node-&gt;left &amp;&amp; !node-&gt;right)
        ans.push_back(s);
      preorder(node-&gt;left, s.size());
      preorder(node-&gt;right, s.size());
      while (s.size() != l) s.pop_back();
    };
    preorder(root, 0);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-257-binary-tree-paths/">花花酱 LeetCode 257. Binary Tree Paths</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-257-binary-tree-paths/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
