<?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>xor Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/xor/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/xor/</link>
	<description></description>
	<lastBuildDate>Sun, 12 Mar 2023 05:03:18 +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>xor Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/xor/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2588. Count the Number of Beautiful Subarrays</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 05:02:21 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix xor]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9984</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums. In one operation, you can: Choose two different indices&#160;i&#160;and&#160;j&#160;such that&#160;0 &#60;= i, j &#60; nums.length. Choose a non-negative integer&#160;k&#160;such that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/">花花酱 LeetCode 2588. Count the Number of Beautiful Subarrays</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. In one operation, you can:</p>



<ul><li>Choose two different indices&nbsp;<code>i</code>&nbsp;and&nbsp;<code>j</code>&nbsp;such that&nbsp;<code>0 &lt;= i, j &lt; nums.length</code>.</li><li>Choose a non-negative integer&nbsp;<code>k</code>&nbsp;such that the&nbsp;<code>k<sup>th</sup></code>&nbsp;bit (<strong>0-indexed</strong>) in the binary representation of&nbsp;<code>nums[i]</code>&nbsp;and&nbsp;<code>nums[j]</code>&nbsp;is&nbsp;<code>1</code>.</li><li>Subtract&nbsp;<code>2<sup>k</sup></code>&nbsp;from&nbsp;<code>nums[i]</code>&nbsp;and&nbsp;<code>nums[j]</code>.</li></ul>



<p>A subarray is&nbsp;<strong>beautiful</strong>&nbsp;if it is possible to make all of its elements equal to&nbsp;<code>0</code>&nbsp;after applying the above operation any number of times.</p>



<p>Return&nbsp;<em>the number of&nbsp;<strong>beautiful subarrays</strong>&nbsp;in the array</em>&nbsp;<code>nums</code>.</p>



