<?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>counting Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/counting/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/counting/</link>
	<description></description>
	<lastBuildDate>Sat, 02 Apr 2022 22:22:58 +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>counting Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/counting/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2222. Number of Ways to Select Buildings</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2222-number-of-ways-to-select-buildings/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2222-number-of-ways-to-select-buildings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 02 Apr 2022 22:22:12 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9609</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;binary string&#160;s&#160;which represents the types of buildings along a street where: s[i] = '0'&#160;denotes that the&#160;ith&#160;building is an office and s[i] =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2222-number-of-ways-to-select-buildings/">花花酱 LeetCode 2222. Number of Ways to Select Buildings</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;binary string&nbsp;<code>s</code>&nbsp;which represents the types of buildings along a street where:</p>



<ul><li><code>s[i] = '0'</code>&nbsp;denotes that the&nbsp;<code>i<sup>th</sup></code>&nbsp;building is an office and</li><li><code>s[i] = '1'</code>&nbsp;denotes that the&nbsp;<code>i<sup>th</sup></code>&nbsp;building is a restaurant.</li></ul>



<p>As a city official, you would like to&nbsp;<strong>select</strong>&nbsp;3 buildings for random inspection. However, to ensure variety,&nbsp;<strong>no two consecutive</strong>&nbsp;buildings out of the&nbsp;<strong>selected</strong>&nbsp;buildings can be of the same type.</p>



<ul><li>For example, given&nbsp;<code>s = "0<u><strong>0</strong></u>1<u><strong>1</strong></u>0<u><strong>1</strong></u>"</code>, we cannot select the&nbsp;<code>1<sup>st</sup></code>,&nbsp;<code>3<sup>rd</sup></code>, and&nbsp;<code>5<sup>th</sup></code>&nbsp;buildings as that would form&nbsp;<code>"0<strong><u>11</u></strong>"</code>&nbsp;which is&nbsp;<strong>not</strong>&nbsp;allowed due to having two consecutive buildings of the same type.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>number of valid ways</strong>&nbsp;to select 3 buildings.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "001101"
<strong>Output:</strong> 6
<strong>Explanation:</strong> 
The following sets of indices selected are valid:
- [0,2,4] from "<strong>0</strong>0<strong><u>1</u></strong>1<strong><u>0</u></strong>1" forms "010"
- [0,3,4] from "<strong>0</strong>01<strong>10</strong>1" forms "010"
- [1,2,4] from "0<strong>01</strong>1<strong>0</strong>1" forms "010"
- [1,3,4] from "0<strong>0</strong>1<strong>10</strong>1" forms "010"
- [2,4,5] from "00<strong>1</strong>1<strong>01</strong>" forms "101"
- [3,4,5] from "001<strong>101</strong>" forms "101"
No other selection is valid. Thus, there are 6 total ways.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "11100"
<strong>Output:</strong> 0
<strong>Explanation:</strong> It can be shown that there are no valid selections.
</pre>



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



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



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



<p>The brute force solution will take O(n<sup>3</sup>) which will lead to TLE.</p>



<p>Since the only two valid cases are &#8220;010&#8221; and &#8220;101&#8221;.</p>



