<?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>swap Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/swap/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/swap/</link>
	<description></description>
	<lastBuildDate>Thu, 05 Aug 2021 05:30:31 +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>swap Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/swap/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1864-minimum-number-of-swaps-to-make-the-binary-string-alternating/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1864-minimum-number-of-swaps-to-make-the-binary-string-alternating/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 05 Aug 2021 05:29:11 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[alternating]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8467</guid>

					<description><![CDATA[<p>Given a binary string&#160;s, return&#160;the&#160;minimum&#160;number of character swaps to make it&#160;alternating, or&#160;-1&#160;if it is impossible. The string is called&#160;alternating&#160;if no two adjacent characters are equal.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1864-minimum-number-of-swaps-to-make-the-binary-string-alternating/">花花酱 LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating</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 string&nbsp;<code>s</code>, return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of character swaps to make it&nbsp;<strong>alternating</strong>, or&nbsp;</em><code>-1</code><em>&nbsp;if it is impossible.</em></p>



<p>The string is called&nbsp;<strong>alternating</strong>&nbsp;if no two adjacent characters are equal. For example, the strings&nbsp;<code>"010"</code>&nbsp;and&nbsp;<code>"1010"</code>&nbsp;are alternating, while the string&nbsp;<code>"0100"</code>&nbsp;is not.</p>



<p>Any two characters may be swapped, even if they are&nbsp;<strong>not adjacent</strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "111000"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Swap positions 1 and 4: "111000" -&gt; "101010"
The string is now alternating.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "010"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The string is already alternating, no swaps are needed.
</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 1000</code></li><li><code>s[i]</code>&nbsp;is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code>.</li></ul>



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



<p>Two passes, make the string starts with &#8216;0&#8217; or &#8216;1&#8217;, count how many 0/1 swaps needed. 0/1 swaps must equal otherwise it&#8217;s impossible to swap.</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 minSwaps(string s) {    
    auto count = [&amp;](int m) {
      vector&lt;int&gt; swaps(2);
      for (int i = 0; i &lt; s.length(); ++i, m ^= 1)
        if (s[i] - '0' != m)
          ++swaps[s[i] - '0'];
      return swaps[0] == swaps[1] ? swaps[0] : INT_MAX;
    };
    
    int ans = min(count(0), count(1));
    return ans != INT_MAX ? ans : -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1864-minimum-number-of-swaps-to-make-the-binary-string-alternating/">花花酱 LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating</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/greedy/leetcode-1864-minimum-number-of-swaps-to-make-the-binary-string-alternating/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1721. Swapping Nodes in a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 17:59:01 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7964</guid>

					<description><![CDATA[<p>You are given the&#160;head&#160;of a linked list, and an integer&#160;k. Return&#160;the head of the linked list after&#160;swapping&#160;the values of the&#160;kth&#160;node from the beginning and the&#160;kth&#160;node&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/">花花酱 LeetCode 1721. Swapping Nodes in a Linked List</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 the&nbsp;<code>head</code>&nbsp;of a linked list, and an integer&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>the head of the linked list after&nbsp;<strong>swapping</strong>&nbsp;the values of the&nbsp;</em><code>k<sup>th</sup></code>&nbsp;<em>node from the beginning and the&nbsp;</em><code>k<sup>th</sup></code>&nbsp;<em>node from the end (the list is&nbsp;<strong>1-indexed</strong>).</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" alt=""/></figure>



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



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



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



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



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



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



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



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



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



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



<ul><li>The number of nodes in the list is&nbsp;<code>n</code>.</li><li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= Node.val &lt;= 100</code></li></ul>



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



<p>Two passes. First pass, find the length of the list. Second pass, record the k-th and n-k+1-th node.<br>Once done swap their values.</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">class Solution {
public:
  ListNode* swapNodes(ListNode* head, int k) {
    int l = 0;
    ListNode* cur = head;    
    while (cur) { cur = cur-&gt;next; ++l; }    
    
    cur = head;
    ListNode* n1 = nullptr;
    ListNode* n2 = nullptr;
    for (int i = 1; i &lt;= l; ++i, cur = cur-&gt;next) {
      if (i == k) n1 = cur;
      if (i == l - k + 1) n2 = cur;
    }
    swap(n1-&gt;val, n2-&gt;val);
    return head;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/">花花酱 LeetCode 1721. Swapping Nodes in a Linked List</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/list/leetcode-1721-swapping-nodes-in-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Jul 2020 15:29:08 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7025</guid>

					<description><![CDATA[<p>Given an array of numbers&#160;arr.&#160;A sequence of numbers is called an arithmetic progression&#160;if the difference between any two consecutive elements is the same. Return&#160;true&#160;if the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/">花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</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 numbers&nbsp;<code>arr</code>.&nbsp;A sequence of numbers is called an arithmetic progression&nbsp;if the difference between any two consecutive elements is the same.</p>



<p>Return&nbsp;<code>true</code>&nbsp;if the array can be rearranged to form an arithmetic progression, otherwise, return&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,5,1]
<strong>Output:</strong> true
<strong>Explanation: </strong>We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,4]
<strong>Output:</strong> false
<strong>Explanation: </strong>There is no way to reorder the elements to obtain an arithmetic progression.
</pre>



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



<ul><li><code>2 &lt;= arr.length &lt;= 1000</code></li><li><code>-10^6 &lt;= arr[i] &lt;= 10^6</code></li></ul>



<h2><strong>Solution 1: Sort and check.</strong></h2>



<p>Time complexity: O(nlog)<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:
  bool canMakeArithmeticProgression(vector&lt;int&gt;&amp; arr) {
    sort(begin(arr), end(arr));
    const int diff = arr[1] - arr[0];
    for (int i = 2; i &lt; arr.size(); ++i)
      if (arr[i] - arr[i - 1] != diff) return false;
    return true;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public boolean canMakeArithmeticProgression(int[] arr) {
    Arrays.sort(arr);
    int diff = arr[1] - arr[0];
    for (int i = 2; i &lt; arr.length; ++i)
      if (arr[i] - arr[i - 1] != diff) return false;
    return true;
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def canMakeArithmeticProgression(self, arr: List[int]) -&gt; bool:
    arr.sort()
    diff = arr[1] - arr[0]
    return all(i - j == diff for i, j in zip(arr[1:], arr[:-1]))</pre>
</div></div>



<h2><strong>Solution 2: Rearrange the array</strong></h2>



<p>Find min / max / diff and put each element into its correct position by swapping elements in place.</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:
  bool canMakeArithmeticProgression(vector&lt;int&gt;&amp; arr) {
    const int n = arr.size();
    const auto [loit, hiit] = minmax_element(cbegin(arr), cend(arr));
    const auto [lo, hi] = pair{*loit, *hiit};
    if ((hi - lo) % (n - 1)) return false;
    const int diff = (hi - lo) / (n - 1);
    if (diff == 0) return true;
    for (int i = 0; i &lt; n; ++i) {
      if ((arr[i] - lo) % diff) return false;
      const int idx = (arr[i] - lo) / diff;
      if (idx != i) swap(arr[i--], arr[idx]);
    }
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/">花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</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-1502-can-make-arithmetic-progression-from-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1187. Make Array Strictly Increasing</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1187-make-array-strictly-increasing/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1187-make-array-strictly-increasing/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Sep 2019 04:33:58 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5537</guid>

					<description><![CDATA[<p>Given two integer arrays&#160;arr1&#160;and&#160;arr2, return the minimum number of operations (possibly zero) needed&#160;to make&#160;arr1&#160;strictly increasing. In one operation, you can choose two indices&#160;0 &#60;=&#160;i &#60;&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1187-make-array-strictly-increasing/">花花酱 LeetCode 1187. Make Array Strictly Increasing</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 width="500" height="375" src="https://www.youtube.com/embed/8ttxdMCU2GE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given two integer arrays&nbsp;<code>arr1</code>&nbsp;and&nbsp;<code>arr2</code>, return the minimum number of operations (possibly zero) needed&nbsp;to make&nbsp;<code>arr1</code>&nbsp;strictly increasing.</p>



<p>In one operation, you can choose two indices&nbsp;<code>0 &lt;=&nbsp;i &lt; arr1.length</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt; arr2.length</code>&nbsp;and do the assignment&nbsp;<code>arr1[i] = arr2[j]</code>.</p>



<p>If there is no way to make&nbsp;<code>arr1</code>&nbsp;strictly increasing,&nbsp;return&nbsp;<code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Replace <code>5</code> with <code>2</code>, then <code>arr1 = [1, 2, 3, 6, 7]</code>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [1,5,3,6,7], arr2 = [4,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Replace <code>5</code> with <code>3</code> and then replace <code>3</code> with <code>4</code>. <code>arr1 = [1, 3, 4, 6, 7]</code>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> You can't make <code>arr1</code> strictly increasing.</pre>



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



<ul><li><code>1 &lt;= arr1.length, arr2.length &lt;= 2000</code></li><li><code>0 &lt;= arr1[i], arr2[i] &lt;= 10^9</code></li></ul>



<p><strong>Solution: DP</strong></p>



<p>Time complexity: O(mn)<br>Space complexity: O(mn) -&gt; O(m + 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 makeArrayIncreasing(vector&lt;int&gt;&amp; a, vector&lt;int&gt;&amp; c) {
    constexpr int kInf = 1e9;
    int m = a.size();    
    // Sort b and make it only containing unique numbers.
    sort(begin(c), end(c));
    vector&lt;int&gt; b;
    for (int i = 0; i &lt; c.size(); ++i) {
      if (!b.empty() &amp;&amp; c[i] == b.back()) continue;
      b.push_back(c[i]);
    }    
    int n = b.size();
    
    // min steps to make a[0~i] valid by keeping a[i]
    vector&lt;int&gt; keep(m, kInf);
    keep[0] = 0;
    // swap[i][j] := min steps to make a[0~i] valid by a[i] = b[j]
    vector&lt;int&gt; swap(n, 1);
    
    for (int i = 1; i &lt; m; ++i) {
      int min_keep = kInf;
      int min_swap = kInf;
      vector&lt;int&gt; temp(n, kInf);
      for (int j = 0; j &lt; n; ++j) {
        if (j &gt; 0) min_swap = min(min_swap, swap[j - 1] + 1);
        if (a[i] &gt; b[j]) min_keep = min(min_keep, swap[j]);        
        if (a[i] &gt; a[i - 1]) keep[i] = keep[i - 1];
        if (b[j] &gt; a[i - 1]) temp[j] = keep[i - 1] + 1;        
        temp[j] = min(temp[j], min_swap);
        keep[i] = min(keep[i], min_keep);
      }
      temp.swap(swap);
    }
    
    int s = *min_element(begin(swap), end(swap));
    int k = keep.back();
    int ans = min(s, k);
    return ans &gt;= kInf ? -1 : ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1187-make-array-strictly-increasing/">花花酱 LeetCode 1187. Make Array Strictly Increasing</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/dynamic-programming/leetcode-1187-make-array-strictly-increasing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 971. Flip Binary Tree To Match Preorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Jan 2019 04:53:57 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[swap]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4611</guid>

					<description><![CDATA[<p>Given a binary tree with&#160;N&#160;nodes, each node has a different value from&#160;{1, ..., N}. A node in this binary tree can be&#160;flipped&#160;by swapping the left&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/">花花酱 LeetCode 971. Flip Binary Tree To Match Preorder Traversal</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 with&nbsp;<code>N</code>&nbsp;nodes, each node has a different value from&nbsp;<code>{1, ..., N}</code>.</p>



<p>A node in this binary tree can be&nbsp;<em>flipped</em>&nbsp;by swapping the left child and the right child of that node.</p>



<p>Consider the sequence of&nbsp;<code>N</code>&nbsp;values reported by a preorder traversal starting from the root.&nbsp; Call such a sequence of&nbsp;<code>N</code>&nbsp;values the&nbsp;<em>voyage</em>&nbsp;of the tree.</p>



<p>(Recall that a&nbsp;<em>preorder traversal</em>&nbsp;of a node means we report the current node&#8217;s value, then preorder-traverse the left child, then preorder-traverse the right child.)</p>



<p>Our goal is to flip the&nbsp;<strong>least number</strong>&nbsp;of nodes in the tree so that the voyage of the tree matches the&nbsp;<code>voyage</code>we are given.</p>



<p>If we can do so, then return a&nbsp;list&nbsp;of the values of all nodes flipped.&nbsp; You may return the answer in any order.</p>



<p>If we cannot do so, then return the list&nbsp;<code>[-1]</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" alt=""/></figure>



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



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



<ol><li><code>1 &lt;= N &lt;= 100</code></li></ol>



<h2>Solution: Pre-order traversal</h2>



<p>if root-&gt;val != v[pos] return [-1]<br>if root-&gt;left?-&gt;val != v[pos + 1], swap the nodes</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  vector&lt;int&gt; flipMatchVoyage(TreeNode* root, vector&lt;int&gt;&amp; voyage) {
    vector&lt;int&gt; flips;
    int pos = 0;
    solve(root, voyage, pos, flips);
    return flips;
  }
private:
  void solve(TreeNode* root, const vector&lt;int&gt;&amp; voyage, int&amp; pos, vector&lt;int&gt;&amp; flips) {
    if (!root) return;
    if (root-&gt;val != voyage.at(pos)) {
      flips.clear();
      flips.push_back(-1);
      return;
    }
    if (root-&gt;left &amp;&amp; root-&gt;left-&gt;val != voyage.at(pos + 1)) {
      swap(root-&gt;left, root-&gt;right);
      flips.push_back(root-&gt;val);
    }
    ++pos;
    solve(root-&gt;left, voyage, pos, flips);
    solve(root-&gt;right, voyage, pos, flips);   
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, 60 ms
class Solution:
  def flipMatchVoyage(self, root, voyage):
    self.pos = 0
    self.flips = []
    def solve(root):
      if not root: return      
      if root.val != voyage[self.pos]:
        self.flips = [-1]
        return
      if root.left and root.left.val != voyage[self.pos + 1]:
        root.left, root.right = root.right, root.left
        self.flips.append(root.val)
      self.pos += 1
      solve(root.left)
      solve(root.right)    
    solve(root)
    return self.flips</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/">花花酱 LeetCode 971. Flip Binary Tree To Match Preorder Traversal</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-971-flip-binary-tree-to-match-preorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 25. Reverse Nodes in k-Group</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-25-reverse-nodes-in-k-group/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-25-reverse-nodes-in-k-group/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 16:27:56 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4125</guid>

					<description><![CDATA[<p>Problem Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-25-reverse-nodes-in-k-group/">花花酱 LeetCode 25. Reverse Nodes in k-Group</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Problem</h1>
<p>Given a linked list, reverse the nodes of a linked list <em>k</em> at a time and return its modified list.</p>
<p><em>k</em> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <em>k</em> then left-out nodes in the end should remain as it is.</p>
<p><strong>Example:</strong></p>
<p>Given this linked list: <code>1-&gt;2-&gt;3-&gt;4-&gt;5</code></p>
<p>For <em>k</em> = 2, you should return: <code>2-&gt;1-&gt;4-&gt;3-&gt;5</code></p>
<p>For <em>k</em> = 3, you should return: <code>3-&gt;2-&gt;1-&gt;4-&gt;5</code></p>
<p><strong>Note:</strong></p>
<ul>
<li>Only constant extra memory is allowed.</li>
<li>You may not alter the values in the list&#8217;s nodes, only nodes itself may be changed.</li>
</ul>
<h1><strong>Solution</strong></h1>
<p>Two passes.</p>
<p>First pass, get the length of the list.</p>
<p>Second pass, swap in groups.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *reverseKGroup(ListNode *head, int k) {
    if (!head || k == 1) return head;
    ListNode dummy(0);
    dummy.next = head;
    int len = 1;
    while (head = head-&gt;next) len++;
    ListNode* pre = &amp;dummy;    
    for (int l = 0; l + k &lt;= len; l += k) {
      ListNode* cur = pre-&gt;next;
      ListNode* nxt = cur-&gt;next;
      for (int i = 1; i &lt; k; ++i) {
        cur-&gt;next = nxt-&gt;next;
        nxt-&gt;next = pre-&gt;next;
        pre-&gt;next = nxt;
        nxt = cur-&gt;next;
      }
      pre = cur;
    }
    return dummy.next;
  }
};</pre><p></div></div></p>
<h1>Related Problems</h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/list/leetcode-24-swap-nodes-in-pairs/">花花酱 LeetCode 24. Swap Nodes in Pairs</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-25-reverse-nodes-in-k-group/">花花酱 LeetCode 25. Reverse Nodes in k-Group</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/list/leetcode-25-reverse-nodes-in-k-group/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 24. Swap Nodes in Pairs</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-24-swap-nodes-in-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-24-swap-nodes-in-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 15:59:12 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[dummy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4122</guid>

					<description><![CDATA[<p>Problem Given a linked list, swap every two adjacent nodes and return its head. Example: Given 1-&#62;2-&#62;3-&#62;4, you should return the list as 2-&#62;1-&#62;4-&#62;3. Note: Your&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-24-swap-nodes-in-pairs/">花花酱 LeetCode 24. Swap Nodes in Pairs</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a linked list, swap every two adjacent nodes and return its head.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false">Given <code>1-&gt;2-&gt;3-&gt;4</code>, you should return the list as <code>2-&gt;1-&gt;4-&gt;3</code>.</pre>
<p><strong>Note:</strong></p>
<ul>
<li>Your algorithm should use only constant extra space.</li>
<li>You may <strong>not</strong> modify the values in the list&#8217;s nodes, only nodes itself may be changed.</li>
</ul>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *swapPairs(ListNode *head) {
    if (!head || !head-&gt;next) return head;    

    ListNode d(0);
    d.next = head;
    head = &amp;d;

    while (head &amp;&amp; head-&gt;next &amp;&amp; head-&gt;next-&gt;next) {
      auto n1 = head-&gt;next;
      auto n2 = n1-&gt;next;

      n1-&gt;next = n2-&gt;next;
      n2-&gt;next = n1;

      head-&gt;next = n2;
      head = n1;
    }
    return d.next;
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution:
  def swapPairs(self, head):
    if not head or not head.next: return head
    dummy = ListNode(0)
    dummy.next = head
    head = dummy
    while head.next and head.next.next:
      n1, n2 = head.next, head.next.next
      n1.next = n2.next
      n2.next = n1
      head.next = n2      
      head = n1
    return dummy.next</pre><p></div></div></p>
<h1>Related Problems</h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-148-sort-list/">花花酱 LeetCode 148. Sort List</a></li>
<li><a href="https://zxi.mytechroad.com/blog/list/leetcode-203-remove-linked-list-elements/">花花酱 LeetCode 203. Remove Linked List Elements</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-24-swap-nodes-in-pairs/">花花酱 LeetCode 24. Swap Nodes in Pairs</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/list/leetcode-24-swap-nodes-in-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 627. Swap Salary</title>
		<link>https://zxi.mytechroad.com/blog/sql/leetcode-627-swap-salary/</link>
					<comments>https://zxi.mytechroad.com/blog/sql/leetcode-627-swap-salary/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 03 Apr 2018 15:17:59 +0000</pubDate>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[swap]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2416</guid>

					<description><![CDATA[<p>Problem https://leetcode.com/problems/swap-salary/description/ Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sql/leetcode-627-swap-salary/">花花酱 LeetCode 627. Swap Salary</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Problem</h1>
<p><a href="https://leetcode.com/problems/swap-salary/description/">https://leetcode.com/problems/swap-salary/description/</a></p>
<div class="question-description">
<div>
<p>Given a table <code>salary</code>, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.For example:</p>
<pre class="crayon:false">| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
</pre>
<p>After running your query, the above salary table should have the following rows:</p>
<pre class="crayon:false">| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
</pre>
</div>
</div>
<h1><strong>Solution: XOR</strong></h1>
<p></p><pre class="crayon-plain-tag"># Author: Huahua
# Running time: 309 ms
update salary set sex = char(ascii('f') ^ ascii('m') ^ ascii(sex))</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sql/leetcode-627-swap-salary/">花花酱 LeetCode 627. Swap Salary</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/sql/leetcode-627-swap-salary/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