<p>A subarray is a contiguous&nbsp;<strong>non-empty</strong>&nbsp;sequence of elements within an array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
  - Choose [3, 1, 2] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
  - Choose [1, 1, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
  - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
  - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
  - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>



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



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



<h2><strong>Solution: Hashtable + Prefix XOR</strong></h2>



<p>The problem is asking to find # of subarrays whose element wise xor is 0. We can use a hashtable to store the frequency of each prefix xor value, which reduces this problem to # of Subarray sum equal to k.</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:
  long long beautifulSubarrays(vector&lt;int&gt;&amp; nums) {
    long long ans = 0;
    unordered_map&lt;int, int&gt; m{{0, 1}};
    int x = 0;
    for (int i = 0; i &lt; nums.size(); ++i) {
      x ^= nums[i];
      ans += m[x];
      m[x] += 1;
    }
    return ans;
  } 
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/">花花酱 LeetCode 2588. Count the Number of Beautiful Subarrays</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-2588-count-the-number-of-beautiful-subarrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2564. Substring XOR Queries</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 16:50:41 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[precompute]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9942</guid>

					<description><![CDATA[<p>You are given a&#160;binary string&#160;s, and a&#160;2D&#160;integer array&#160;queries&#160;where&#160;queries[i] = [firsti, secondi]. For the&#160;ith&#160;query, find the&#160;shortest substring&#160;of&#160;s&#160;whose&#160;decimal value,&#160;val, yields&#160;secondi&#160;when&#160;bitwise XORed&#160;with&#160;firsti. In other words,&#160;val ^ firsti ==&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/">花花酱 LeetCode 2564. Substring XOR Queries</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2564. Substring XOR Queries - 刷题找工作 EP410" width="500" height="281" src="https://www.youtube.com/embed/UsH8x4Fg4DI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div></figure>



<p>You are given a&nbsp;<strong>binary string</strong>&nbsp;<code>s</code>, and a&nbsp;<strong>2D</strong>&nbsp;integer array&nbsp;<code>queries</code>&nbsp;where&nbsp;<code>queries[i] = [first<sub>i</sub>, second<sub>i</sub>]</code>.</p>



<p>For the&nbsp;<code>i<sup>th</sup></code>&nbsp;query, find the&nbsp;<strong>shortest substring</strong>&nbsp;of&nbsp;<code>s</code>&nbsp;whose&nbsp;<strong>decimal value</strong>,&nbsp;<code>val</code>, yields&nbsp;<code>second<sub>i</sub></code>&nbsp;when&nbsp;<strong>bitwise XORed</strong>&nbsp;with&nbsp;<code>first<sub>i</sub></code>. In other words,&nbsp;<code>val ^ first<sub>i</sub> == second<sub>i</sub></code>.</p>



<p>The answer to the&nbsp;<code>i<sup>th</sup></code>&nbsp;query is the endpoints (<strong>0-indexed</strong>) of the substring&nbsp;<code>[left<sub>i</sub>, right<sub>i</sub>]</code>&nbsp;or&nbsp;<code>[-1, -1]</code>&nbsp;if no such substring exists. If there are multiple answers, choose the one with the&nbsp;<strong>minimum</strong>&nbsp;<code>left<sub>i</sub></code>.</p>



<p><em>Return an array</em>&nbsp;<code>ans</code>&nbsp;<em>where</em>&nbsp;<code>ans[i] = [left<sub>i</sub>, right<sub>i</sub>]</code>&nbsp;<em>is the answer to the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>query.</em></p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous non-empty sequence of characters within a string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "101101", queries = [[0,5],[1,2]]
<strong>Output:</strong> [[0,2],[2,3]]
<strong>Explanation:</strong> For the first query the substring in range <code>[0,2]</code> is <strong>"101"</strong> which has a decimal value of <strong><code>5</code></strong>, and <strong><code>5 ^ 0 = 5</code></strong>, hence the answer to the first query is <code>[0,2]</code>. In the second query, the substring in range <code>[2,3]</code> is <strong>"11",</strong> and has a decimal value of <strong>3</strong>, and <strong>3<code> ^ 1 = 2</code></strong>.&nbsp;So, <code>[2,3]</code> is returned for the second query. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0101", queries = [[12,8]]
<strong>Output:</strong> [[-1,-1]]
<strong>Explanation:</strong> In this example there is no substring that answers the query, hence <code>[-1,-1] is returned</code>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1", queries = [[4,5]]
<strong>Output:</strong> [[0,0]]
<strong>Explanation:</strong> For this example, the substring in range <code>[0,0]</code> has a decimal value of <strong><code>1</code></strong>, and <strong><code>1 ^ 4 = 5</code></strong>. So, the answer is <code>[0,0]</code>.
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li><li><code>s[i]</code>&nbsp;is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code>.</li><li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= first<sub>i</sub>, second<sub>i</sub> &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Pre-compute</strong></h2>



<p>We can pre-compute all possible substrings</p>



<p>Time complexity: O(n*32 + m)<br>Space complexity: O(n*32)</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;vector&lt;int&gt;&gt; substringXorQueries(string s, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    unordered_map&lt;int, vector&lt;int&gt;&gt; m;
    const int l = s.length();
    for (int i = 0; i &lt; l; ++i) {
      if (s[i] == '0') {
        if (!m.count(0)) m[0] = {i, i};
        continue;
      }
      for (int j = 0, cur = 0; j &lt; 32 &amp;&amp; i + j &lt; l; ++j) {
        cur = (cur &lt;&lt; 1) | (s[i + j] - '0');
        if (!m.count(cur))
          m[cur] = {i, i + j};
      }
    }
    vector&lt;vector&lt;int&gt;&gt; ans;    
    for (const auto&amp; q : queries) {
      int x = q[0] ^ q[1];
      if (m.count(x)) 
        ans.push_back(m[x]);
      else
        ans.push_back({-1, -1});
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/">花花酱 LeetCode 2564. Substring XOR Queries</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-2564-substring-xor-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2317. Maximum XOR After Operations</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-2317-maximum-xor-after-operations/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-2317-maximum-xor-after-operations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Jun 2022 03:58:32 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9766</guid>

					<description><![CDATA[<p>You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that&#160;AND&#160;is the bitwise AND&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-2317-maximum-xor-after-operations/">花花酱 LeetCode 2317. Maximum XOR After Operations</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2317. Maximum XOR After Operations - 刷题找工作 EP398" width="500" height="281" src="https://www.youtube.com/embed/8wexnTx5wlE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, select <strong>any</strong> non-negative integer <code>x</code> and an index <code>i</code>, then <strong>update</strong> <code>nums[i]</code> to be equal to <code>nums[i] AND (nums[i] XOR x)</code>.</p>



<p>Note that&nbsp;<code>AND</code>&nbsp;is the bitwise AND operation and&nbsp;<code>XOR</code>&nbsp;is the bitwise XOR operation.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;possible bitwise XOR of all elements of&nbsp;</em><code>nums</code><em>&nbsp;after applying the operation&nbsp;<strong>any number</strong>&nbsp;of times</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,4,6]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.
Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.
It can be shown that 7 is the maximum possible bitwise XOR.
Note that other operations may be used to achieve a bitwise XOR of 7.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,9,2]
<strong>Output:</strong> 11
<strong>Explanation:</strong> Apply the operation zero times.
The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.
It can be shown that 11 is the maximum possible bitwise XOR.</pre>



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



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



<h2><strong>Solution: Bitwise OR</strong></h2>



<p>The maximum possible number MAX = nums[0] | nums[1] | &#8230; | nums[n &#8211; 1]. </p>



<p>We need to prove:<br>1) MAX is achievable.<br>2) MAX is the largest number we can get.</p>



<p><code>nums[i] AND (nums[i] XOR x)</code> means that we can turn any 1 bits to 0 for nums[i].</p>



<p>1) If the i-th bit of MAX is 1, which means there are at least one number with i-th bit equals to 1, however, for XOR, if there are even numbers with i-th bit equal to one, the final results will be 0 for i-th bit, we get a smaller number. By using the operation, we can choose one of them and flip the bit.<br><br>**1** XOR <meta charset="utf-8">**1** XOR <meta charset="utf-8">**1** XOR <meta charset="utf-8">**1** = **0** =&gt; <br>**<strong><span class="has-inline-color has-vivid-red-color">0</span></strong>** XOR <meta charset="utf-8">**1** XOR <meta charset="utf-8">**1** XOR <meta charset="utf-8">**1** = **<strong><span class="has-inline-color has-vivid-red-color">1</span></strong>**<br></p>



<p>2) If the i-th bit of MAX is 0, which means the i-th bit of all the numbers is 0, there is nothing we can do with the operation, and the XOR will be 0 as well.<br>e.g. <meta charset="utf-8">**0** XOR <meta charset="utf-8">**0** XOR <meta charset="utf-8">**0** XOR <meta charset="utf-8">**0** = **0**</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 maximumXOR(vector&lt;int&gt;&amp; nums) {
    return reduce(begin(nums), end(nums), 0, bit_or());
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-2317-maximum-xor-after-operations/">花花酱 LeetCode 2317. Maximum XOR After Operations</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-2317-maximum-xor-after-operations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2220. Minimum Bit Flips to Convert Number</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-2220-minimum-bit-flips-to-convert-number/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-2220-minimum-bit-flips-to-convert-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 02 Apr 2022 21:30:55 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9601</guid>

					<description><![CDATA[<p>A&#160;bit flip&#160;of a number&#160;x&#160;is choosing a bit in the binary representation of&#160;x&#160;and&#160;flipping&#160;it from either&#160;0&#160;to&#160;1&#160;or&#160;1&#160;to&#160;0. For example, for&#160;x = 7, the binary representation is&#160;111&#160;and we may&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-2220-minimum-bit-flips-to-convert-number/">花花酱 LeetCode 2220. Minimum Bit Flips to Convert Number</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&nbsp;<strong>bit flip</strong>&nbsp;of a number&nbsp;<code>x</code>&nbsp;is choosing a bit in the binary representation of&nbsp;<code>x</code>&nbsp;and&nbsp;<strong>flipping</strong>&nbsp;it from either&nbsp;<code>0</code>&nbsp;to&nbsp;<code>1</code>&nbsp;or&nbsp;<code>1</code>&nbsp;to&nbsp;<code>0</code>.</p>



<ul><li>For example, for&nbsp;<code>x = 7</code>, the binary representation is&nbsp;<code>111</code>&nbsp;and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get&nbsp;<code>110</code>, flip the second bit from the right to get&nbsp;<code>101</code>, flip the fifth bit from the right (a leading zero) to get&nbsp;<code>10111</code>, etc.</li></ul>



<p>Given two integers&nbsp;<code>start</code>&nbsp;and&nbsp;<code>goal</code>, return<em>&nbsp;the&nbsp;<strong>minimum</strong>&nbsp;number of&nbsp;<strong>bit flips</strong>&nbsp;to convert&nbsp;</em><code>start</code><em>&nbsp;to&nbsp;</em><code>goal</code>.</p>



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



<pre class="wp-block-preformatted:crayon:false"><strong>Input:</strong> start = 10, goal = 7
<strong>Output:</strong> 3
<strong>Explanation:</strong> The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:
- Flip the first bit from the right: 1010 -&gt; 1011.
- Flip the third bit from the right: 1011 -&gt; 1111.
- Flip the fourth bit from the right: 1111 -&gt; 0111.
It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.</pre>



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



<pre class="wp-block-preformatted:crayon:false"><strong>Input:</strong> start = 3, goal = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:
- Flip the first bit from the right: 011 -&gt; 010.
- Flip the second bit from the right: 010 -&gt; 000.
- Flip the third bit from the right: 000 -&gt; 100.
It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.
</pre>



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



<ul><li><code>0 &lt;= start, goal &lt;= 10<sup>9</sup></code></li></ul>



<p><strong>Solution: XOR</strong></p>



<p>start ^ goal will give us the bitwise difference of start and goal in binary format. <br>ans = # of 1 ones in the xor-ed results. <br>For C++, we can use __builtin_popcount or bitset&lt;32>::count() to get the number of bits set for a given integer.</p>



<p>Time complexity: O(1)<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 minBitFlips(int start, int goal) {
    return bitset&lt;32&gt;(start ^ goal).count(); // __builtin_popcount(start ^ goal);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-2220-minimum-bit-flips-to-convert-number/">花花酱 LeetCode 2220. Minimum Bit Flips to Convert Number</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-2220-minimum-bit-flips-to-convert-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 136. Single Number</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-136-single-number/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-136-single-number/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 05:04:42 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[O(1) space]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8843</guid>

					<description><![CDATA[<p>Given a&#160;non-empty&#160;array of integers&#160;nums, every element appears&#160;twice&#160;except for one. Find that single one. You must&#160;implement a solution with a linear runtime complexity and use&#160;only constant&#160;extra&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-136-single-number/">花花酱 LeetCode 136. Single Number</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&nbsp;<strong>non-empty</strong>&nbsp;array of integers&nbsp;<code>nums</code>, every element appears&nbsp;<em>twice</em>&nbsp;except for one. Find that single one.</p>



<p>You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.</p>



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



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



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



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



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



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



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



<ul><li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li><li><code>-3 * 10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 3 * 10<sup>4</sup></code></li><li>Each element in the array appears twice except for one element which appears only once.</li></ul>



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



<p>single_number ^ a ^ b ^ c ^ &#8230; ^ a ^ b ^ c &#8230; = single_number</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:
  int singleNumber(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    for (int x : nums)
      ans ^= x;
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Related Problems</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/bit/leetcode-137-single-number-ii/" data-type="post" data-id="8846">花花酱 LeetCode 137. Single Number II</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-136-single-number/">花花酱 LeetCode 136. Single Number</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-136-single-number/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1863. Sum of All Subset XOR Totals</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1863-sum-of-all-subset-xor-totals/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1863-sum-of-all-subset-xor-totals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 05 Aug 2021 05:03:21 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Bit]]></category>
		<category><![CDATA[subset]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8464</guid>

					<description><![CDATA[<p>The&#160;XOR total&#160;of an array is defined as the bitwise&#160;XOR&#160;of&#160;all its elements, or&#160;0&#160;if the array is&#160;empty. For example, the&#160;XOR total&#160;of the array&#160;[2,5,6]&#160;is&#160;2 XOR 5 XOR 6&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1863-sum-of-all-subset-xor-totals/">花花酱 LeetCode 1863. Sum of All Subset XOR Totals</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>The&nbsp;<strong>XOR total</strong>&nbsp;of an array is defined as the bitwise&nbsp;<code>XOR</code>&nbsp;of<strong>&nbsp;all its elements</strong>, or&nbsp;<code>0</code>&nbsp;if the array is<strong>&nbsp;empty</strong>.</p>



<ul><li>For example, the&nbsp;<strong>XOR total</strong>&nbsp;of the array&nbsp;<code>[2,5,6]</code>&nbsp;is&nbsp;<code>2 XOR 5 XOR 6 = 1</code>.</li></ul>



<p>Given an array&nbsp;<code>nums</code>, return&nbsp;<em>the&nbsp;<strong>sum</strong>&nbsp;of all&nbsp;<strong>XOR totals</strong>&nbsp;for every&nbsp;<strong>subset</strong>&nbsp;of&nbsp;</em><code>nums</code>.&nbsp;</p>



<p><strong>Note:</strong>&nbsp;Subsets with the&nbsp;<strong>same</strong>&nbsp;elements should be counted&nbsp;<strong>multiple</strong>&nbsp;times.</p>



<p>An array&nbsp;<code>a</code>&nbsp;is a&nbsp;<strong>subset</strong>&nbsp;of an array&nbsp;<code>b</code>&nbsp;if&nbsp;<code>a</code>&nbsp;can be obtained from&nbsp;<code>b</code>&nbsp;by deleting some (possibly zero) elements of&nbsp;<code>b</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,3]
<strong>Output:</strong> 6
<strong>Explanation: </strong>The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,1,6]
<strong>Output:</strong> 28
<strong>Explanation: </strong>The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,4,5,6,7,8]
<strong>Output:</strong> 480
<strong>Explanation:</strong> The sum of all XOR totals for every subset is 480.
</pre>



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



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



<h2><strong>Solution 1: Brute Force</strong></h2>



<p>Use an array A to store all the xor subsets, for a given number x<br>A = A + [x ^ a for a in A]</p>



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



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def subsetXORSum(self, nums: List[int]) -&gt; int:    
    xors = [0]
    for x in nums:
      xors += [xor ^ x for xor in xors]    
    return sum(xors)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1863-sum-of-all-subset-xor-totals/">花花酱 LeetCode 1863. Sum of All Subset XOR Totals</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-1863-sum-of-all-subset-xor-totals/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1835. Find XOR Sum of All Pairs Bitwise AND</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1835-find-xor-sum-of-all-pairs-bitwise-and/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1835-find-xor-sum-of-all-pairs-bitwise-and/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 18 Apr 2021 17:47:53 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8379</guid>

					<description><![CDATA[<p>The&#160;XOR sum&#160;of a list is the bitwise&#160;XOR&#160;of all its elements. If the list only contains one element, then its&#160;XOR sum&#160;will be equal to this element.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1835-find-xor-sum-of-all-pairs-bitwise-and/">花花酱 LeetCode 1835. Find XOR Sum of All Pairs Bitwise AND</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>The&nbsp;<strong>XOR sum</strong>&nbsp;of a list is the bitwise&nbsp;<code>XOR</code>&nbsp;of all its elements. If the list only contains one element, then its&nbsp;<strong>XOR sum</strong>&nbsp;will be equal to this element.</p>



<ul><li>For example, the&nbsp;<strong>XOR sum</strong>&nbsp;of&nbsp;<code>[1,2,3,4]</code>&nbsp;is equal to&nbsp;<code>1 XOR 2 XOR 3 XOR 4 = 4</code>, and the&nbsp;<strong>XOR sum</strong>&nbsp;of&nbsp;<code>[3]</code>&nbsp;is equal to&nbsp;<code>3</code>.</li></ul>



<p>You are given two&nbsp;<strong>0-indexed</strong>&nbsp;arrays&nbsp;<code>arr1</code>&nbsp;and&nbsp;<code>arr2</code>&nbsp;that consist only of non-negative integers.</p>



<p>Consider the list containing the result of&nbsp;<code>arr1[i] AND arr2[j]</code>&nbsp;(bitwise&nbsp;<code>AND</code>) for every&nbsp;<code>(i, j)</code>&nbsp;pair where&nbsp;<code>0 &lt;= i &lt; arr1.length</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt; arr2.length</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>XOR sum</strong>&nbsp;of the aforementioned list</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [1,2,3], arr2 = [6,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [12], arr2 = [4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The list = [12 AND 4] = [4]. The XOR sum = 4.
</pre>



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



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



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



<p>(a[0] &amp; b[i]) ^ (a[1] &amp; b[i]) ^ &#8230; ^ (a[n-1] &amp; b[i]) = (a[0] ^ a[1] ^ &#8230;  ^ a[n-1]) &amp; b[i]</p>



<p>We can pre compute that xor sum of array A.</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:
  int getXORSum(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    int ans = 0;    
    int xora = 0;
    for (int a : A) xora ^= a;    
    for (int b : B) ans ^= (xora &amp; b);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1835-find-xor-sum-of-all-pairs-bitwise-and/">花花酱 LeetCode 1835. Find XOR Sum of All Pairs Bitwise AND</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-1835-find-xor-sum-of-all-pairs-bitwise-and/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1829. Maximum XOR for Each Query</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1829-maximum-xor-for-each-query/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1829-maximum-xor-for-each-query/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Apr 2021 19:08:24 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8361</guid>

					<description><![CDATA[<p>You are given a&#160;sorted&#160;array&#160;nums&#160;of&#160;n&#160;non-negative integers and an integer&#160;maximumBit. You want to perform the following query&#160;n&#160;times: Find a non-negative integer&#160;k &#60; 2maximumBit&#160;such that&#160;nums[0] XOR nums[1] XOR&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1829-maximum-xor-for-each-query/">花花酱 LeetCode 1829. Maximum XOR for Each Query</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 a&nbsp;<strong>sorted</strong>&nbsp;array&nbsp;<code>nums</code>&nbsp;of&nbsp;<code>n</code>&nbsp;non-negative integers and an integer&nbsp;<code>maximumBit</code>. You want to perform the following query&nbsp;<code>n</code>&nbsp;<strong>times</strong>:</p>



<ol><li>Find a non-negative integer&nbsp;<code>k &lt; 2<sup>maximumBit</sup></code>&nbsp;such that&nbsp;<code>nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k</code>&nbsp;is&nbsp;<strong>maximized</strong>.&nbsp;<code>k</code>&nbsp;is the answer to the&nbsp;<code>i<sup>th</sup></code>&nbsp;query.</li><li>Remove the&nbsp;<strong>last&nbsp;</strong>element from the current array&nbsp;<code>nums</code>.</li></ol>



<p>Return&nbsp;<em>an array</em>&nbsp;<code>answer</code><em>, where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the answer to the&nbsp;</em><code>i<sup>th</sup></code><em>&nbsp;query</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,1,3], maximumBit = 2
<strong>Output:</strong> [0,3,2,3]
<strong>Explanation</strong>: The queries are answered as follows:
1<sup>st</sup> query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.
2<sup>nd</sup> query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.
3<sup>rd</sup> query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.
4<sup>th</sup> query: nums = [0], k = 3 since 0 XOR 3 = 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,4,7], maximumBit = 3
<strong>Output:</strong> [5,2,6,5]
<strong>Explanation</strong>: The queries are answered as follows:
1<sup>st</sup> query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.
2<sup>nd</sup> query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.
3<sup>rd</sup> query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.
4<sup>th</sup> query: nums = [2], k = 5 since 2 XOR 5 = 7.
</pre>



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



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



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



<ul><li><code>nums.length == n</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= maximumBit &lt;= 20</code></li><li><code>0 &lt;= nums[i] &lt; 2<sup>maximumBit</sup></code></li><li><code>nums</code>​​​ is sorted in&nbsp;<strong>ascending</strong>&nbsp;order.</li></ul>



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



<p>Compute s = nums[0] ^ nums[1] ^ &#8230; nums[n-1] first</p>



<p>to remove nums[i], we just need to do s ^= nums[i]</p>



<p>We can always maximize the xor of s and k to (2^maxbit &#8211; 1)<br>k = (2 ^ maxbit &#8211; 1) ^ s</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:
  vector&lt;int&gt; getMaximumXor(vector&lt;int&gt;&amp; nums, int maximumBit) {
    const int t = (1 &lt;&lt; maximumBit) - 1;
    const int n = nums.size();
    vector&lt;int&gt; ans(n);
    int s = 0;
    for (int x : nums) s ^= x;    
    for (int i = n - 1; i &gt;= 0; --i) {
      ans[n - i - 1] = t ^ s;
      s ^= nums[i];
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1829-maximum-xor-for-each-query/">花花酱 LeetCode 1829. Maximum XOR for Each Query</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-1829-maximum-xor-for-each-query/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1738. Find Kth Largest XOR Coordinate Value</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1738-find-kth-largest-xor-coordinate-value/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1738-find-kth-largest-xor-coordinate-value/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 Jan 2021 06:23:11 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[k-th]]></category>
		<category><![CDATA[submatrix]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8029</guid>

					<description><![CDATA[<p>You are given a 2D&#160;matrix&#160;of size&#160;m x n, consisting of non-negative integers. You are also given an integer&#160;k. The&#160;value&#160;of coordinate&#160;(a, b)&#160;of the matrix is the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1738-find-kth-largest-xor-coordinate-value/">花花酱 LeetCode 1738. Find Kth Largest XOR Coordinate Value</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 a 2D&nbsp;<code>matrix</code>&nbsp;of size&nbsp;<code>m x n</code>, consisting of non-negative integers. You are also given an integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>value</strong>&nbsp;of coordinate&nbsp;<code>(a, b)</code>&nbsp;of the matrix is the XOR of all&nbsp;<code>matrix[i][j]</code>&nbsp;where&nbsp;<code>0 &lt;= i &lt;= a &lt; m</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt;= b &lt; n</code>&nbsp;<strong>(0-indexed)</strong>.</p>



<p>Find the&nbsp;<code>k<sup>th</sup></code>&nbsp;largest value&nbsp;<strong>(1-indexed)</strong>&nbsp;of all the coordinates of&nbsp;<code>matrix</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[5,2],[1,6]], k = 1
<strong>Output:</strong> 7
<strong>Explanation:</strong> The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[5,2],[1,6]], k = 2
<strong>Output:</strong> 5
<strong>Explanation: </strong>The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[5,2],[1,6]], k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[5,2],[1,6]], k = 4
<strong>Output:</strong> 0
<strong>Explanation:</strong> The value of coordinate (1,1) is 5 XOR 2 XOR 1 XOR 6 = 0, which is the 4th largest value.</pre>



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



<ul><li><code>m == matrix.length</code></li><li><code>n == matrix[i].length</code></li><li><code>1 &lt;= m, n &lt;= 1000</code></li><li><code>0 &lt;= matrix[i][j] &lt;= 10<sup>6</sup></code></li><li><code>1 &lt;= k &lt;= m * n</code></li></ul>



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



<p>Similar to <a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-304-range-sum-query-2d-immutable/" data-type="post" data-id="348">花花酱 LeetCode 304. Range Sum Query 2D – Immutable</a></p>



<p>xor[i][j] = matrix[i][j] ^ xor[i &#8211; 1][j &#8211; 1] ^ xor[i &#8211; 1][j] ^ xor[i][j- 1]</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int kthLargestValue(vector&lt;vector&lt;int&gt;&gt;&amp; matrix, int k) {    
    const int m = matrix.size(), n = matrix[0].size();
    vector&lt;int&gt; v;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        v.push_back(matrix[i][j] 
                      ^= (i ? matrix[i - 1][j] : 0) 
                       ^ (j ? matrix[i][j - 1] : 0) 
                       ^ (i * j ? matrix[i - 1][j - 1] : 0));
    nth_element(begin(v), begin(v) + k - 1, end(v), greater&lt;int&gt;());    
    return v[k - 1];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1738-find-kth-largest-xor-coordinate-value/">花花酱 LeetCode 1738. Find Kth Largest XOR Coordinate Value</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-1738-find-kth-largest-xor-coordinate-value/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1734. Decode XORed Permutation</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1734-decode-xored-permutation/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1734-decode-xored-permutation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 23 Jan 2021 22:08:09 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8011</guid>

					<description><![CDATA[<p>There is an integer array&#160;perm&#160;that is a permutation of the first&#160;n&#160;positive integers, where&#160;n&#160;is always&#160;odd. It was encoded into another integer array&#160;encoded&#160;of length&#160;n - 1, such&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1734-decode-xored-permutation/">花花酱 LeetCode 1734. Decode XORed Permutation</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 an integer array&nbsp;<code>perm</code>&nbsp;that is a permutation of the first&nbsp;<code>n</code>&nbsp;positive integers, where&nbsp;<code>n</code>&nbsp;is always&nbsp;<strong>odd</strong>.</p>



<p>It was encoded into another integer array&nbsp;<code>encoded</code>&nbsp;of length&nbsp;<code>n - 1</code>, such that&nbsp;<code>encoded[i] = perm[i] XOR perm[i + 1]</code>. For example, if&nbsp;<code>perm = [1,3,2]</code>, then&nbsp;<code>encoded = [2,1]</code>.</p>



<p>Given the&nbsp;<code>encoded</code>&nbsp;array, return&nbsp;<em>the original array</em>&nbsp;<code>perm</code>. It is guaranteed that the answer exists and is unique.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encoded = [3,1]
<strong>Output:</strong> [1,2,3]
<strong>Explanation:</strong> If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]
</pre>



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



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



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



<ul><li><code>3 &lt;= n &lt;&nbsp;10<sup>5</sup></code></li><li><code>n</code>&nbsp;is odd.</li><li><code>encoded.length == n - 1</code></li></ul>



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



<p>The key is to find p[0]. p[i] = p[i &#8211; 1] ^ encoded[i &#8211; 1]</p>



<ol><li>p[0] ^ p[1] ^ &#8230; ^ p[n-1] = 1 ^ 2 ^ &#8230; ^ n</li><li>encoded[1] ^ encode[3] ^ &#8230; ^ encoded[n-2] = (p[1] ^ p[2]) ^ (p[3] ^ p[4]) ^ &#8230; ^ (p[n-2] ^ p[n-1])</li></ol>



<p>1) xor 2) = p[0]</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:
  vector&lt;int&gt; decode(vector&lt;int&gt;&amp; encoded) {    
    const int n = encoded.size() + 1;
    vector&lt;int&gt; perm(n);
    // p[0] = (p[0]^p[1]^...^p[n-1] = 1^2^...^n) 
    //      ^ (p[1]^p[2]^...^p[n-1])
    for (int i = 1; i &lt;= n; ++i) 
      perm[0] ^= i;
    for (int i = 1; i &lt; n; i += 2)
      perm[0] ^= encoded[i];
    for (int i = 1; i &lt; n; ++i)
      perm[i] = perm[i - 1] ^ encoded[i - 1];
    return perm;        
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1734-decode-xored-permutation/">花花酱 LeetCode 1734. Decode XORed Permutation</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-1734-decode-xored-permutation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1720. Decode XORed Array</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1720-decode-xored-array/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1720-decode-xored-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 17:47:03 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7961</guid>

					<description><![CDATA[<p>There is a&#160;hidden&#160;integer array&#160;arr&#160;that consists of&#160;n&#160;non-negative integers. It was encoded into another integer array&#160;encoded&#160;of length&#160;n - 1, such that&#160;encoded[i] = arr[i] XOR arr[i + 1].&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1720-decode-xored-array/">花花酱 LeetCode 1720. Decode XORed 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>There is a&nbsp;<strong>hidden</strong>&nbsp;integer array&nbsp;<code>arr</code>&nbsp;that consists of&nbsp;<code>n</code>&nbsp;non-negative integers.</p>



<p>It was encoded into another integer array&nbsp;<code>encoded</code>&nbsp;of length&nbsp;<code>n - 1</code>, such that&nbsp;<code>encoded[i] = arr[i] XOR arr[i + 1]</code>. For example, if&nbsp;<code>arr = [1,0,2,1]</code>, then&nbsp;<code>encoded = [1,2,3]</code>.</p>



<p>You are given the&nbsp;<code>encoded</code>&nbsp;array. You are also given an integer&nbsp;<code>first</code>, that is the first element of&nbsp;<code>arr</code>, i.e.&nbsp;<code>arr[0]</code>.</p>



<p>Return&nbsp;<em>the original array</em>&nbsp;<code>arr</code>. It can be proved that the answer exists and is unique.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encoded = [1,2,3], first = 1
<strong>Output:</strong> [1,0,2,1]
<strong>Explanation:</strong> If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
</pre>



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



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



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



<ul><li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li><li><code>encoded.length == n - 1</code></li><li><code>0 &lt;= encoded[i] &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= first &lt;= 10<sup>5</sup></code></li></ul>



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



<p>encoded[i] = arr[i] ^ arr[i + 1]<br>encoded[i] ^ arr[i] = arr[i] ^ arr[i] ^ arr[i + 1]<br>arr[i+1] = encoded[i]^arr[i]</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">class Solution {
public:
  vector&lt;int&gt; decode(vector&lt;int&gt;&amp; encoded, int first) {
    const int n = encoded.size() + 1;
    vector&lt;int&gt; ans(n, first);
    for (int i = 0; i + 1 &lt; n; ++i)
      ans[i + 1] = ans[i] ^ encoded[i];
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1720-decode-xored-array/">花花酱 LeetCode 1720. Decode XORed 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/bit/leetcode-1720-decode-xored-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 421. Maximum XOR of Two Numbers in an Array</title>
		<link>https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 21:31:59 +0000</pubDate>
				<category><![CDATA[Trie]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[trie]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7868</guid>

					<description><![CDATA[<p>Given an integer array&#160;nums, return&#160;the maximum result of&#160;nums[i] XOR nums[j], where&#160;0 ≤ i ≤ j &#60; n. Follow up:&#160;Could you do this in&#160;O(n)&#160;runtime? Example 1:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/">花花酱 LeetCode 421. Maximum XOR of Two Numbers in 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 integer array&nbsp;<code>nums</code>, return&nbsp;<em>the maximum result of&nbsp;<code>nums[i] XOR nums[j]</code></em>, where&nbsp;<code>0 ≤ i ≤ j &lt; n</code>.</p>



<p><strong>Follow up:</strong>&nbsp;Could you do this in&nbsp;<code>O(n)</code>&nbsp;runtime?</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,10,5,25,2,8]
<strong>Output:</strong> 28
<strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28.</pre>



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



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



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



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



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70]
<strong>Output:</strong> 127
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li><li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup>&nbsp;- 1</code></li></ul>



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Trie {
public:
  Trie(): children(2) {}  
  vector&lt;unique_ptr&lt;Trie&gt;&gt; children;
};
class Solution {
public:
  int findMaximumXOR(vector&lt;int&gt;&amp; nums) {
    Trie root;
    
    // Insert a number into the trie.
    auto insert = [&amp;](Trie* node, int num) {
      for (int i = 31; i &gt;= 0; --i) {
        int bit = (num &gt;&gt; i) &amp; 1;
        if (!node-&gt;children[bit])
          node-&gt;children[bit] = std::make_unique&lt;Trie&gt;();
        node = node-&gt;children[bit].get();
      }
    };
  
    // Find max xor sum of num and another element in the array.
    auto query = [&amp;](Trie* node, int num) {
      int sum = 0;
      for (int i = 31; i &gt;= 0; --i) {
        int bit = (num &gt;&gt; i) &amp; 1;
        if (node-&gt;children[1 - bit]) {
          sum += (1 &lt;&lt; i);
          node = node-&gt;children[1 - bit].get();
        } else {
          node = node-&gt;children[bit].get();
        }
      }
      return sum;
    };
    
    // Insert all numbers.
    for (int x : nums) 
      insert(&amp;root, x);
    
    int ans = 0;
    // For each number find the maximum xor sum.
    for (int x : nums) 
      ans = max(ans, query(&amp;root, x));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/">花花酱 LeetCode 421. Maximum XOR of Two Numbers in 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/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1542. Find Longest Awesome Substring</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1542-find-longest-awesome-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1542-find-longest-awesome-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 10 Aug 2020 07:34:23 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7222</guid>

					<description><![CDATA[<p>Given a string&#160;s. An&#160;awesome&#160;substring is a non-empty substring of&#160;s&#160;such that we can make any number of swaps in order to make it palindrome. Return the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1542-find-longest-awesome-substring/">花花酱 LeetCode 1542. Find Longest Awesome Substring</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-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1542. Find Longest Awesome Substring - 刷题找工作 EP349" width="500" height="281" src="https://www.youtube.com/embed/b0oxAd94FOg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>s</code>. An&nbsp;<em>awesome</em>&nbsp;substring is a non-empty substring of&nbsp;<code>s</code>&nbsp;such that we can make any number of swaps in order to make it palindrome.</p>



<p>Return the length of the maximum length&nbsp;<strong>awesome substring</strong>&nbsp;of&nbsp;<code>s</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "3242415"
<strong>Output:</strong> 5
<strong>Explanation:</strong> "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "213123"
<strong>Output:</strong> 6
<strong>Explanation:</strong> "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s</code>&nbsp;consists only of digits.</li></ul>



<h2><strong>Solution: Prefix mask + Hashtable</strong></h2>



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



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1542-ep349-2.png" alt="" class="wp-image-7234" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1542-ep349-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1542-ep349-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/08/1542-ep349-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>For a palindrome all digits must occurred even times expect one. We can use a 10 bit mask to track the occurrence of each digit for prefix s[0~i]. 0 is even, 1 is odd.</p>



<p>We use a hashtable to track the <strong>first index</strong> of each prefix state.<br>If s[0~i] and s[0~j] have the same state which means every digits in s[i+1~j] occurred even times (zero is also even) and it&#8217;s an awesome string. Then (j &#8211; (i+1)  + 1) = j &#8211; i is the length of the palindrome. So far so good.</p>



<p>But we still need to consider the case when there is a digit with odd occurrence. We can enumerate all possible ones from 0 to 9, and temporarily flip the bit of the digit and see whether that state happened before. </p>



<p>fisrt_index[0] = -1, first_index[*] = inf<br>ans = max(ans, j &#8211; first_index[mask])</p>



<p>Time complexity: O(n)<br>Space complexity: O(2^10) = O(1)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int longestAwesome(string s) {
    constexpr int kInf = 1e9;
    vector&lt;int&gt; idx(1024, kInf);
    idx[0] = -1;
    int mask = 0; // prefix's state 0:even, 1:odd
    int ans = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      mask ^= (1 &lt;&lt; (s[i] - '0'));
      ans = max(ans, i - idx[mask]);
      // One digit with odd count is allowed.
      for (int j = 0; j &lt; 10; ++j)
        ans = max(ans, i - idx[mask ^ (1 &lt;&lt; j)]);
      idx[mask] = min(idx[mask], i);
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public int longestAwesome(String s) {
    final int n = s.length();
    int[] idx = new int[1024];
    Arrays.fill(idx, n);
    idx[0] = -1;
    int mask = 0;
    int ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      mask ^= (1 &lt;&lt; (s.charAt(i) - '0'));
      ans = Math.max(ans, i - idx[mask]);      
      for (int j = 0; j &lt; 10; ++j)
        ans = Math.max(ans, 
                       i - idx[mask ^ (1 &lt;&lt; j)]);
      idx[mask] = Math.min(idx[mask], i);
    }
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def longestAwesome(self, s: str) -&gt; int:  
    idx = [-1] + [len(s)] * 1023
    ans, mask = 0, 0
    for i, c in enumerate(s):
      mask ^= 1 &lt;&lt; (ord(c) - ord('0'))
      ans = max([ans, i - idx[mask]]
                + [i - idx[mask ^ (1 &lt;&lt; j)] for j in range(10)])
      idx[mask] = min(idx[mask], i)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1542-find-longest-awesome-substring/">花花酱 LeetCode 1542. Find Longest Awesome Substring</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-1542-find-longest-awesome-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1529. Bulb Switcher IV</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-1529-bulb-switcher-iv/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-1529-bulb-switcher-iv/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Jul 2020 18:52:08 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[flip]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7166</guid>

					<description><![CDATA[<p>There is a room with&#160;n&#160;bulbs, numbered from&#160;0&#160;to&#160;n-1,&#160;arranged in a row from left to right. Initially all the bulbs are&#160;turned off. Your task is to obtain&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1529-bulb-switcher-iv/">花花酱 LeetCode 1529. Bulb Switcher IV</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>0</code>&nbsp;to&nbsp;<code>n-1</code>,&nbsp;arranged in a row from left to right. Initially all the bulbs are&nbsp;<strong>turned off</strong>.</p>



<p>Your task is to obtain the configuration represented by&nbsp;<code>target</code>&nbsp;where&nbsp;<code>target[i]</code>&nbsp;is &#8216;1&#8217; if the i-th bulb is turned on and is &#8216;0&#8217; if it is turned off.</p>



<p>You have a switch&nbsp;to flip the state of the bulb,&nbsp;a flip operation is defined as follows:</p>



<ul><li>Choose&nbsp;<strong>any</strong>&nbsp;bulb (index&nbsp;<code>i</code>)&nbsp;of your current configuration.</li><li>Flip each bulb from index&nbsp;<code>i</code>&nbsp;to&nbsp;<code>n-1</code>.</li></ul>



<p>When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0.</p>



<p>Return the&nbsp;<strong>minimum</strong>&nbsp;number of flips required to form&nbsp;<code>target</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = "10111"
<strong>Output:</strong> 3
<strong>Explanation: </strong>Initial configuration "00000".
flip from the third bulb:  "00000" -&gt; "00111"
flip from the first bulb:  "00111" -&gt; "11000"
flip from the second bulb:  "11000" -&gt; "10111"
We need at least 3 flip operations to form target.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = "101"
<strong>Output:</strong> 3
<strong>Explanation: </strong>"000" -&gt; "111" -&gt; "100" -&gt; "101".
</pre>



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



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



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



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



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



<ul><li><code>1 &lt;= target.length &lt;= 10^5</code></li><li><code>target[i] == '0'</code>&nbsp;or&nbsp;<code>target[i] == '1'</code></li></ul>



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



<p>Flip from left to right, since flipping the a bulb won&#8217;t affect anything in the left.<br>We count how many times flipped so far, and that % 2 will be the state for all the bulb to the right.<br>If the current bulb&#8217;s state != target, we have to flip once.</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:
  int minFlips(string target) {
    int ans = 0;
    int cur = 0;
    for (char c : target) {
      if (c - '0' != cur) {
        cur ^= 1;
        ++ans;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-1529-bulb-switcher-iv/">花花酱 LeetCode 1529. Bulb Switcher IV</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-1529-bulb-switcher-iv/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1486. XOR Operation in an Array</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1486-xor-operation-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1486-xor-operation-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Jun 2020 04:57:38 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6953</guid>

					<description><![CDATA[<p>Given an integer&#160;n&#160;and an integer&#160;start. Define an array&#160;nums&#160;where&#160;nums[i] = start + 2*i&#160;(0-indexed) and&#160;n == nums.length. Return the bitwise&#160;XOR&#160;of all elements of&#160;nums. Example 1: Input: n&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1486-xor-operation-in-an-array/">花花酱 LeetCode 1486. XOR Operation in 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 integer&nbsp;<code>n</code>&nbsp;and an integer&nbsp;<code>start</code>.</p>



<p>Define an array&nbsp;<code>nums</code>&nbsp;where&nbsp;<code>nums[i] = start + 2*i</code>&nbsp;(0-indexed) and&nbsp;<code>n == nums.length</code>.</p>



<p>Return the bitwise&nbsp;XOR&nbsp;of all elements of&nbsp;<code>nums</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, start = 0
<strong>Output:</strong> 8
<strong>Explanation: </strong>Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, start = 3
<strong>Output:</strong> 8
<strong>Explanation: </strong>Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 10, start = 5
<strong>Output:</strong> 2
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 1000</code></li><li><code>0 &lt;= start &lt;= 1000</code></li><li><code>n == nums.length</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 xorOperation(int n, int start) {
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      ans ^= (start + 2 * i);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1486-xor-operation-in-an-array/">花花酱 LeetCode 1486. XOR Operation in 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/simulation/leetcode-1486-xor-operation-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