<p>We just need to count how many 0s and 1s, thus we can count 01s and 10s and finally 010s and 101s.</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 numberOfWays(string s) {    
    long long c0 = 0, c1 = 0, c01 = 0, c10 = 0, c101 = 0, c010 = 0;
    for (char c : s) {
      if (c == '0') {
        ++c0;
        c10 += c1;
        c010 += c01;
      } else {
        ++c1;
        c01 += c0;
        c101 += c10;
      }
    }
    return c101 + c010;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2222-number-of-ways-to-select-buildings/">花花酱 LeetCode 2222. Number of Ways to Select Buildings</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-2222-number-of-ways-to-select-buildings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 19 Oct 2021 00:55:36 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[counting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8620</guid>

					<description><![CDATA[<p>There are&#160;n&#160;pieces arranged in a line, and each piece is colored either by&#160;'A'&#160;or by&#160;'B'. You are given a string&#160;colors&#160;of length&#160;n&#160;where&#160;colors[i]&#160;is the color of the&#160;ith&#160;piece. Alice&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/">花花酱 LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color</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 are&nbsp;<code>n</code>&nbsp;pieces arranged in a line, and each piece is colored either by&nbsp;<code>'A'</code>&nbsp;or by&nbsp;<code>'B'</code>. You are given a string&nbsp;<code>colors</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where&nbsp;<code>colors[i]</code>&nbsp;is the color of the&nbsp;<code>i<sup>th</sup></code>&nbsp;piece.</p>



<p>Alice and Bob are playing a game where they take&nbsp;<strong>alternating turns</strong>&nbsp;removing pieces from the line. In this game, Alice moves<strong>&nbsp;first</strong>.</p>



<ul><li>Alice is only allowed to remove a piece colored&nbsp;<code>'A'</code>&nbsp;if&nbsp;<strong>both its neighbors</strong>&nbsp;are also colored&nbsp;<code>'A'</code>. She is&nbsp;<strong>not allowed</strong>&nbsp;to remove pieces that are colored&nbsp;<code>'B'</code>.</li><li>Bob is only allowed to remove a piece colored&nbsp;<code>'B'</code>&nbsp;if&nbsp;<strong>both its neighbors</strong>&nbsp;are also colored&nbsp;<code>'B'</code>. He is&nbsp;<strong>not allowed</strong>&nbsp;to remove pieces that are colored&nbsp;<code>'A'</code>.</li><li>Alice and Bob&nbsp;<strong>cannot</strong>&nbsp;remove pieces from the edge of the line.</li><li>If a player cannot make a move on their turn, that player&nbsp;<strong>loses</strong>&nbsp;and the other player&nbsp;<strong>wins</strong>.</li></ul>



<p>Assuming Alice and Bob play optimally, return&nbsp;<code>true</code><em>&nbsp;if Alice wins, or return&nbsp;</em><code>false</code><em>&nbsp;if Bob wins</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> colors = "AAABABB"
<strong>Output:</strong> true
<strong>Explanation:</strong>
AAABABB -&gt; AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.

Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> colors = "AA"
<strong>Output:</strong> false
<strong>Explanation:</strong>
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> colors = "ABBBBBBBAAA"
<strong>Output:</strong> false
<strong>Explanation:</strong>
ABBBBBBBAAA -&gt; ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last 'A' from the right.

ABBBBBBBAA -&gt; ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.

On Alice's second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.
</pre>



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



<ul><li><code>1 &lt;=&nbsp;colors.length &lt;= 10<sup>5</sup></code></li><li><code>colors</code>&nbsp;consists of only the letters&nbsp;<code>'A'</code>&nbsp;and&nbsp;<code>'B'</code></li></ul>



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



<p>Count how many &#8216;AAA&#8217;s and &#8216;BBB&#8217;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:
  bool winnerOfGame(string colors) {
    const int n = colors.size();
    int count = 0;
    for (int i = 1; i &lt; n - 1; ++i)
      if (colors[i - 1] == colors[i] &amp;&amp;
          colors[i] == colors[i + 1])
        count += (colors[i] == 'A' ? 1 : -1);    
    return count &gt; 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/">花花酱 LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1897. Redistribute Characters to Make All Strings Equal</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1897-redistribute-characters-to-make-all-strings-equal/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1897-redistribute-characters-to-make-all-strings-equal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 11 Aug 2021 19:20:06 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8562</guid>

					<description><![CDATA[<p>You are given an array of strings&#160;words&#160;(0-indexed). In one operation, pick two&#160;distinct&#160;indices&#160;i&#160;and&#160;j, where&#160;words[i]&#160;is a non-empty string, and move&#160;any&#160;character from&#160;words[i]&#160;to&#160;any&#160;position in&#160;words[j]. Return&#160;true&#160;if you can make&#160;every&#160;string in&#160;words&#160;equal&#160;using&#160;any&#160;number&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1897-redistribute-characters-to-make-all-strings-equal/">花花酱 LeetCode 1897. Redistribute Characters to Make All Strings Equal</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of strings&nbsp;<code>words</code>&nbsp;(<strong>0-indexed</strong>).</p>



<p>In one operation, pick two&nbsp;<strong>distinct</strong>&nbsp;indices&nbsp;<code>i</code>&nbsp;and&nbsp;<code>j</code>, where&nbsp;<code>words[i]</code>&nbsp;is a non-empty string, and move&nbsp;<strong>any</strong>&nbsp;character from&nbsp;<code>words[i]</code>&nbsp;to&nbsp;<strong>any</strong>&nbsp;position in&nbsp;<code>words[j]</code>.</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if you can make<strong>&nbsp;every</strong>&nbsp;string in&nbsp;</em><code>words</code><em>&nbsp;<strong>equal&nbsp;</strong>using&nbsp;<strong>any</strong>&nbsp;number of operations</em>,<em>&nbsp;and&nbsp;</em><code>false</code>&nbsp;<em>otherwise</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["abc","aabc","bc"]
<strong>Output:</strong> true
<strong>Explanation:</strong> Move the first 'a' in <code>words[1] to the front of words[2],
to make </code><code>words[1]</code> = "abc" and words[2] = "abc".
All the strings are now equal to "abc", so return <code>true</code>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["ab","a"]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to make all the strings equal using the operation.
</pre>



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



<ul><li><code>1 &lt;= words.length &lt;= 100</code></li><li><code>1 &lt;= words[i].length &lt;= 100</code></li><li><code>words[i]</code>&nbsp;consists of lowercase English letters.</li></ul>



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



<p>Count the frequency of each character, it must be a multiplier of n such that we can evenly distribute it to all the words.<br>e.g. n = 3, a = 9, b = 6, c = 3, each word will be &#8220;aaabbc&#8221;.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool makeEqual(vector&lt;string&gt;&amp; words) {
    vector&lt;int&gt; freq(26);
    for (const auto&amp; word : words)
      for (char c : word)
        ++freq[c - 'a'];    
    for (int f : freq)
      if (f % words.size()) return false;        
    return true;
  }
};</pre>

</div><h2 class="tabtitle">Python3 one-liner</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def makeEqual(self, words: List[str]) -&gt; bool:
    return all(c % len(words) == 0 for c in Counter(''.join(words)).values())</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1897-redistribute-characters-to-make-all-strings-equal/">花花酱 LeetCode 1897. Redistribute Characters to Make All Strings Equal</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-1897-redistribute-characters-to-make-all-strings-equal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 05 Aug 2021 06:26:50 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8478</guid>

					<description><![CDATA[<p>There are&#160;n&#160;uniquely-sized sticks whose lengths are integers from&#160;1&#160;to&#160;n. You want to arrange the sticks such that&#160;exactly&#160;k&#160;sticks are&#160;visible&#160;from the left. A stick&#160;is&#160;visible&#160;from the left if there&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible/">花花酱 LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible</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 are&nbsp;<code>n</code>&nbsp;uniquely-sized sticks whose lengths are integers from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>. You want to arrange the sticks such that&nbsp;<strong>exactly</strong>&nbsp;<code>k</code>&nbsp;sticks are&nbsp;<strong>visible</strong>&nbsp;from the left. A stick&nbsp;is&nbsp;<strong>visible</strong>&nbsp;from the left if there are no&nbsp;<strong>longer</strong>&nbsp;sticks to the&nbsp;<strong>left</strong>&nbsp;of it.</p>



<ul><li>For example, if the sticks are arranged&nbsp;<code>[<u>1</u>,<u>3</u>,2,<u>5</u>,4]</code>, then the sticks with lengths&nbsp;<code>1</code>,&nbsp;<code>3</code>, and&nbsp;<code>5</code>&nbsp;are visible from the left.</li></ul>



<p>Given&nbsp;<code>n</code>&nbsp;and&nbsp;<code>k</code>, return&nbsp;<em>the&nbsp;<strong>number</strong>&nbsp;of such arrangements</em>. Since the answer may be large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, k = 5
<strong>Output:</strong> 1
<strong>Explanation:</strong> [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 20, k = 11
<strong>Output:</strong> 647427950
<strong>Explanation:</strong> There are 647427950 (mod 10<sup>9 </sup>+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
</pre>



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



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



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



<p>dp(n, k) = dp(n &#8211; 1, k &#8211; 1) + (n-1) * dp(n-1, k)</p>



<p>Time complexity: O(n*k)<br>Space complexity: O(n*k) -&gt; O(k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int rearrangeSticks(int n, int k) {
    constexpr int kMod = 1e9 + 7;
    vector&lt;vector&lt;long&gt;&gt; dp(n + 1, vector&lt;long&gt;(k + 1));        
    for (int j = 1; j &lt;= k; ++j) {
      dp[j][j] = 1;
      for (int i = j + 1; i &lt;= n; ++i)
        dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j] * (i - 1)) % kMod;
    }
    return dp[n][k];
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  @lru_cache(maxsize=None)
  def rearrangeSticks(self, n: int, k: int) -&gt; int:
    if k == 0: return 0
    if k == n or n &lt;= 2: return 1
    return (self.rearrangeSticks(n - 1, k - 1) + 
            (n - 1) * self.rearrangeSticks(n - 1, k)) % (10**9 + 7)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible/">花花酱 LeetCode 1866. Number of Ways to Rearrange Sticks With K Sticks Visible</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-1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1817. Finding the Users Active Minutes</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1817-finding-the-users-active-minutes/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1817-finding-the-users-active-minutes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 07 Apr 2021 00:05:02 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[hashset]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8323</guid>

					<description><![CDATA[<p>You are given the logs for users&#8217; actions on LeetCode, and an integer&#160;k. The logs are represented by a 2D integer array&#160;logs&#160;where each&#160;logs[i] = [IDi,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1817-finding-the-users-active-minutes/">花花酱 LeetCode 1817. Finding the Users Active Minutes</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given the logs for users&#8217; actions on LeetCode, and an integer&nbsp;<code>k</code>. The logs are represented by a 2D integer array&nbsp;<code>logs</code>&nbsp;where each&nbsp;<code>logs[i] = [ID<sub>i</sub>, time<sub>i</sub>]</code>&nbsp;indicates that the user with&nbsp;<code>ID<sub>i</sub></code>&nbsp;performed an action at the minute&nbsp;<code>time<sub>i</sub></code>.</p>



<p><strong>Multiple users</strong>&nbsp;can perform actions simultaneously, and a single user can perform&nbsp;<strong>multiple actions</strong>&nbsp;in the same minute.</p>



<p>The&nbsp;<strong>user active minutes (UAM)</strong>&nbsp;for a given user is defined as the&nbsp;<strong>number of unique minutes</strong>&nbsp;in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.</p>



<p>You are to calculate a&nbsp;<strong>1-indexed</strong>&nbsp;array&nbsp;<code>answer</code>&nbsp;of size&nbsp;<code>k</code>&nbsp;such that, for each&nbsp;<code>j</code>&nbsp;(<code>1 &lt;= j &lt;= k</code>),&nbsp;<code>answer[j]</code>&nbsp;is the&nbsp;<strong>number of users</strong>&nbsp;whose&nbsp;<strong>UAM</strong>&nbsp;equals&nbsp;<code>j</code>.</p>



<p>Return&nbsp;<em>the array&nbsp;</em><code>answer</code><em>&nbsp;as described above</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
<strong>Output:</strong> [0,2,0,0,0]
<strong>Explanation:</strong>
The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> logs = [[1,1],[2,2],[2,3]], k = 4
<strong>Output:</strong> [1,1,0,0]
<strong>Explanation:</strong>
The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
There is one user with a UAM of 1 and one with a UAM of 2.
Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.
</pre>



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



<ul><li><code>1 &lt;= logs.length &lt;= 10<sup>4</sup></code></li><li><code>0 &lt;= ID<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= time<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>k</code>&nbsp;is in the range&nbsp;<code>[The maximum&nbsp;<strong>UAM</strong>&nbsp;for a user, 10<sup>5</sup>]</code>.</li></ul>



<h2><strong>Solution: Hashsets in a Hashtable</strong></h2>



<p>key: user_id, value: set{time} </p>



<p>Time complexity: O(n + k)<br>Space complexity: O(n + k)</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; findingUsersActiveMinutes(vector&lt;vector&lt;int&gt;&gt;&amp; logs, int k) {
    unordered_map&lt;int, unordered_set&lt;int&gt;&gt; m;
    vector&lt;int&gt; ans(k);
    for (const auto&amp; log : logs)
      m[log[0]].insert(log[1]);
    for (const auto&amp; [id, s] : m)
      ++ans[s.size() - 1];
    return ans;
  }
};</pre>
</div></div>



<p><br></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1817-finding-the-users-active-minutes/">花花酱 LeetCode 1817. Finding the Users Active Minutes</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-1817-finding-the-users-active-minutes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1759. Count Number of Homogenous Substrings</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1759-count-number-of-homogenous-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1759-count-number-of-homogenous-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 04:55:02 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8105</guid>

					<description><![CDATA[<p>Given a string&#160;s, return&#160;the number of&#160;homogenous&#160;substrings of&#160;s.&#160;Since the answer may be too large, return it&#160;modulo&#160;109&#160;+ 7. A string is&#160;homogenous&#160;if all the characters of the string&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1759-count-number-of-homogenous-substrings/">花花酱 LeetCode 1759. Count Number of Homogenous Substrings</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 string&nbsp;<code>s</code>, return&nbsp;<em>the number of&nbsp;<strong>homogenous</strong>&nbsp;substrings of&nbsp;</em><code>s</code><em>.</em>&nbsp;Since the answer may be too large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p>A string is&nbsp;<strong>homogenous</strong>&nbsp;if all the characters of the string are the same.</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 = "abbcccaa"
<strong>Output:</strong> 13
<strong>Explanation:</strong> The homogenous substrings are listed as below:
"a"   appears 3 times.
"aa"  appears 1 time.
"b"   appears 2 times.
"bb"  appears 1 time.
"c"   appears 3 times.
"cc"  appears 2 times.
"ccc" appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "xy"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The homogenous substrings are "x" and "y".</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;consists of lowercase letters.</li></ul>



<p><strong>Solution: Counting</strong></p>



<p>Let m be the length of the longest homogenous substring, # of homogenous substring is m * (m + 1) / 2.<br>e.g. aaabb<br>&#8220;aaa&#8221; =&gt; m = 3,  # = 3 * (3 + 1) / 2 = 6<br>&#8220;bb&#8221; =&gt; m = 2, # = 2 * (2+1) / 2 = 3<br>Total = 6 + 3 = 9</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 countHomogenous(string s) {
    constexpr int kMod = 1e9 + 7;
    const int n = s.length();
    long ans = 0;
    for (long i = 0, j = 0; i &lt; n; i = j) {
      while (j &lt; n &amp;&amp; s[i] == s[j]) ++j;
      ans += (j - i) * (j - i + 1) / 2;
    }
    return ans % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1759-count-number-of-homogenous-substrings/">花花酱 LeetCode 1759. Count Number of Homogenous Substrings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1759-count-number-of-homogenous-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1758. Minimum Changes To Make Alternating Binary String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1758-minimum-changes-to-make-alternating-binary-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1758-minimum-changes-to-make-alternating-binary-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 04:34:31 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8102</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;consisting only of the characters&#160;'0'&#160;and&#160;'1'. In one operation, you can change any&#160;'0'&#160;to&#160;'1'&#160;or vice versa. The string is called alternating if no&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1758-minimum-changes-to-make-alternating-binary-string/">花花酱 LeetCode 1758. Minimum Changes To Make Alternating Binary String</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 string&nbsp;<code>s</code>&nbsp;consisting only of the characters&nbsp;<code>'0'</code>&nbsp;and&nbsp;<code>'1'</code>. In one operation, you can change any&nbsp;<code>'0'</code>&nbsp;to&nbsp;<code>'1'</code>&nbsp;or vice versa.</p>



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



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of operations needed to make</em>&nbsp;<code>s</code>&nbsp;<em>alternating</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0100"
<strong>Output:</strong> 1
<strong>Explanation:</strong> If you change the last character to '1', s will be "0101", which is alternating.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "10"
<strong>Output:</strong> 0
<strong>Explanation:</strong> s is already alternating.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1111"
<strong>Output:</strong> 2
<strong>Explanation:</strong> You need two operations to reach "0101" or "1010".
</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></ul>



<h2><strong>Solution: Two Counters</strong></h2>



<p>The final string is either 010101&#8230; or 101010&#8230;<br>We just need two counters to record the number of changes needed to transform the original string to those two final strings.</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 minOperations(string s) {
    int c1 = 0, c2 = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      c1 += (s[i] - '0' == i % 2);
      c2 += (s[i] - '0' != i % 2);
    }
    return min(c1, c2);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1758-minimum-changes-to-make-alternating-binary-string/">花花酱 LeetCode 1758. Minimum Changes To Make Alternating Binary String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1758-minimum-changes-to-make-alternating-binary-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1704. Determine if String Halves Are Alike</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1704-determine-if-string-halves-are-alike/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1704-determine-if-string-halves-are-alike/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 08:17:51 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[vowel]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7856</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;of even length. Split this string into two halves of equal lengths, and let&#160;a&#160;be the first half and&#160;b&#160;be the second half.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1704-determine-if-string-halves-are-alike/">花花酱 LeetCode 1704. Determine if String Halves Are Alike</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 string&nbsp;<code>s</code>&nbsp;of even length. Split this string into two halves of equal lengths, and let&nbsp;<code>a</code>&nbsp;be the first half and&nbsp;<code>b</code>&nbsp;be the second half.</p>



<p>Two strings are&nbsp;<strong>alike</strong>&nbsp;if they have the same number of vowels (<code>'a'</code>,&nbsp;<code>'e'</code>,&nbsp;<code>'i'</code>,&nbsp;<code>'o'</code>,&nbsp;<code>'u'</code>,&nbsp;<code>'A'</code>,&nbsp;<code>'E'</code>,&nbsp;<code>'I'</code>,&nbsp;<code>'O'</code>,&nbsp;<code>'U'</code>). Notice that&nbsp;<code>s</code>&nbsp;contains uppercase and lowercase letters.</p>



<p>Return&nbsp;<code>true</code><em>&nbsp;if&nbsp;</em><code>a</code><em>&nbsp;and&nbsp;</em><code>b</code><em>&nbsp;are&nbsp;<strong>alike</strong></em>. Otherwise, return&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "book"
<strong>Output:</strong> true
<strong>Explanation:</strong>&nbsp;a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "textbook"
<strong>Output:</strong> false
<strong>Explanation:</strong>&nbsp;a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
</pre>



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



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



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



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



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



<ul><li><code>2 &lt;= s.length &lt;= 1000</code></li><li><code>s.length</code>&nbsp;is even.</li><li><code>s</code>&nbsp;consists of&nbsp;<strong>uppercase and lowercase</strong>&nbsp;letters.</li></ul>



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



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



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def halvesAreAlike(self, s: str) -&gt; bool:
    def count(s: str) -&gt; int:
      return sum(c in 'aeiouAEIOU' for c in s)
    n = len(s)
    return count(s[:n//2]) == count(s[n//2:])</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1704-determine-if-string-halves-are-alike/">花花酱 LeetCode 1704. Determine if String Halves Are Alike</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1704-determine-if-string-halves-are-alike/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1702. Maximum Binary String After Change</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 02:47:25 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7849</guid>

					<description><![CDATA[<p>You are given a binary string&#160;binary&#160;consisting of only&#160;0&#8216;s or&#160;1&#8216;s. You can apply each of the following operations any number of times: Operation 1: If the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/">花花酱 LeetCode 1702. Maximum Binary String After Change</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 binary string&nbsp;<code>binary</code>&nbsp;consisting of only&nbsp;<code>0</code>&#8216;s or&nbsp;<code>1</code>&#8216;s. You can apply each of the following operations any number of times:</p>



<ul><li>Operation 1: If the number contains the substring&nbsp;<code>"00"</code>, you can replace it with&nbsp;<code>"10"</code>.<ul><li>For example,&nbsp;<code>"00010" -&gt; "10010</code>&#8220;</li></ul></li><li>Operation 2: If the number contains the substring&nbsp;<code>"10"</code>, you can replace it with&nbsp;<code>"01"</code>.<ul><li>For example,&nbsp;<code>"00010" -&gt; "00001"</code></li></ul></li></ul>



<p><em>Return the&nbsp;<strong>maximum binary string</strong>&nbsp;you can obtain after any number of operations. Binary string&nbsp;<code>x</code>&nbsp;is greater than binary string&nbsp;<code>y</code>&nbsp;if&nbsp;<code>x</code>&#8216;s decimal representation is greater than&nbsp;<code>y</code>&#8216;s decimal representation.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> binary = "000110"
<strong>Output:</strong> "111011"
<strong>Explanation:</strong> A valid transformation sequence can be:
"000110" -&gt; "000101" 
"000101" -&gt; "100101" 
"100101" -&gt; "110101" 
"110101" -&gt; "110011" 
"110011" -&gt; "111011"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> binary = "01"
<strong>Output:</strong> "01"
<strong>Explanation:</strong>&nbsp;"01" cannot be transformed any further.
</pre>



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



<ul><li><code>1 &lt;= binary.length &lt;= 10<sup>5</sup></code></li><li><code>binary</code>&nbsp;consist of&nbsp;<code>'0'</code>&nbsp;and&nbsp;<code>'1'</code>.</li></ul>



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



<p>Leading 1s are good, no need to change them.<br>For the rest of the string<br>1. Apply operation 2 to make the string into 3 parts, leading 1s, middle 0s and tailing 1s.<br>e.g. 110<strong>1010</strong>1 =&gt; 11001<strong>10</strong>1 =&gt; 1100<strong>10</strong>11 =&gt; 11000111<br>2. Apply operation 1 to make flip zeros to ones except the last one.<br>e.g. 11<strong>00</strong>0111 =&gt; 111<strong>00</strong>111 =&gt; 11110111<br><br>There will be only one zero (if the input string is not all 1s) is the final largest string, the position of the zero is leading 1s + zeros &#8211; 1.</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:
  string maximumBinaryString(string s) {
    const int n = s.length();
    int l = 0;
    int z = 0;
    for (char&amp; c : s) {
      if (c == '0') {
        ++z;
      } else if (z == 0) { // leading 1s      
        ++l;
      }
      c = '1';
    }
    if (l != n) s[l + z - 1] = '0';
    return s;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/">花花酱 LeetCode 1702. Maximum Binary String After Change</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1702-maximum-binary-string-after-change/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1566. Detect Pattern of Length M Repeated K or More Times</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1566-detect-pattern-of-length-m-repeated-k-or-more-times/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1566-detect-pattern-of-length-m-repeated-k-or-more-times/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Aug 2020 05:44:48 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7312</guid>

					<description><![CDATA[<p>Given an array of positive integers&#160;arr,&#160; find a pattern of length&#160;m&#160;that is repeated&#160;k&#160;or more times. A&#160;pattern&#160;is a subarray (consecutive sub-sequence) that consists of one or&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1566-detect-pattern-of-length-m-repeated-k-or-more-times/">花花酱 LeetCode 1566. Detect Pattern of Length M Repeated K or More Times</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of positive integers&nbsp;<code>arr</code>,&nbsp; find a pattern of length&nbsp;<code>m</code>&nbsp;that is repeated&nbsp;<code>k</code>&nbsp;or more times.</p>



<p>A&nbsp;<strong>pattern</strong>&nbsp;is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times&nbsp;<strong>consecutively&nbsp;</strong>without overlapping. A pattern is defined by its length and the number of repetitions.</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if there exists a pattern of length</em>&nbsp;<code>m</code>&nbsp;<em>that is repeated</em>&nbsp;<code>k</code>&nbsp;<em>or more times, otherwise return</em>&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,4,4,4,4], m = 1, k = 3
<strong>Output:</strong> true
<strong>Explanation: </strong>The pattern <strong>(4)</strong> of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
<strong>Output:</strong> true
<strong>Explanation: </strong>The pattern <strong>(1,2)</strong> of length 2 is repeated 2 consecutive times. Another valid pattern <strong>(2,1) is</strong> also repeated 2 times.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,1,2,1,3], m = 2, k = 3
<strong>Output:</strong> false
<strong>Explanation: </strong>The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,1,2], m = 2, k = 2
<strong>Output:</strong> false
<strong>Explanation: </strong>Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,2,2,2], m = 2, k = 3
<strong>Output:</strong> false
<strong>Explanation: </strong>The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
</pre>



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



<ul><li><code>2 &lt;= arr.length &lt;= 100</code></li><li><code>1 &lt;= arr[i] &lt;= 100</code></li><li><code>1 &lt;= m&nbsp;&lt;= 100</code></li><li><code>2 &lt;= k&nbsp;&lt;= 100</code></li></ul>



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



<p>Time complexity: O(nmk)<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:
  bool containsPattern(vector&lt;int&gt;&amp; arr, int m, int k) {
    const int n = arr.size();
    for (int i = 0; i + m * k &lt;= n; ++i) {
      bool valid = true;
      for (int j = 1; j &lt; k &amp;&amp; valid; ++j)
        for (int p = 0; p &lt; m &amp;&amp; valid; ++p)
          if (arr[i + j * m + p] != arr[i + p])
            valid = false;
      if (valid) return true;
    }
    return false;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Shift and count</strong></h2>



<p>Since we need k consecutive subarrays, we can compare arr[i] with arr[i + m], if they are the same, increase the counter, otherwise reset the counter. If the counter reaches (k &#8211; 1)  * m, it means we found k consecutive subarrays of length m.</p>



<p>ex1: arr = [1,2,4,4,4,4], m = 1, k = 3<br>i arr[i], arr[i + m] counter<br>0 1.       2.               0<br>0 2.       4.               0<br>0 4.       4.               1<br>0 4.       4.               2. &lt;&#8211; found</p>



<p>ex2: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2<br>i arr[i], arr[i + m] counter<br>0 1.       1.               1<br>0 2.       2.               2 &lt;&#8211; found</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:
  bool containsPattern(vector&lt;int&gt;&amp; arr, int m, int k) {
    const int n = arr.size();
    int count = 0;
    for (int i = 0; i + m &lt; n; ++i) {      
      if (arr[i] == arr[i + m]) {
        if (++count == (k - 1) * m) return true;
      } else {
        count = 0;
      }      
    }
    return false;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1566-detect-pattern-of-length-m-repeated-k-or-more-times/">花花酱 LeetCode 1566. Detect Pattern of Length M Repeated K or More Times</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1566-detect-pattern-of-length-m-repeated-k-or-more-times/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1550. Three Consecutive Odds</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1550-three-consecutive-odds/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1550-three-consecutive-odds/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Aug 2020 04:25:28 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[odd]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7247</guid>

					<description><![CDATA[<p>Given an integer array&#160;arr, return&#160;true&#160;if there are three consecutive odd numbers in the array. Otherwise, return&#160;false. Example 1: Input: arr = [2,6,4,1] Output: false Explanation:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1550-three-consecutive-odds/">花花酱 LeetCode 1550. Three Consecutive Odds</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>arr</code>, return&nbsp;<code>true</code>&nbsp;if there are three consecutive odd numbers in the array. Otherwise, return&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,6,4,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> There are no three consecutive odds.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,34,3,4,5,7,23,12]
<strong>Output:</strong> true
<strong>Explanation:</strong> [5,7,23] are three consecutive odds.
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;= 1000</code></li><li><code>1 &lt;= arr[i] &lt;= 1000</code></li></ul>



<h2><strong>Solution: Counting</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">class Solution {
public:
  bool threeConsecutiveOdds(vector&lt;int&gt;&amp; arr) {       
    int count = 0;
    for (int x : arr) {
      if (x &amp; 1) {
        if (++count == 3) return true;
      } else {
        count = 0;
      }
    }
    return false;      
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1550-three-consecutive-odds/">花花酱 LeetCode 1550. Three Consecutive Odds</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1550-three-consecutive-odds/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Aug 2020 17:15:43 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7219</guid>

					<description><![CDATA[<p>Given a parentheses string&#160;s&#160;containing only the characters&#160;'('&#160;and&#160;')'. A parentheses string is&#160;balanced&#160;if: Any left parenthesis&#160;'('&#160;must have a corresponding two consecutive right parenthesis&#160;'))'. Left parenthesis&#160;'('&#160;must go before&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/">花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</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 parentheses string&nbsp;<code>s</code>&nbsp;containing only the characters&nbsp;<code>'('</code>&nbsp;and&nbsp;<code>')'</code>. A parentheses string is&nbsp;<strong>balanced</strong>&nbsp;if:</p>



<ul><li>Any left parenthesis&nbsp;<code>'('</code>&nbsp;must have a corresponding two consecutive right parenthesis&nbsp;<code>'))'</code>.</li><li>Left parenthesis&nbsp;<code>'('</code>&nbsp;must go before the corresponding two&nbsp;consecutive right parenthesis&nbsp;<code>'))'</code>.</li></ul>



<p>For example,&nbsp;<code>"())"</code>,&nbsp;<code>"())(())))"</code>&nbsp;and&nbsp;<code>"(())())))"</code>&nbsp;are&nbsp;balanced,&nbsp;<code>")()"</code>,&nbsp;<code>"()))"</code>&nbsp;and&nbsp;<code>"(()))"</code>&nbsp;are not balanced.</p>



<p>You can insert the characters &#8216;(&#8216; and &#8216;)&#8217; at any position of the string to balance it if needed.</p>



<p>Return&nbsp;<em>the minimum number of insertions</em>&nbsp;needed to make&nbsp;<code>s</code>&nbsp;balanced.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(()))"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The second '(' has two matching '))', but the first '(' has only ')' matching. We need to to add one more ')' at the end of the string to be "(())))" which is balanced.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "())"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The string is already balanced.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "))())("
<strong>Output:</strong> 3
<strong>Explanation:</strong> Add '(' to match the first '))', Add '))' to match the last '('.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(((((("
<strong>Output:</strong> 12
<strong>Explanation:</strong> Add 12 ')' to balance the string.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = ")))))))"
<strong>Output:</strong> 5
<strong>Explanation:</strong> Add 4 '(' at the beginning of the string and one ')' at the end. The string becomes "(((())))))))".
</pre>



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



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



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



<p>Count how many close parentheses we need.</p>



<ol><li>if s[i] is &#8216;)&#8217;, we decrease the counter.<ol><li>if counter becomes negative, means we need to insert &#8216;(&#8216;<ol><li>increase ans by 1, increase the counter by 2, we need one more &#8216;)&#8217;</li><li>&#8216;)&#8217; -> &#8216;()&#8217; </li></ol></li></ol></li><li>if s[i] is &#8216;(&#8216;<ol><li>if we have an odd counter, means there is a unbalanced &#8216;)&#8217; e.g. &#8216;(()(&#8216;, counter is 3<ol><li>need to insert &#8216;)&#8217;, decrease counter, increase ans</li><li>&#8216;(()(&#8216; -> &#8216;(<s>())</s>(&#8216;, counter = 2</li></ol></li><li>increase counter by 2, each &#8216;(&#8216; needs two &#8216;)&#8217;s. &#8216;(<s>())</s>(&#8216; -> counter = 4</li></ol></li><li>Once done, if counter is greater than zero, we need insert that much &#8216;)s&#8217;<ol><li>counter = 5, &#8216;((()&#8217; -> &#8216;((())))))&#8217;</li></ol></li></ol>



<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 minInsertions(string s) {
    int ans = 0;
    int close = 0; // # of ')' needed.    
    for (char c : s) {
      if (c == ')') {
        if (--close &lt; 0) {          
          // need to insert one '('
          // ')' -&gt; '()'
          ++ans;
          close += 2;
        }
      } else {
        if (close &amp; 1) {          
          // need to insert one ')'
          // case '(()(' -&gt; '(())('
          --close;
          ++ans;
        }
        close += 2; // need two ')'s
      }
    }
    return ans + close;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/">花花酱 LeetCode 1541. Minimum Insertions to Balance a Parentheses String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1541-minimum-insertions-to-balance-a-parentheses-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 21 Apr 2020 06:18:20 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6652</guid>

					<description><![CDATA[<p>Given three integers&#160;n,&#160;m&#160;and&#160;k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/">花花酱 LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons</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 three integers&nbsp;<code>n</code>,&nbsp;<code>m</code>&nbsp;and&nbsp;<code>k</code>. Consider the following algorithm to find the maximum element of an array of positive integers:</p>



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



<p>You should build the array arr which has the following properties:</p>



<ul><li><code>arr</code>&nbsp;has exactly&nbsp;<code>n</code>&nbsp;integers.</li><li><code>1 &lt;= arr[i] &lt;= m</code>&nbsp;where&nbsp;<code>(0 &lt;= i &lt; n)</code>.</li><li>After applying the mentioned algorithm to&nbsp;<code>arr</code>, the value&nbsp;<code>search_cost</code>&nbsp;is equal to&nbsp;<code>k</code>.</li></ul>



<p>Return&nbsp;<em>the number of ways</em>&nbsp;to build the array&nbsp;<code>arr</code>&nbsp;under the mentioned conditions.&nbsp;As the answer may grow large, the answer&nbsp;<strong>must be</strong>&nbsp;computed modulo&nbsp;<code>10^9 + 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, m = 3, k = 1
<strong>Output:</strong> 6
<strong>Explanation:</strong> The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, m = 2, k = 3
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no possible arrays that satisify the mentioned conditions.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 9, m = 1, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 50, m = 100, k = 25
<strong>Output:</strong> 34549172
<strong>Explanation:</strong> Don't forget to compute the answer modulo 1000000007
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 37, m = 17, k = 7
<strong>Output:</strong> 418930126
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 50</code></li><li><code>1 &lt;= m &lt;= 100</code></li><li><code>0 &lt;= k &lt;= n</code></li></ul>



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



<p>dp[n][m][k] := ways to build given n,m,k.</p>



<p>dp[n][m][k] = sum(dp[n-1][m][k] + dp[n-1][i-1][k-1] &#8211; dp[n-1][i-1][k]), 1 &lt;= i &lt;= m<br>dp[1][m][1] = m<br>dp[n][m][k] = 0 if k &lt; 1 or k > m or k > n</p>



<p>Time complexity: O(n*m^2*k)<br>Space complexity: O(n*m*k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
int mem[51][101][51] = {0};
class Solution {
public:
  int numOfArrays(int n, int m, int k) {
    const int kMod = 1e9 + 7;    
    function&lt;int(int, int, int)&gt; dp = [&amp;dp](int n, int m, int k) {
      if (k &lt; 1 || k &gt; m || k &gt; n) return 0;
      if (n == 1 &amp;&amp; k == 1) return m;
      if (mem[n][m][k]) return mem[n][m][k];      
      long ans = 0;
      for (int i = 1; i &lt;= m; ++i) {
        ans += dp(n - 1, m, k);
        ans += dp(n - 1, i - 1, k - 1);
        ans -= dp(n - 1, i - 1, k);
        ans = (ans + kMod) % kMod;
      }
      return mem[n][m][k] = ans;
    };    
    return dp(n, m, k);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/">花花酱 LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons</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-1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1370. Increasing Decreasing String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1370-increasing-decreasing-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1370-increasing-decreasing-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 07:16:42 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6397</guid>

					<description><![CDATA[<p>Given a string&#160;s. You should re-order the string using the following algorithm: Pick the&#160;smallest&#160;character from&#160;s&#160;and&#160;append&#160;it to the result. Pick the&#160;smallest&#160;character from&#160;s&#160;which is greater than the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1370-increasing-decreasing-string/">花花酱 LeetCode 1370. Increasing Decreasing String</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 string&nbsp;<code>s</code>. You should re-order the string using the following algorithm:</p>



<ol><li>Pick the&nbsp;<strong>smallest</strong>&nbsp;character from&nbsp;<code>s</code>&nbsp;and&nbsp;<strong>append</strong>&nbsp;it to the result.</li><li>Pick the&nbsp;<strong>smallest</strong>&nbsp;character from&nbsp;<code>s</code>&nbsp;which is greater than the last appended character to the result and&nbsp;<strong>append</strong>&nbsp;it.</li><li>Repeat step 2 until you cannot pick more characters.</li><li>Pick the&nbsp;<strong>largest</strong>&nbsp;character from&nbsp;<code>s</code>&nbsp;and&nbsp;<strong>append</strong>&nbsp;it to the result.</li><li>Pick the&nbsp;<strong>largest</strong>&nbsp;character from&nbsp;<code>s</code>&nbsp;which is smaller than the last appended character to the result and&nbsp;<strong>append</strong>&nbsp;it.</li><li>Repeat step 5 until you cannot pick more characters.</li><li>Repeat the steps from 1 to 6 until you pick all characters from&nbsp;<code>s</code>.</li></ol>



<p>In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.</p>



<p>Return&nbsp;<em>the result string</em>&nbsp;after sorting&nbsp;<code>s</code>&nbsp;with this algorithm.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aaaabbbbcccc"
<strong>Output:</strong> "abccbaabccba"
<strong>Explanation:</strong> After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "rat"
<strong>Output:</strong> "art"
<strong>Explanation:</strong> The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
</pre>



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



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



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



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



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 500</code></li><li><code>s</code>&nbsp;contains only lower-case English letters.</li></ul>



<h2><strong>Solution: Counting frequency of each character</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string sortString(string s) {
    vector&lt;int&gt; count(26);
    for (char c : s) ++count[c - 'a'];
    string ans;
    while (ans.length() != s.length()) {
      for (char c = 'a'; c &lt;= 'z'; ++c)
        if (--count[c - 'a'] &gt;= 0)
          ans += c;
      for (char c = 'z'; c &gt;= 'a'; --c)
        if (--count[c - 'a'] &gt;= 0)
          ans += c;      
    }
    return ans;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def sortString(self, s: str) -&gt; str:
    seq = string.ascii_lowercase + string.ascii_lowercase[::-1]
    count = collections.Counter(s)
    ans = &quot;&quot;
    while len(ans) != len(s):
      for c in seq:
        if count[c] &gt; 0:
          ans += c
          count[c] -= 1
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1370-increasing-decreasing-string/">花花酱 LeetCode 1370. Increasing Decreasing String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1370-increasing-decreasing-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1365. How Many Numbers Are Smaller Than the Current Number</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/%e8%8a%b1%e8%8a%b1%e9%85%b1-leetcode-1365-how-many-numbers-are-smaller-than-the-current-number/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/%e8%8a%b1%e8%8a%b1%e9%85%b1-leetcode-1365-how-many-numbers-are-smaller-than-the-current-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Mar 2020 08:52:29 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[smaller]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6395</guid>

					<description><![CDATA[<p>Given the array&#160;nums, for each&#160;nums[i]&#160;find out how many numbers in the array are smaller than it. That is, for each&#160;nums[i]&#160;you have to count the number&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/%e8%8a%b1%e8%8a%b1%e9%85%b1-leetcode-1365-how-many-numbers-are-smaller-than-the-current-number/">花花酱 LeetCode 1365. How Many Numbers Are Smaller Than the Current 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 the array&nbsp;<code>nums</code>, for each&nbsp;<code>nums[i]</code>&nbsp;find out how many numbers in the array are smaller than it. That is, for each&nbsp;<code>nums[i]</code>&nbsp;you have to count the number of valid&nbsp;<code>j's</code>&nbsp;such that&nbsp;<code>j != i</code>&nbsp;<strong>and</strong>&nbsp;<code>nums[j] &lt; nums[i]</code>.</p>



<p>Return the answer in an array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [8,1,2,2,3]
<strong>Output:</strong> [4,0,1,1,3]
<strong>Explanation:</strong> 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
</pre>



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



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



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



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



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



<ul><li><code>2 &lt;= nums.length &lt;= 500</code></li><li><code>0 &lt;= nums[i] &lt;= 100</code></li></ul>



<h2><strong>Solution 1: 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="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; smallerNumbersThanCurrent(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; ans(n);
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (i != j &amp;&amp; nums[j] &lt; nums[i]) ++ans[i];          
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Sort + Binary Search</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; smallerNumbersThanCurrent(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; s(nums);
    sort(begin(s), end(s));    
    vector&lt;int&gt; ans(n);
    for (int i = 0; i &lt; n; ++i)
      ans[i] = distance(begin(s), lower_bound(begin(s), end(s), nums[i]));
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 3: Cumulative frequency</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(101)</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; smallerNumbersThanCurrent(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; f(101);
    for (int x : nums) ++f[x];
    partial_sum(begin(f), end(f), begin(f));    
    for (int&amp; x : nums) 
      x = x == 0 ? 0 : f[x - 1];
    return nums;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/%e8%8a%b1%e8%8a%b1%e9%85%b1-leetcode-1365-how-many-numbers-are-smaller-than-the-current-number/">花花酱 LeetCode 1365. How Many Numbers Are Smaller Than the Current 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/algorithms/array/%e8%8a%b1%e8%8a%b1%e9%85%b1-leetcode-1365-how-many-numbers-are-smaller-than-the-current-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
