<?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>prefix &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/prefix/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 11 Apr 2025 04:28:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>prefix &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2012. Sum of Beauty in the Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2012-sum-of-beauty-in-the-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2012-sum-of-beauty-in-the-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 11 Apr 2025 04:21:38 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[prefix max]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10326</guid>

					<description><![CDATA[数据规模比较大，算法必须是O(n)的。 可以预先使用O(n)时间计算nums[0] .. nums[i]的最大值，存在left[i]中，以及nums[i] .. nums[n-1]的最小值存在right[i]中。然后再按题目的定义计算即可。 时间复杂度：O(n)空间复杂度：O(n) [crayon-67fd1b7c3578f533968179/]]]></description>
										<content:encoded><![CDATA[
<p>数据规模比较大，算法必须是O(n)的。</p>



<p>可以预先使用O(n)时间计算nums[0] .. nums[i]的最大值，存在left[i]中，以及nums[i] .. nums[n-1]的最小值存在right[i]中。然后再按题目的定义计算即可。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(n)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int sumOfBeauties(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; left(n, nums[0]);
    vector&lt;int&gt; right(n, nums.back());
    for (int i = 1; i &lt; n; ++i)
      left[i] = max(left[i - 1], nums[i]);
    for (int i = n - 2; i &gt;= 0; --i)
      right[i] = min(right[i + 1], nums[i]);
    int ans = 0;
    for (int i = 1; i &lt; n - 1; ++i)
      if (left[i - 1] &lt; nums[i] &amp;&amp; nums[i] &lt; right[i + 1])
        ans += 2;
      else if (nums[i - 1] &lt; nums[i] &amp;&amp; nums[i] &lt; nums[i + 1])
        ans += 1;
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2012-sum-of-beauty-in-the-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3029. Minimum Time to Revert Word to Initial State I</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 06 Feb 2024 02:02:17 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[surffix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10114</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;string&#160;word&#160;and an integer&#160;k. At every second, you must perform the following operations: Remove the first&#160;k&#160;characters of&#160;word. Add any&#160;k&#160;characters to the end of&#160;word.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>word</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>At every second, you must perform the following operations:</p>



<ul class="wp-block-list"><li>Remove the first&nbsp;<code>k</code>&nbsp;characters of&nbsp;<code>word</code>.</li><li>Add any&nbsp;<code>k</code>&nbsp;characters to the end of&nbsp;<code>word</code>.</li></ul>



<p><strong>Note</strong>&nbsp;that you do not necessarily need to add the same characters that you removed. However, you must perform&nbsp;<strong>both</strong>&nbsp;operations at every second.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;time greater than zero required for</em>&nbsp;<code>word</code>&nbsp;<em>to revert to its&nbsp;<strong>initial</strong>&nbsp;state</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= word.length &lt;= 50</code></li><li><code>1 &lt;= k &lt;= word.length</code></li><li><code>word</code>&nbsp;consists only of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Suffix ==? Prefix</strong></h2>



<p>Compare the suffix with prefix.</p>



<p>word = &#8220;abacaba&#8221;, k = 3<br>ans = 1, &#8220;<s>aba</s>caba&#8221; != &#8220;abac<s>aba</s>&#8220;<br>ans = 2, &#8220;<s>abacab</s>a&#8221; == &#8220;a<s>bacaba</s>&#8220;, we find it.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minimumTimeToInitialState(string_view word, int k) {
    const int n = word.length();
    for (int i = 1; i * k &lt; n; ++i) {
      string_view t = word.substr(i * k);
      if (t == word.substr(0, t.length())) return i;
    }      
    return (n + k - 1) / k;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-3029-minimum-time-to-revert-word-to-initial-state-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2657. Find the Prefix Common Array of Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 15:10:21 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[mask]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10027</guid>

					<description><![CDATA[You are given two&#160;0-indexed&#160;integer&#160;permutations&#160;A&#160;and&#160;B&#160;of length&#160;n. A&#160;prefix common array&#160;of&#160;A&#160;and&#160;B&#160;is an array&#160;C&#160;such that&#160;C[i]&#160;is equal to the count of numbers that are present at or before the index&#160;i&#160;in&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>0-indexed&nbsp;</strong>integer<strong>&nbsp;</strong>permutations&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;of length&nbsp;<code>n</code>.</p>



<p>A&nbsp;<strong>prefix common array</strong>&nbsp;of&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;is an array&nbsp;<code>C</code>&nbsp;such that&nbsp;<code>C[i]</code>&nbsp;is equal to the count of numbers that are present at or before the index&nbsp;<code>i</code>&nbsp;in both&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>prefix common array</strong>&nbsp;of&nbsp;</em><code>A</code><em>&nbsp;and&nbsp;</em><code>B</code>.</p>



<p>A sequence of&nbsp;<code>n</code>&nbsp;integers is called a&nbsp;<strong>permutation</strong>&nbsp;if it contains all integers from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>&nbsp;exactly once.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4]
<strong>Output:</strong> [0,2,3,4]
<strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0.
At i = 1: 1 and 3 are common in A and B, so C[1] = 2.
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> A = [2,3,1], B = [3,1,2]
<strong>Output:</strong> [0,1,3]
<strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0.
At i = 1: only 3 is common in A and B, so C[1] = 1.
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li><li><code>1 &lt;= A[i], B[i] &lt;= n</code></li><li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Bitset</strong></h2>



<p>Use bitsets to store the numbers seen so far for each array, and use sA &amp; sB to count the common elements.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findThePrefixCommonArray(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    bitset&lt;51&gt; sA;
    bitset&lt;51&gt; sB;
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; A.size(); ++i) {
      sA.set(A[i]);
      sB.set(B[i]);
      ans.push_back((sA &amp; sB).count());
    }
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Counter</strong></h2>



<p>Use a counter to track the frequency of each element, when the counter[x] == 2, we found a pair.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findThePrefixCommonArray(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    vector&lt;int&gt; count(A.size() + 1);
    vector&lt;int&gt; ans;
    for (int i = 0, s = 0; i &lt; A.size(); ++i) {
      if (++count[A[i]] == 2) ++s;
      if (++count[B[i]] == 2) ++s;
      ans.push_back(s);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2416. Sum of Prefix Scores of Strings</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 18 Sep 2022 19:44:55 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[tire]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9832</guid>

					<description><![CDATA[You are given an array&#160;words&#160;of size&#160;n&#160;consisting of&#160;non-empty&#160;strings. We define the&#160;score&#160;of a string&#160;word&#160;as the&#160;number&#160;of strings&#160;words[i]&#160;such that&#160;word&#160;is a&#160;prefix&#160;of&#160;words[i]. For example, if&#160;words = ["a", "ab", "abc", "cab"], then&#8230;]]></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 2416. Sum of Prefix Scores of Strings - 刷题找工作 EP402" width="500" height="281" src="https://www.youtube.com/embed/OJ0PMH6M2MQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>words</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;consisting of&nbsp;<strong>non-empty</strong>&nbsp;strings.</p>



<p>We define the&nbsp;<strong>score</strong>&nbsp;of a string&nbsp;<code>word</code>&nbsp;as the&nbsp;<strong>number</strong>&nbsp;of strings&nbsp;<code>words[i]</code>&nbsp;such that&nbsp;<code>word</code>&nbsp;is a&nbsp;<strong>prefix</strong>&nbsp;of&nbsp;<code>words[i]</code>.</p>



<ul class="wp-block-list"><li>For example, if&nbsp;<code>words = ["a", "ab", "abc", "cab"]</code>, then the score of&nbsp;<code>"ab"</code>&nbsp;is&nbsp;<code>2</code>, since&nbsp;<code>"ab"</code>&nbsp;is a prefix of both&nbsp;<code>"ab"</code>&nbsp;and&nbsp;<code>"abc"</code>.</li></ul>



<p>Return&nbsp;<em>an array&nbsp;</em><code>answer</code><em>&nbsp;of size&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the&nbsp;<strong>sum</strong>&nbsp;of scores of every&nbsp;<strong>non-empty</strong>&nbsp;prefix of&nbsp;</em><code>words[i]</code>.</p>



<p><strong>Note</strong>&nbsp;that a string is considered as a prefix of itself.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["abc","ab","bc","b"]
<strong>Output:</strong> [5,4,3,2]
<strong>Explanation:</strong> The answer for each string is the following:
- "abc" has 3 prefixes: "a", "ab", and "abc".
- There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc".
The total is answer[0] = 2 + 2 + 1 = 5.
- "ab" has 2 prefixes: "a" and "ab".
- There are 2 strings with the prefix "a", and 2 strings with the prefix "ab".
The total is answer[1] = 2 + 2 = 4.
- "bc" has 2 prefixes: "b" and "bc".
- There are 2 strings with the prefix "b", and 1 string with the prefix "bc".
The total is answer[2] = 2 + 1 = 3.
- "b" has 1 prefix: "b".
- There are 2 strings with the prefix "b".
The total is answer[3] = 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["abcd"]
<strong>Output:</strong> [4]
<strong>Explanation:</strong>
"abcd" has 4 prefixes: "a", "ab", "abc", and "abcd".
Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= words.length &lt;= 1000</code></li><li><code>1 &lt;= words[i].length &lt;= 1000</code></li><li><code>words[i]</code>&nbsp;consists of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Trie</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png" alt="" class="wp-image-9836" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2.png"><img decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2.png" alt="" class="wp-image-9837" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3.png" alt="" class="wp-image-9839" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<p>Insert all the words into a tire whose node val is the number of substrings that have the current prefix.</p>



<p>During query time, sum up the values along the prefix path.</p>



<p>Time complexity: O(sum(len(word))<br>Space complexity: O(sum(len(word))</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
struct Trie {
  Trie* ch[26] = {};
  int cnt = 0;
  void insert(string_view s) {
    Trie* cur = this;
    for (char c : s) {
      if (!cur-&gt;ch[c - 'a']) 
        cur-&gt;ch[c - 'a'] = new Trie();
      cur = cur-&gt;ch[c - 'a'];
      ++cur-&gt;cnt;
    }
  }
  int query(string_view s) {
    Trie* cur = this;
    int ans = 0;
    for (char c : s) {
      cur = cur-&gt;ch[c - 'a'];
      ans += cur-&gt;cnt;
    }
    return ans;
  }
};
class Solution {
public:
  vector&lt;int&gt; sumPrefixScores(vector&lt;string&gt;&amp; words) {
    Trie* root = new Trie();
    for (const string&amp; w : words)
      root-&gt;insert(w);
    vector&lt;int&gt; ans;
    for (const string&amp; w : words)
      ans.push_back(root-&gt;query(w));
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2256. Minimum Average Difference</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2256-minimum-average-difference/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2256-minimum-average-difference/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 May 2022 04:49:42 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[suffix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9707</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;of length&#160;n. The&#160;average difference&#160;of the index&#160;i&#160;is the&#160;absolute&#160;difference&#160;between the average of the&#160;first&#160;i + 1&#160;elements of&#160;nums&#160;and the average of the&#160;last&#160;n - i -&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>.</p>



<p>The&nbsp;<strong>average difference</strong>&nbsp;of the index&nbsp;<code>i</code>&nbsp;is the&nbsp;<strong>absolute</strong>&nbsp;<strong>difference</strong>&nbsp;between the average of the&nbsp;<strong>first</strong>&nbsp;<code>i + 1</code>&nbsp;elements of&nbsp;<code>nums</code>&nbsp;and the average of the&nbsp;<strong>last</strong>&nbsp;<code>n - i - 1</code>&nbsp;elements. Both averages should be&nbsp;<strong>rounded down</strong>&nbsp;to the nearest integer.</p>



<p>Return<em>&nbsp;the index with the&nbsp;<strong>minimum average difference</strong></em>. If there are multiple such indices, return the&nbsp;<strong>smallest</strong>&nbsp;one.</p>



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



<ul class="wp-block-list"><li>The&nbsp;<strong>absolute difference</strong>&nbsp;of two numbers is the absolute value of their difference.</li><li>The&nbsp;<strong>average</strong>&nbsp;of&nbsp;<code>n</code>&nbsp;elements is the&nbsp;<strong>sum</strong>&nbsp;of the&nbsp;<code>n</code>&nbsp;elements divided (<strong>integer division</strong>) by&nbsp;<code>n</code>.</li><li>The average of&nbsp;<code>0</code>&nbsp;elements is considered to be&nbsp;<code>0</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,5,3,9,5,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
The average difference of index 3 is the minimum average difference so return 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<p>Solution: Prefix / Suffix Sum</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumAverageDifference(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    long long suffix = accumulate(begin(nums), end(nums), 0LL);
    long long prefix = 0;
    int best = INT_MAX;
    int ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      prefix += nums[i];
      suffix -= nums[i];
      int cur = abs(prefix / (i + 1) - (i == n - 1 ? 0 : suffix / (n - i - 1)));
      if (cur &lt; best) {
        best = cur;
        ans = i;
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2256-minimum-average-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1915. Number of Wonderful Substrings</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Dec 2021 11:11:08 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9230</guid>

					<description><![CDATA[A&#160;wonderful&#160;string is a string where&#160;at most one&#160;letter appears an&#160;odd&#160;number of times. For example,&#160;"ccjjc"&#160;and&#160;"abab"&#160;are wonderful, but&#160;"ab"&#160;is not. Given a string&#160;word&#160;that consists of the first ten lowercase&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>wonderful</strong>&nbsp;string is a string where&nbsp;<strong>at most one</strong>&nbsp;letter appears an&nbsp;<strong>odd</strong>&nbsp;number of times.</p>



<ul class="wp-block-list"><li>For example,&nbsp;<code>"ccjjc"</code>&nbsp;and&nbsp;<code>"abab"</code>&nbsp;are wonderful, but&nbsp;<code>"ab"</code>&nbsp;is not.</li></ul>



<p>Given a string&nbsp;<code>word</code>&nbsp;that consists of the first ten lowercase English letters (<code>'a'</code>&nbsp;through&nbsp;<code>'j'</code>), return&nbsp;<em>the&nbsp;<strong>number of wonderful non-empty substrings</strong>&nbsp;in&nbsp;</em><code>word</code><em>. If the same substring appears multiple times in&nbsp;</em><code>word</code><em>, then count&nbsp;<strong>each occurrence</strong>&nbsp;separately.</em></p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters in a string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "aba"
<strong>Output:</strong> 4
<strong>Explanation:</strong> The four wonderful substrings are underlined below:
- "<strong>a</strong>ba" -&gt; "a"
- "a<strong>b</strong>a" -&gt; "b"
- "ab<strong>a</strong>" -&gt; "a"
- "<strong>aba</strong>" -&gt; "aba"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "aabb"
<strong>Output:</strong> 9
<strong>Explanation:</strong> The nine wonderful substrings are underlined below:
- "<strong><u>a</u></strong>abb" -&gt; "a"
- "<strong>aa</strong>bb" -&gt; "aa"
- "<strong>aab</strong>b" -&gt; "aab"
- "<strong>aabb</strong>" -&gt; "aabb"
- "a<strong>a</strong>bb" -&gt; "a"
- "a<strong>abb</strong>" -&gt; "abb"
- "aa<strong>b</strong>b" -&gt; "b"
- "aa<strong>bb</strong>" -&gt; "bb"
- "aab<strong>b</strong>" -&gt; "b"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "he"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The two wonderful substrings are underlined below:
- "<strong><u>h</u></strong>e" -&gt; "h"
- "h<strong><u>e</u></strong>" -&gt; "e"
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li><li><code>word</code>&nbsp;consists of lowercase English letters from&nbsp;<code>'a'</code>&nbsp;to&nbsp;<code>'j'</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Prefix Bitmask + Hashtable</strong></h2>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1371-find-the-longest-substring-containing-vowels-in-even-counts/" data-type="post" data-id="6400">花花酱 LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts</a>, we use   a bitmask to represent the occurrence (odd or even) of each letter and use a hashtable to store the frequency of each bitmask seen so far.<br><br>1. &#8220;0000000000&#8221; means all letters occur even times.<br>2. &#8220;0000000101&#8221; means <meta charset="utf-8">all letters occur even times expect letter &#8216;a&#8217; and &#8216;c&#8217; that occur odd times.</p>



<p>We scan the word from left to right and update the bitmask: bitmask ^= (1 &lt;&lt; (c-&#8216;a&#8217;)). <br>However, the bitmask only represents the state of the prefix, i.e. word[0:i], then how can we count substrings? The answer is hashtable.  If the same bitmask occurs c times before, which means there are c indices that word[0~j1], word[0~j2], &#8230;, word[0~jc] have the same state as word[0~i] that means for word[j1+1~i], word[j2+1~i], &#8230;, word[jc+1~i], all letters occurred even times. <br>For the &#8220;at most one odd&#8221; case, we toggle each bit of the bitmask and check how many times it occurred before.</p>



<p>ans += freq[mask] + sum(freq[mask ^ (1 &lt;&lt; i)] for i in range(k))</p>



<p>Time complexity: O(n*k)<br>Space complexity: O(2<sup>k</sup>)<br>where k = j &#8211; a + 1 = 10</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  long long wonderfulSubstrings(string word) {
    constexpr int l = 'j' - 'a' + 1;
    vector&lt;int&gt; count(1 &lt;&lt; l);
    count[0] = 1;
    int mask = 0;
    long long ans = 0;
    for (char c : word) {
      mask ^= 1 &lt;&lt; (c - 'a'); 
      for (int i = 0; i &lt; l; ++i)
        ans += count[mask ^ (1 &lt;&lt; i)]; // one odd.
      ans += count[mask]++; // all even.
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1915-number-of-wonderful-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2100. Find Good Days to Rob the Bank</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2100-find-good-days-to-rob-the-bank/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2100-find-good-days-to-rob-the-bank/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Dec 2021 18:54:07 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[suffix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9136</guid>

					<description><![CDATA[You and a gang of thieves are planning on robbing a bank. You are given a&#160;0-indexed&#160;integer array&#160;security, where&#160;security[i]&#160;is the number of guards on duty on&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You and a gang of thieves are planning on robbing a bank. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>security</code>, where&nbsp;<code>security[i]</code>&nbsp;is the number of guards on duty on the&nbsp;<code>i<sup>th</sup></code>&nbsp;day. The days are numbered starting from&nbsp;<code>0</code>. You are also given an integer&nbsp;<code>time</code>.</p>



<p>The&nbsp;<code>i<sup>th</sup></code>&nbsp;day is a good day to rob the bank if:</p>



<ul class="wp-block-list"><li>There are at least&nbsp;<code>time</code>&nbsp;days before and after the&nbsp;<code>i<sup>th</sup></code>&nbsp;day,</li><li>The number of guards at the bank for the&nbsp;<code>time</code>&nbsp;days&nbsp;<strong>before</strong>&nbsp;<code>i</code>&nbsp;are&nbsp;<strong>non-increasing</strong>, and</li><li>The number of guards at the bank for the&nbsp;<code>time</code>&nbsp;days&nbsp;<strong>after</strong>&nbsp;<code>i</code>&nbsp;are&nbsp;<strong>non-decreasing</strong>.</li></ul>



<p>More formally, this means day&nbsp;<code>i</code>&nbsp;is a good day to rob the bank if and only if&nbsp;<code>security[i - time] &gt;= security[i - time + 1] &gt;= ... &gt;= security[i] &lt;= ... &lt;= security[i + time - 1] &lt;= security[i + time]</code>.</p>



<p>Return&nbsp;<em>a list of&nbsp;<strong>all</strong>&nbsp;days&nbsp;<strong>(0-indexed)&nbsp;</strong>that are good days to rob the bank</em>.<em>&nbsp;The order that the days are returned in does<strong>&nbsp;</strong><strong>not</strong>&nbsp;matter.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> security = [5,3,3,3,5,6,2], time = 2
<strong>Output:</strong> [2,3]
<strong>Explanation:</strong>
On day 2, we have security[0] &gt;= security[1] &gt;= security[2] &lt;= security[3] &lt;= security[4].
On day 3, we have security[1] &gt;= security[2] &gt;= security[3] &lt;= security[4] &lt;= security[5].
No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> security = [1,1,1,1,1], time = 0
<strong>Output:</strong> [0,1,2,3,4]
<strong>Explanation:</strong>
Since time equals 0, every day is a good day to rob the bank, so return every day.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> security = [1,2,3,4,5,6], time = 2
<strong>Output:</strong> []
<strong>Explanation:</strong>
No day has 2 days before it that have a non-increasing number of guards.
Thus, no day is a good day to rob the bank, so return an empty list.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> security = [1], time = 5
<strong>Output:</strong> []
<strong>Explanation:</strong>
No day has 5 days before and after it.
Thus, no day is a good day to rob the bank, so return an empty list.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= security.length &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= security[i], time &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Pre-Processing</strong></h2>



<p>Pre-compute the non-increasing days at days[i] and the non-decreasing days at days[i] using prefix and suffix arrays.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; goodDaysToRobBank(vector&lt;int&gt;&amp; security, int time) {
    const int n = security.size();
    vector&lt;int&gt; before(n);
    vector&lt;int&gt; after(n);
    for (int i = 1; i &lt; n; ++i)
      before[i] = security[i - 1] &gt;= security[i] ? before[i - 1] + 1 : 0;
    for (int i = n - 2; i &gt;= 0; --i)
      after[i] = security[i + 1] &gt;= security[i] ? after[i + 1] + 1 : 0;
    vector&lt;int&gt; ans;
    for (int i = time; i + time &lt; n; ++i)
      if (before[i] &gt;= time &amp;&amp; after[i] &gt;= time)
        ans.push_back(i);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2100-find-good-days-to-rob-the-bank/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 201. Bitwise AND of Numbers Range</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-201-bitwise-and-of-numbers-range/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-201-bitwise-and-of-numbers-range/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Dec 2021 02:38:22 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9038</guid>

					<description><![CDATA[Given two integers&#160;left&#160;and&#160;right&#160;that represent the range&#160;[left, right], return&#160;the bitwise AND of all numbers in this range, inclusive. Example 1: Input: left = 5, right =&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given two integers&nbsp;<code>left</code>&nbsp;and&nbsp;<code>right</code>&nbsp;that represent the range&nbsp;<code>[left, right]</code>, return&nbsp;<em>the bitwise AND of all numbers in this range, inclusive</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> left = 5, right = 7
<strong>Output:</strong> 4
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> left = 0, right = 0
<strong>Output:</strong> 0
</pre>



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



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



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



<ul class="wp-block-list"><li><code>0 &lt;= left &lt;= right &lt;= 2<sup>31</sup>&nbsp;- 1</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Bit operation</strong></h2>



<p>Bitwise AND all the numbers between left and right will clear out all the <strong>low bits</strong>. Basically this question is asking to find the common prefix of left and right in the binary format.</p>



<p><br>5 = 0b0101<br>7 = 0b0111<br>the common prefix is 0b0100 which is 4.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int rangeBitwiseAnd(int left, int right) {
    while (right &gt; left)
      right &amp;= (right - 1); // clears the lowest set bit.
    return right;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/bit/leetcode-201-bitwise-and-of-numbers-range/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[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;]]></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 class="wp-block-list"><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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 1764. Form Array by Concatenating Subarrays of Another Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1764-form-array-by-concatenating-subarrays-of-another-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1764-form-array-by-concatenating-subarrays-of-another-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Feb 2021 00:32:23 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[kmp]]></category>
		<category><![CDATA[matching]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8131</guid>

					<description><![CDATA[You are given a 2D integer array&#160;groups&#160;of length&#160;n. You are also given an integer array&#160;nums. You are asked if you can choose&#160;n&#160;disjoint&#160;subarrays from the array&#160;nums&#160;such&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a 2D integer array&nbsp;<code>groups</code>&nbsp;of length&nbsp;<code>n</code>. You are also given an integer array&nbsp;<code>nums</code>.</p>



<p>You are asked if you can choose&nbsp;<code>n</code>&nbsp;<strong>disjoint&nbsp;</strong>subarrays from the array&nbsp;<code>nums</code>&nbsp;such that the&nbsp;<code>i<sup>th</sup></code>&nbsp;subarray is equal to&nbsp;<code>groups[i]</code>&nbsp;(<strong>0-indexed</strong>), and if&nbsp;<code>i &gt; 0</code>, the&nbsp;<code>(i-1)<sup>th</sup></code>&nbsp;subarray appears&nbsp;<strong>before</strong>&nbsp;the&nbsp;<code>i<sup>th</sup></code>&nbsp;subarray in&nbsp;<code>nums</code>&nbsp;(i.e. the subarrays must be in the same order as&nbsp;<code>groups</code>).</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if you can do this task, and</em>&nbsp;<code>false</code>&nbsp;<em>otherwise</em>.</p>



<p>Note that the subarrays are&nbsp;<strong>disjoint</strong>&nbsp;if and only if there is no index&nbsp;<code>k</code>&nbsp;such that&nbsp;<code>nums[k]</code>&nbsp;belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can choose the 0<sup>th</sup> subarray as [1,-1,0,<strong>1,-1,-1</strong>,3,-2,0] and the 1<sup>st</sup> one as [1,-1,0,1,-1,-1,<strong>3,-2,0</strong>].
These subarrays are disjoint as they share no common nums[k] element.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]
<strong>Output:</strong> false
<strong>Explanation: </strong>Note that choosing the subarrays [<strong>1,2,3,4</strong>,10,-2] and [1,2,3,4,<strong>10,-2</strong>] is incorrect because they are not in the same order as in groups.
[10,-2] must come before [1,2,3,4].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]
<strong>Output:</strong> false
<strong>Explanation: </strong>Note that choosing the subarrays [7,7,<strong>1,2,3</strong>,4,7,7] and [7,7,1,2,<strong>3,4</strong>,7,7] is invalid because they are not disjoint.
They share a common elements nums[4] (0-indexed).
</pre>



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



<ul class="wp-block-list"><li><code>groups.length == n</code></li><li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li><li><code>1 &lt;= groups[i].length, sum(groups[i].length) &lt;= 10<sup>3</sup></code></li><li><code>1 &lt;= nums.length &lt;= 10<sup>3</sup></code></li><li><code>-10<sup>7</sup>&nbsp;&lt;= groups[i][j], nums[k] &lt;= 10<sup>7</sup></code></li></ul>



<p></p>



<h2 class="wp-block-heading"><strong>Solution: Brute Force</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool canChoose(vector&lt;vector&lt;int&gt;&gt;&amp; groups, vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int s = 0;
    for (const auto&amp; g : groups) {
      bool found = false;
      for (int i = s; i &lt;= n - g.size(); ++i)
        if (equal(begin(g), end(g), begin(nums) + i)) {
          s = i + g.size();
          found = true;
          break;
        }
      if (!found) return false;
    }
    return true;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1764-form-array-by-concatenating-subarrays-of-another-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1744. Can You Eat Your Favorite Candy on Your Favorite Day?</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1744-can-you-eat-your-favorite-candy-on-your-favorite-day/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1744-can-you-eat-your-favorite-candy-on-your-favorite-day/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 31 Jan 2021 05:33:27 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8052</guid>

					<description><![CDATA[You are given a&#160;(0-indexed)&#160;array of positive integers&#160;candiesCount&#160;where&#160;candiesCount[i]&#160;represents the number of candies of the&#160;ith&#160;type you have. You are also given a 2D array&#160;queries&#160;where&#160;queries[i] = [favoriteTypei, favoriteDayi,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>(0-indexed)</strong>&nbsp;array of positive integers&nbsp;<code>candiesCount</code>&nbsp;where&nbsp;<code>candiesCount[i]</code>&nbsp;represents the number of candies of the&nbsp;<code>i<sup>th</sup></code>&nbsp;type you have. You are also given a 2D array&nbsp;<code>queries</code>&nbsp;where&nbsp;<code>queries[i] = [favoriteType<sub>i</sub>, favoriteDay<sub>i</sub>, dailyCap<sub>i</sub>]</code>.</p>



<p>You play a game with the following rules:</p>



<ul class="wp-block-list"><li>You start eating candies on day&nbsp;<code><strong>0</strong></code>.</li><li>You&nbsp;<strong>cannot</strong>&nbsp;eat&nbsp;<strong>any</strong>&nbsp;candy of type&nbsp;<code>i</code>&nbsp;unless you have eaten&nbsp;<strong>all</strong>&nbsp;candies of type&nbsp;<code>i - 1</code>.</li><li>You must eat&nbsp;<strong>at least</strong>&nbsp;<strong>one</strong>&nbsp;candy per day until you have eaten all the candies.</li></ul>



<p>Construct a boolean array&nbsp;<code>answer</code>&nbsp;such that&nbsp;<code>answer.length == queries.length</code>&nbsp;and&nbsp;<code>answer[i]</code>&nbsp;is&nbsp;<code>true</code>&nbsp;if you can eat a candy of type&nbsp;<code>favoriteType<sub>i</sub></code>&nbsp;on day&nbsp;<code>favoriteDay<sub>i</sub></code>&nbsp;without eating&nbsp;<strong>more than</strong>&nbsp;<code>dailyCap<sub>i</sub></code>&nbsp;candies on&nbsp;<strong>any</strong>&nbsp;day, and&nbsp;<code>false</code>&nbsp;otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.</p>



<p>Return&nbsp;<em>the constructed array&nbsp;</em><code>answer</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
<strong>Output:</strong> [true,false,true]
<strong>Explanation:</strong>
1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
2- You can eat at most 4 candies each day.
   If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
   On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
<strong>Output:</strong> [false,true,true,false,false]
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= candiesCount.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= candiesCount[i] &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li><li><code>queries[i].length == 3</code></li><li><code>0 &lt;= favoriteType<sub>i</sub>&nbsp;&lt; candiesCount.length</code></li><li><code>0 &lt;= favoriteDay<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= dailyCap<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Prefix Sum</strong></h2>



<ol class="wp-block-list"><li>We must have enough capacity to eat all candies before the current type.</li><li>We must have at least prefix sum candies than days, since we have to eat at least one each day.</li></ol>



<p>sum[i] = sum(candyCount[0~i])<br>ans = {days * cap &gt; sum[type &#8211; 1] &amp;&amp; days &lt;= sum[type])</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="urvanov-syntax-highlighter-plain-tag">// Author: Huhua
class Solution {
public:
  vector&lt;bool&gt; canEat(vector&lt;int&gt;&amp; candiesCount, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    const int n = candiesCount.size();
    vector&lt;long&gt; sums(n + 1);    
    for (int i = 1; i &lt;= n; ++i)
      sums[i] += sums[i - 1] + candiesCount[i - 1];
    vector&lt;bool&gt; ans;
    for (const auto&amp; q : queries) {
      const long type = q[0], days = q[1] + 1, cap = q[2];
      ans.push_back(days * cap &gt; sums[type] &amp;&amp; days &lt;= sums[type + 1]);
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1744-can-you-eat-your-favorite-candy-on-your-favorite-day/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1658. Minimum Operations to Reduce X to Zero</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1658-minimum-operations-to-reduce-x-to-zero/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1658-minimum-operations-to-reduce-x-to-zero/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Nov 2020 04:59:07 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7675</guid>

					<description><![CDATA[You are given an integer array&#160;nums&#160;and an integer&#160;x. In one operation, you can either remove the leftmost or the rightmost element from the array&#160;nums&#160;and subtract&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>x</code>. In one operation, you can either remove the leftmost or the rightmost element from the array&nbsp;<code>nums</code>&nbsp;and subtract its value from&nbsp;<code>x</code>. Note that this&nbsp;<strong>modifies</strong>&nbsp;the array for future operations.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum number</strong>&nbsp;of operations to reduce&nbsp;</em><code>x</code>&nbsp;<em>to&nbsp;<strong>exactly</strong></em>&nbsp;<code>0</code>&nbsp;<em>if it&#8217;s possible</em><em>, otherwise, return&nbsp;</em><code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,4,2,3], x = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> The optimal solution is to remove the last two elements to reduce x to zero.
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,20,1,1,3], x = 10
<strong>Output:</strong> 5
<strong>Explanation:</strong> The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= x &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution1: Prefix Sum + Hashtable</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; nums, int x) {
    const int n = nums.size();
    vector&lt;int&gt; l(n), r(n);
    unordered_map&lt;int, int&gt; ml, mr;
    ml[0] = mr[0] = -1;
    for (int i = 0; i &lt; n; ++i) {
      l[i] = nums[i] + (i &gt; 0 ? l[i - 1] : 0);      
      r[i] = nums[n - i - 1] + (i &gt; 0 ? r[i - 1]: 0);
      ml[l[i]] = mr[r[i]] = i;
    }
    int ans = INT_MAX;
    for (int i = 0; i &lt; n; ++i) {
      int s1 = x - l[i];
      auto it1 = mr.find(s1);
      if (it1 != mr.end()) ans = min(ans, i + 1 + it1-&gt;second + 1);
      int s2 = x - r[i];
      auto it2 = ml.find(s2);
      if (it2 != ml.end()) ans = min(ans, i + 1 + it2-&gt;second + 1);      
    }
    return ans &gt; n ? -1 : ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution2: Sliding Window</strong></h2>



<p>Find the longest sliding window whose sum of elements equals sum(nums) &#8211; x<br>ans = n &#8211; window_size</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; nums, int x) {
    const int n = nums.size();
    int target = accumulate(begin(nums), end(nums), 0) - x;    
    int ans = INT_MAX;
    for (int s = 0, l = 0, r = 0; r &lt; n; ++r) {
      s += nums[r];
      while (s &gt; target &amp;&amp; l &lt;= r) s -= nums[l++];
      if (s == target) ans = min(ans, n - (r - l + 1));
    }
    return ans &gt; n ? -1 : ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1658-minimum-operations-to-reduce-x-to-zero/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1638. Count Substrings That Differ by One Character</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1638-count-substrings-that-differ-by-one-character/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1638-count-substrings-that-differ-by-one-character/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 31 Oct 2020 20:42:07 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7585</guid>

					<description><![CDATA[Given two strings&#160;s&#160;and&#160;t, find the number of ways you can choose a non-empty substring of&#160;s&#160;and replace a&#160;single character&#160;by a different character such that the resulting&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given two strings&nbsp;<code>s</code>&nbsp;and&nbsp;<code>t</code>, find the number of ways you can choose a non-empty substring of&nbsp;<code>s</code>&nbsp;and replace a&nbsp;<strong>single character</strong>&nbsp;by a different character such that the resulting substring is a substring of&nbsp;<code>t</code>. In other words, find the number of substrings in&nbsp;<code>s</code>&nbsp;that differ from some substring in&nbsp;<code>t</code>&nbsp;by&nbsp;<strong>exactly</strong>&nbsp;one character.</p>



<p>For example, the underlined substrings in&nbsp;<code>"computer"</code>&nbsp;and&nbsp;<code>"computation"</code>&nbsp;only differ by the&nbsp;<code>'e'</code>/<code>'a'</code>, so this is a valid way.</p>



<p>Return&nbsp;<em>the number of substrings that satisfy the condition above.</em></p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aba", t = "baba"
<strong>Output:</strong> 6
<strong>Explanation: </strong>The following are the pairs of substrings from s and t that differ by exactly 1 character:
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
The underlined portions are the substrings that are chosen from s and t.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ab", t = "bb"
<strong>Output:</strong> 3
<strong>Explanation: </strong>The following are the pairs of substrings from s and t that differ by 1 character:
("ab", "bb")
("ab", "bb")
("ab", "bb")
​​​​The underlined portions are the substrings that are chosen from s and t.
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abe", t = "bbc"
<strong>Output:</strong> 10
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= s.length, t.length &lt;= 100</code></li><li><code>s</code>&nbsp;and&nbsp;<code>t</code>&nbsp;consist of lowercase English letters only.</li></ul>



<h2 class="wp-block-heading"><strong>Solution1: All Pairs + Prefix Matching</strong></h2>



<p>match s[i:i+p] with t[j:j+p], is there is one missed char, increase the ans, until there are two miss matched chars or reach the end.</p>



<p>Time complexity: O(m*n*min(m,n))<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int countSubstrings(string s, string t) {
    const int m = s.length();
    const int n = t.length();
    int ans = 0, diff = 0;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j, diff = 0)
        for (int p = 0; i + p &lt; m &amp;&amp; j + p &lt; n &amp;&amp; diff &lt;= 1; ++p)          
          if ((diff += (s[i + p] != t[j + p])) == 1) ++ans;
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Continuous Matching</strong></h2>



<p>Start matching s[0] with t[j] and s[i] with t[0]</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int countSubstrings(string s, string t) {
    const int m = s.length();
    const int n = t.length();
    int ans = 0;
    auto helper = [&amp;](int i, int j) {      
      for (int cur = 0, pre = 0; i &lt; m &amp;&amp; j &lt; n; ++i, ++j) {
        ++cur;
        if (s[i] != t[j]) {
          pre = cur;
          cur = 0;
        }
        ans += pre;
      }
    };
    for (int i = 0; i &lt; m; ++i) helper(i, 0);
    for (int j = 1; j &lt; n; ++j) helper(0, j);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1638-count-substrings-that-differ-by-one-character/feed/</wfw:commentRss>
			<slash:comments>0</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[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;]]></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 loading="lazy" 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; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" 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 class="wp-block-list"><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s</code>&nbsp;consists only of digits.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Prefix mask + Hashtable</strong></h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" 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="auto, (max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" 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="auto, (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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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>
]]></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 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 May 2020 05:13:48 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[word]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6810</guid>

					<description><![CDATA[Given a&#160;sentence&#160;that consists of some words separated by a&#160;single space, and a&#160;searchWord. You have to check if&#160;searchWord&#160;is a prefix of any word in&#160;sentence. Return&#160;the index&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<code>sentence</code>&nbsp;that consists of some words separated by a&nbsp;<strong>single space</strong>, and a&nbsp;<code>searchWord</code>.</p>



<p>You have to check if&nbsp;<code>searchWord</code>&nbsp;is a prefix of any word in&nbsp;<code>sentence</code>.</p>



<p>Return&nbsp;<em>the index of the word</em>&nbsp;in&nbsp;<code>sentence</code>&nbsp;where&nbsp;<code>searchWord</code>&nbsp;is a prefix of this word (<strong>1-indexed</strong>).</p>



<p>If&nbsp;<code>searchWord</code>&nbsp;is&nbsp;a prefix of more than one word, return the index of the first word&nbsp;<strong>(minimum index)</strong>. If there is no such word return&nbsp;<strong>-1</strong>.</p>



<p>A&nbsp;<strong>prefix</strong>&nbsp;of a string&nbsp;<code>S</code>&nbsp;is any leading contiguous substring of&nbsp;<code>S</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence = "i love eating burger", searchWord = "burg"
<strong>Output:</strong> 4
<strong>Explanation:</strong> "burg" is prefix of "burger" which is the 4th word in the sentence.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence = "this problem is an easy problem", searchWord = "pro"
<strong>Output:</strong> 2
<strong>Explanation:</strong> "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence = "i am tired", searchWord = "you"
<strong>Output:</strong> -1
<strong>Explanation:</strong> "you" is not a prefix of any word in the sentence.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence = "i use triple pillow", searchWord = "pill"
<strong>Output:</strong> 4
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence = "hello from the other side", searchWord = "they"
<strong>Output:</strong> -1
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= sentence.length &lt;= 100</code></li><li><code>1 &lt;= searchWord.length &lt;= 10</code></li><li><code>sentence</code>&nbsp;consists of lowercase English letters and spaces.</li><li><code>searchWord</code>&nbsp;consists of lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Brute Force</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="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int isPrefixOfWord(string sentence, string searchWord) {
    const int n = sentence.size();
    const int l = searchWord.size();
    int word = 0;
    for (int i = 0; i &lt;= n - l; ++i) {
      if (i == 0 || sentence[i - 1] == ' ') {
        ++word;
        bool valid = true;
        for (int j = 0; j &lt; l &amp;&amp; valid; ++j)
          valid = valid &amp;&amp; (sentence[i + j] == searchWord[j]);
        if (valid) return word;      
      }
    }
    return -1;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
