<?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>frequency Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/frequency/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/frequency/</link>
	<description></description>
	<lastBuildDate>Tue, 16 Jan 2024 01:58:47 +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>frequency Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/frequency/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3005. Count Elements With Maximum Frequency</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-3005-count-elements-with-maximum-frequency/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-3005-count-elements-with-maximum-frequency/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 16 Jan 2024 01:56:31 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10104</guid>

					<description><![CDATA[<p>You are given an array&#160;nums&#160;consisting of&#160;positive&#160;integers. Return&#160;the&#160;total frequencies&#160;of elements in&#160;nums&#160;such that those elements all have the&#160;maximum&#160;frequency. The&#160;frequency&#160;of an element is the number of occurrences of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-3005-count-elements-with-maximum-frequency/">花花酱 LeetCode 3005. Count Elements With Maximum Frequency</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&nbsp;<code>nums</code>&nbsp;consisting of&nbsp;<strong>positive</strong>&nbsp;integers.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>total frequencies</strong>&nbsp;of elements in</em><em>&nbsp;</em><code>nums</code>&nbsp;<em>such that those elements all have the&nbsp;<strong>maximum</strong>&nbsp;frequency</em>.</p>



<p>The&nbsp;<strong>frequency</strong>&nbsp;of an element is the number of occurrences of that element in the array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>



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



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



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



<p>Use a hashtable to store the frequency of each element, and compare it with a running maximum frequency. Reset answer if current frequency is greater than maximum frequency. Increment the answer if current frequency is equal to the maximum frequency.</p>



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



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

// Author: Huahua
<pre class="crayon-plain-tag">class Solution {
public:
  int maxFrequencyElements(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; m;
    int freq = 0;
    int ans = 0;
    for (int x : nums) {
      if (++m[x] &gt; freq)
        freq = m[x], ans = 0;
      if (m[x] == freq)
        ans += m[x];
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-3005-count-elements-with-maximum-frequency/">花花酱 LeetCode 3005. Count Elements With Maximum Frequency</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-3005-count-elements-with-maximum-frequency/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1781. Sum of Beauty of All Substrings</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1781-sum-of-beauty-of-all-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1781-sum-of-beauty-of-all-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 06 Mar 2021 17:41:22 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8200</guid>

					<description><![CDATA[<p>The&#160;beauty&#160;of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of&#160;"abaacc"&#160;is&#160;3 - 1 = 2.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1781-sum-of-beauty-of-all-substrings/">花花酱 LeetCode 1781. Sum of Beauty of All 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>The&nbsp;<strong>beauty</strong>&nbsp;of a string is the difference in frequencies between the most frequent and least frequent characters.</p>



<ul><li>For example, the beauty of&nbsp;<code>"abaacc"</code>&nbsp;is&nbsp;<code>3 - 1 = 2</code>.</li></ul>



<p>Given a string&nbsp;<code>s</code>, return&nbsp;<em>the sum of&nbsp;<strong>beauty</strong>&nbsp;of all of its substrings.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabcb"
<strong>Output:</strong> 5
<strong>Explanation: </strong>The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;=500</code></li><li><code>s</code>&nbsp;consists of only lowercase English letters.</li></ul>



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



<p>Time complexity: O(n<sup>2</sup>log26)<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:
  int beautySum(string_view s) {
    const int n = s.size();
    int ans = 0;
    vector&lt;int&gt; f(26);
    map&lt;int, int&gt; m;
    for (int i = 0; i &lt; n; ++i) {
      fill(begin(f), end(f), 0);
      m.clear();
      for (int j = i; j &lt; n; ++j) {
        const int c = ++f[s[j] - 'a'];
        ++m[c];
        if (c &gt; 1) {
          auto it = m.find(c - 1);
          if (--it-&gt;second == 0)
            m.erase(it);
        }
        ans += rbegin(m)-&gt;first - begin(m)-&gt;first;  
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1781-sum-of-beauty-of-all-substrings/">花花酱 LeetCode 1781. Sum of Beauty of All 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-1781-sum-of-beauty-of-all-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1647. Minimum Deletions to Make Character Frequencies Unique</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1647-minimum-deletions-to-make-character-frequencies-unique/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1647-minimum-deletions-to-make-character-frequencies-unique/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Nov 2020 06:06:06 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7619</guid>

					<description><![CDATA[<p>A string&#160;s&#160;is called&#160;good&#160;if there are no two different characters in&#160;s&#160;that have the same&#160;frequency. Given a string&#160;s, return&#160;the&#160;minimum&#160;number of characters you need to delete to make&#160;s&#160;good.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1647-minimum-deletions-to-make-character-frequencies-unique/">花花酱 LeetCode 1647. Minimum Deletions to Make Character Frequencies Unique</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A string&nbsp;<code>s</code>&nbsp;is called&nbsp;<strong>good</strong>&nbsp;if there are no two different characters in&nbsp;<code>s</code>&nbsp;that have the same&nbsp;<strong>frequency</strong>.</p>



<p>Given a string&nbsp;<code>s</code>, return<em>&nbsp;the&nbsp;<strong>minimum</strong>&nbsp;number of characters you need to delete to make&nbsp;</em><code>s</code><em>&nbsp;<strong>good</strong>.</em></p>



<p>The&nbsp;<strong>frequency</strong>&nbsp;of a character in a string is the number of times it appears in the string. For example, in the string&nbsp;<code>"aab"</code>, the&nbsp;<strong>frequency</strong>&nbsp;of&nbsp;<code>'a'</code>&nbsp;is&nbsp;<code>2</code>, while the&nbsp;<strong>frequency</strong>&nbsp;of&nbsp;<code>'b'</code>&nbsp;is&nbsp;<code>1</code>.</p>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aaabbbcc"
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ceabaacb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
</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;contains only lowercase English letters.</li></ul>



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



<p>The deletion order doesn&#8217;t matter, we can process from &#8216;a&#8217; to &#8216;z&#8217;. Use a hashtable to store the &#8220;final frequency&#8221; so far, for each char, decrease its frequency until it becomes unique in the final frequency hashtable.</p>



<p>Time complexity: O(n + 26^2)<br>Space complexity: O(26)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int minDeletions(string s) {
    vector&lt;int&gt; freq(26);
    for (char c : s) ++freq[c - 'a'];    
    unordered_set&lt;int&gt; seen;
    int ans = 0;
    for (int f : freq) {
      while (f &amp;&amp; !seen.insert(f).second) {        
        --f;
        ++ans;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1647-minimum-deletions-to-make-character-frequencies-unique/">花花酱 LeetCode 1647. Minimum Deletions to Make Character Frequencies Unique</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-1647-minimum-deletions-to-make-character-frequencies-unique/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Sep 2020 05:05:47 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7348</guid>

					<description><![CDATA[<p>Given two arrays of integers&#160;nums1&#160;and&#160;nums2, return the number of triplets formed (type 1 and type 2) under the following rules: Type 1: Triplet (i, j,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/">花花酱 LeetCode 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given two arrays of integers&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>, return the number of triplets formed (type 1 and type 2) under the following rules:</p>



<ul><li>Type 1: Triplet (i, j, k)&nbsp;if&nbsp;<code>nums1[i]<sup>2</sup>&nbsp;== nums2[j] * nums2[k]</code>&nbsp;where&nbsp;<code>0 &lt;= i &lt; nums1.length</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt; k &lt; nums2.length</code>.</li><li>Type 2:&nbsp;Triplet (i, j, k) if&nbsp;<code>nums2[i]<sup>2</sup>&nbsp;== nums1[j] * nums1[k]</code>&nbsp;where&nbsp;<code>0 &lt;= i &lt; nums2.length</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt; k &lt; nums1.length</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [7,4], nums2 = [5,2,8,9]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Type 1: (1,1,2), nums1[1]^2 = nums2[1] * nums2[2]. (4^2 = 2 * 8). 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,1], nums2 = [1,1,1]
<strong>Output:</strong> 9
<strong>Explanation:</strong> All Triplets are valid, because 1^2 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2).  nums1[i]^2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]^2 = nums1[j] * nums1[k].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [7,7,8,3], nums2 = [1,2,9,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 valid triplets.
Type 1: (3,0,2).  nums1[3]^2 = nums2[0] * nums2[2].
Type 2: (3,0,1).  nums2[3]^2 = nums1[0] * nums1[1].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [4,7,9,11,23], nums2 = [3,5,1024,12,18]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no valid triplets.
</pre>



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



<ul><li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li><li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10^5</code></li></ul>



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



<p>For each number y in the second array, count its frequency.</p>



<p>For each number x in the first, if x * x % y == 0, let r = x * x / y<br>if r == y: ans += f[y] * f[y-1]<br>else ans += f[y] * f[r]<br><br>Final ans /= 2</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numTriplets(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    return solve(nums1, nums2) + solve(nums2, nums1);
  }
private:
  int solve(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    int ans = 0;
    unordered_map&lt;int, int&gt; f;
    for (int y : nums2) ++f[y];
    for (long x : nums1)
      for (const auto&amp; [y, c] : f) {                
        long r = x * x / y;
        if (x * x % y || !f.count(r)) continue;
        if (r == y) ans += c * (c - 1);
        else ans += c * f[r];
      }
    return ans / 2;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/">花花酱 LeetCode 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1577-number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1525. Number of Good Ways to Split a String</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1525-number-of-good-ways-to-split-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1525-number-of-good-ways-to-split-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Jul 2020 20:58:50 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7143</guid>

					<description><![CDATA[<p>You are given a string&#160;s, a&#160;split is called&#160;good&#160;if you can split&#160;s&#160;into 2&#160;non-empty strings&#160;p&#160;and&#160;q&#160;where its concatenation is equal to&#160;s&#160;and the number of distinct letters in&#160;p&#160;and&#160;q&#160;are the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1525-number-of-good-ways-to-split-a-string/">花花酱 LeetCode 1525. Number of Good Ways to Split a 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>, a&nbsp;split is called&nbsp;<em>good</em>&nbsp;if you can split&nbsp;<code>s</code>&nbsp;into 2&nbsp;non-empty strings&nbsp;<code>p</code>&nbsp;and&nbsp;<code>q</code>&nbsp;where its concatenation is equal to&nbsp;<code>s</code>&nbsp;and the number of distinct letters in&nbsp;<code>p</code>&nbsp;and&nbsp;<code>q</code>&nbsp;are the same.</p>



<p>Return the number of&nbsp;<em>good</em>&nbsp;splits you can make in&nbsp;<code>s</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aacaba"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 5 ways to split <code>"aacaba"</code> and 2 of them are good. 
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 1
<strong>Explanation: </strong>Split the string as follows ("ab", "cd").
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> 4
<strong>Explanation: </strong>All possible splits are good.</pre>



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



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



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



<ul><li><code>s</code>&nbsp;contains only lowercase English letters.</li><li><code>1 &lt;= s.length &lt;= 10^5</code></li></ul>



<h2><strong>Solution: Sliding Window</strong></h2>



<ol><li>Count the frequency of each letter and count number of unique letters for the entire string as right part.</li><li>Iterate over the string, add current letter to the left part, and remove it from the right part.</li><li>We only<ol><li>increase the number of unique letters when its frequency becomes to 1</li><li>decrease the number of unique letters when its frequency becomes to 0  </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 numSplits(string s) {
    vector&lt;int&gt; r(26);
    vector&lt;int&gt; l(26);
    int cr = 0;
    for (char c : s)
      cr += (++r[c - 'a'] == 1);    
    int ans = 0;
    int cl = 0;
    for (char c : s) {
      cl += (++l[c - 'a'] == 1);
      cr -= (--r[c - 'a'] == 0);
      ans += cl == cr;
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution {
  public int numSplits(String s) {
    int[] l = new int[26];
    int[] r = new int[26];
    int ans = 0;
    int cl = 0;
    int cr = 0;
    for (char c : s.toCharArray())
      if (++r[c - 'a'] == 1) ++cr;
    for (char c : s.toCharArray()) {
      if (++l[c - 'a'] == 1) ++cl;
      if (--r[c - 'a'] == 0) --cr;
      if (cl == cr) ++ans;
    }
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def numSplits(self, s: str) -&gt; int:
    s = [ord(c) - ord('a') for c in s]
    l, r = [0] * 26, [0] * 26
    cl, cr, ans = 0, 0, 0
    for c in s:
      r[c] += 1
      if r[c] == 1: cr += 1
    for c in s:
      l[c] += 1
      r[c] -= 1
      if l[c] == 1: cl += 1
      if r[c] == 0: cr -= 1
      if cl == cr: ans += 1
    return ans</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1525-number-of-good-ways-to-split-a-string/">花花酱 LeetCode 1525. Number of Good Ways to Split a 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/sliding-window/leetcode-1525-number-of-good-ways-to-split-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1497. Check If Array Pairs Are Divisible by k</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1497-check-if-array-pairs-are-divisible-by-k/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1497-check-if-array-pairs-are-divisible-by-k/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Jun 2020 07:50:56 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mod]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6996</guid>

					<description><![CDATA[<p>Given an array of integers&#160;arr&#160;of even length&#160;n&#160;and an integer&#160;k. We want to divide the array into exactly&#160;n /&#160;2&#160;pairs such that the sum of each pair&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1497-check-if-array-pairs-are-divisible-by-k/">花花酱 LeetCode 1497. Check If Array Pairs Are Divisible by k</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers&nbsp;<code>arr</code>&nbsp;of even length&nbsp;<code>n</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>We want to divide the array into exactly&nbsp;<code>n /&nbsp;2</code>&nbsp;pairs such that the sum of each pair is divisible by&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>True</em>&nbsp;If you can find a way to do that or&nbsp;<em>False</em>&nbsp;otherwise.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4,5,10,6,7,8,9], k = 5
<strong>Output:</strong> true
<strong>Explanation:</strong> Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4,5,6], k = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> Pairs are (1,6),(2,5) and(3,4).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4,5,6], k = 10
<strong>Output:</strong> false
<strong>Explanation:</strong> You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
</pre>



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



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



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



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



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



<ul><li><code>arr.length == n</code></li><li><code>1 &lt;= n &lt;= 10^5</code></li><li><code>n</code>&nbsp;is even.</li><li><code>-10^9 &lt;= arr[i] &lt;= 10^9</code></li><li><code>1 &lt;= k &lt;= 10^5</code></li></ul>



<h2><strong>Solution: Mod and Count</strong></h2>



<p>Count the frequency of (x % k + k) % k.<br>f[0] should be even (zero is also even)<br>f[1] = f[k -1] ((1 + k &#8211; 1) % k == 0)<br>f[2] = f[k -2] ((2 + k &#8211; 2) % k == 0)<br>&#8230;<br>Time complexity: O(n)<br>Space complexity: 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:
  bool canArrange(vector&lt;int&gt;&amp; arr, int k) {
    vector&lt;int&gt; f(k);
    for (int x : arr) ++f[(x % k + k) % k];
    for (int i = 1; i &lt; k; ++i)
      if (f[i] != f[k - i]) return false;
    return f[0] % 2 == 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1497-check-if-array-pairs-are-divisible-by-k/">花花酱 LeetCode 1497. Check If Array Pairs Are Divisible by k</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1497-check-if-array-pairs-are-divisible-by-k/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1481. Least Number of Unique Integers after K Removals</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1481-least-number-of-unique-integers-after-k-removals/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1481-least-number-of-unique-integers-after-k-removals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Jun 2020 02:40:03 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6932</guid>

					<description><![CDATA[<p>Given an array of integers&#160;arr&#160;and an integer&#160;k.&#160;Find the&#160;least number of unique integers&#160;after removing&#160;exactly&#160;k&#160;elements. Example 1: Input: arr = [5,5,4], k = 1 Output: 1 Explanation:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1481-least-number-of-unique-integers-after-k-removals/">花花酱 LeetCode 1481. Least Number of Unique Integers after K Removals</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>k</code>.&nbsp;Find the&nbsp;<em>least number of unique integers</em>&nbsp;after removing&nbsp;<strong>exactly</strong>&nbsp;<code>k</code>&nbsp;elements<strong>.</strong></p>



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



<pre class="wp-block-preformatted:crayon:false"><strong>Input: </strong>arr = [5,5,4], k = 1
<strong>Output: </strong>1
<strong>Explanation</strong>: Remove the single 4, only 5 is left.
</pre>



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



<pre class="wp-block-preformatted:crayon:false"><strong>Input: </strong>arr = [4,3,1,1,3,3,2], k = 3
<strong>Output: </strong>2
<strong>Explanation</strong>: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.</pre>



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



<ul><li><code>1 &lt;= arr.length&nbsp;&lt;= 10^5</code></li><li><code>1 &lt;= arr[i] &lt;= 10^9</code></li><li><code>0 &lt;= k&nbsp;&lt;= arr.length</code></li></ul>



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



<p>Count the frequency of each unique number. Sort by frequency, remove items with lowest frequency first.</p>



<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:
  int findLeastNumOfUniqueInts(vector&lt;int&gt;&amp; arr, int k) {    
    unordered_map&lt;int, int&gt; c;
    for (int x : arr) ++c[x];
    vector&lt;int&gt; m; // freq
    for (const auto [x, f] : c)
      m.push_back(f);
    sort(begin(m), end(m));
    int ans = m.size();    
    int i = 0;
    while (k--) {
      if (--m[i] == 0) {
        ++i;
        --ans;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1481-least-number-of-unique-integers-after-k-removals/">花花酱 LeetCode 1481. Least Number of Unique Integers after K Removals</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-1481-least-number-of-unique-integers-after-k-removals/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 1178. Number of Valid Words for Each Puzzle</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1178-number-of-valid-words-for-each-puzzle/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1178-number-of-valid-words-for-each-puzzle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Sep 2019 01:28:10 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5521</guid>

					<description><![CDATA[<p>With respect to a given&#160;puzzle&#160;string, a&#160;word&#160;is&#160;valid&#160;if both the following conditions are satisfied: word&#160;contains the first letter of&#160;puzzle. For each letter in&#160;word, that letter is in&#160;puzzle.For&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1178-number-of-valid-words-for-each-puzzle/">花花酱 LeetCode 1178. Number of Valid Words for Each Puzzle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/qOrmhPX-gAU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>

With respect to a given&nbsp;<code>puzzle</code>&nbsp;string, a&nbsp;<code>word</code>&nbsp;is&nbsp;<em>valid</em>&nbsp;if both the following conditions are satisfied:</p>



<ul><li><code>word</code>&nbsp;contains the first letter of&nbsp;<code>puzzle</code>.</li><li>For each letter in&nbsp;<code>word</code>, that letter is in&nbsp;<code>puzzle</code>.<br>For example, if the puzzle is &#8220;abcdefg&#8221;, then valid words are &#8220;faced&#8221;, &#8220;cabbage&#8221;, and &#8220;baggage&#8221;; while invalid words are &#8220;beefed&#8221; (doesn&#8217;t include &#8220;a&#8221;) and &#8220;based&#8221; (includes &#8220;s&#8221; which isn&#8217;t in the puzzle).</li></ul>



<p>Return an array&nbsp;<code>answer</code>, where&nbsp;<code>answer[i]</code>&nbsp;is the number of words in the given word list&nbsp;<code>words</code>&nbsp;that are valid with respect to the puzzle&nbsp;<code>puzzles[i]</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 
words = ["aaaa","asas","able","ability","actt","actor","access"], 
puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
<strong>Output:</strong> [1,1,3,2,4,0]
<strong>Explanation:</strong>
1 valid word&nbsp;for "aboveyz" : "aaaa" 
1 valid word&nbsp;for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for&nbsp;"absoryz" : "aaaa", "asas"
4 valid words for&nbsp;"actresz" : "aaaa", "asas", "actt", "access"
There're&nbsp;no valid words for&nbsp;"gaswxyz" cause none of the words in the list contains letter 'g'.
</pre>



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



<ul><li><code>1 &lt;= words.length &lt;= 10^5</code></li><li><code>4 &lt;= words[i].length &lt;= 50</code></li><li><code>1 &lt;= puzzles.length &lt;= 10^4</code></li><li><code>puzzles[i].length == 7</code></li><li><code>words[i][j]</code>,&nbsp;<code>puzzles[i][j]</code>&nbsp;are English lowercase letters.</li><li>Each&nbsp;<code>puzzles[i]&nbsp;</code>doesn&#8217;t contain repeated characters.</li></ul>



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



<p>Preprocessing: <br>Compress each word to a bit map, and compute the frequency of each bit map.<br>Since there are at most |words| bitmaps while its value ranging from 0 to 2^26, thus it&#8217;s better to use a hashtable instead of an array.</p>



<p>Query:<br>Use the same way to compress a puzzle into a bit map.<br>Try all subsets (at most 128) of the puzzle (the bit of the first character is be must), and check how many words match each subset.</p>



<p>words = [&#8220;aaaa&#8221;,&#8221;asas&#8221;,&#8221;able&#8221;,&#8221;ability&#8221;,&#8221;actt&#8221;,&#8221;actor&#8221;,&#8221;access&#8221;], <br>puzzle = &#8220;abslute&#8221;<br>bitmap(&#8220;aaaa&#8221;)  = {0}<br>bitmap(&#8220;asas&#8221;) = {0, 18}<br>bitmap(&#8220;able&#8221;) = {0,1,4,11}<br>bitmap(&#8220;actt&#8221;) = {0, 2, 19}<br>bitmap(&#8220;actor&#8221;) = {0, 2, 14, 17, 19}<br>bitmap(&#8220;access&#8221;) = {0, 2, 4, 18}<br><br>bitmap(&#8220;abslute&#8221;) = {0, 1, 4, 11, 18, 19, 20}<br></p>



<p>Time complexity: O(sum(len(w_i)) + |puzzles|)<br>Space complexity: O(|words|)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 136 ms, 29.7 MB
class Solution {
public:
  vector&lt;int&gt; findNumOfValidWords(vector&lt;string&gt;&amp; words, vector&lt;string&gt;&amp; puzzles) {
    vector&lt;int&gt; ans;    
    unordered_map&lt;int, int&gt; freq;
    for (const string&amp; word : words) {
      int mask = 0;
      for (char c : word)
        mask |= 1 &lt;&lt; (c - 'a');
      ++freq[mask];
    }    
    for (const string&amp; p : puzzles) {
      int mask = 0;      
      for (char c : p)
        mask |= 1 &lt;&lt; (c - 'a');
      int first = p[0] - 'a';
      int curr = mask;
      int total = 0;
      while (curr) {
        if ((curr &gt;&gt; first) &amp; 1) {
          auto it = freq.find(curr);
          if (it != freq.end()) total += it-&gt;second;
        }
        curr = (curr - 1) &amp; mask;
      }
      ans.push_back(total);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1178-number-of-valid-words-for-each-puzzle/">花花酱 LeetCode 1178. Number of Valid Words for Each Puzzle</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-1178-number-of-valid-words-for-each-puzzle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1177. Can Make Palindrome from Substring</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1177-can-make-palindrome-from-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1177-can-make-palindrome-from-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Sep 2019 00:56:36 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5516</guid>

					<description><![CDATA[<p>Given a string&#160;s, we make queries on substrings of&#160;s. For each query&#160;queries[i] = [left, right, k], we may&#160;rearrange&#160;the substring&#160;s[left], ..., s[right], and then choose&#160;up to&#160;k&#160;of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1177-can-make-palindrome-from-substring/">花花酱 LeetCode 1177. Can Make Palindrome from Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>, we make queries on substrings of&nbsp;<code>s</code>.</p>



<p>For each query&nbsp;<code>queries[i] = [left, right, k]</code>, we may&nbsp;<strong>rearrange</strong>&nbsp;the substring&nbsp;<code>s[left], ..., s[right]</code>, and then choose&nbsp;<strong>up to</strong>&nbsp;<code>k</code>&nbsp;of them to replace with any lowercase English letter.&nbsp;</p>



<p>If the substring&nbsp;is possible to be a&nbsp;palindrome string after the operations above, the result of the query is&nbsp;<code>true</code>.&nbsp;Otherwise, the result&nbsp;is&nbsp;<code>false</code>.</p>



<p>Return an array&nbsp;<code>answer[]</code>, where&nbsp;<code>answer[i]</code>&nbsp;is the result of the&nbsp;<code>i</code>-th query&nbsp;<code>queries[i]</code>.</p>



<p>Note that: Each letter is counted&nbsp;<strong>individually</strong>&nbsp;for replacement so&nbsp;if for example&nbsp;<code>s[left..right] = "aaa"</code>, and&nbsp;<code>k = 2</code>, we can only replace two of the letters.&nbsp; (Also, note that the initial string&nbsp;<code>s</code>&nbsp;is never modified by any query.)</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
<strong>Output:</strong> [true,false,false,true,true]
<strong>Explanation:</strong>
queries[0] : substring = "d", is palidrome.
queries[1] :&nbsp;substring = "bc", is not palidrome.
queries[2] :&nbsp;substring = "abcd", is not palidrome after replacing only 1 character.
queries[3] :&nbsp;substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4] :&nbsp;substring = "abcda",&nbsp;could be changed to "abcba" which is palidrome.
</pre>



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



<ul><li><code>1 &lt;= s.length,&nbsp;queries.length&nbsp;&lt;= 10^5</code></li><li><code>0 &lt;= queries[i][0] &lt;= queries[i][1] &lt;&nbsp;s.length</code></li><li><code>0 &lt;= queries[i][2] &lt;= s.length</code></li><li><code>s</code>&nbsp;only contains lowercase English letters.</li></ul>



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



<p>Compute the prefix frequency of each characters, then we can efficiently compute the frequency of each characters in the substring in O(1) time. Count the number odd frequency characters o, we can convert it to a palindrome if o / 2 &lt;= k.</p>



<p>Time complexity: <br>preprocessing: O(n)<br>Query: O(1)<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;bool&gt; canMakePaliQueries(string s, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    vector&lt;bool&gt; ans;
    int n = s.length();
    vector&lt;vector&lt;int&gt;&gt; f(n + 1, vector&lt;int&gt;(26));
    for (int i = 0; i &lt; n; ++i) {
      ++f[i][s[i] - 'a'];
      f[i + 1] = f[i];
    }
    for (const auto&amp; q : queries) {      
      int l = q[0];
      int r = q[1];
      int k = q[2];      
      int o = 0;
      for (int i = 0; i &lt; 26; ++i) {
        int c = f[r][i] - (l == 0 ? 0 : f[l - 1][i]);        
        o += c % 2;
      }
      ans.push_back(o / 2 &lt;= k);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1177-can-make-palindrome-from-substring/">花花酱 LeetCode 1177. Can Make Palindrome from Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1177-can-make-palindrome-from-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 748. Shortest Completing Word</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 20 Dec 2017 16:23:52 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[frequency]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1294</guid>

					<description><![CDATA[<p>题目大意: 给你一个由字母和数字组成车牌。另外给你一些单词，让你找一个最短的单词能够覆盖住车牌中的字母（不考虑大小写）。如果有多个解，输出第一个解。 Problem: Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/">花花酱 LeetCode 748. Shortest Completing Word</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><iframe width="500" height="375" src="https://www.youtube.com/embed/vHzPkqpPiWk?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意: 给你一个由字母和数字组成车牌。另外给你一些单词，让你找一个最短的单词能够覆盖住车牌中的字母（不考虑大小写）。如果有多个解，输出第一个解。</p>
<p><strong>Problem:</strong></p>
<p>Find the minimum length word from a given dictionary <code>words</code>, which has all the letters from the string <code>licensePlate</code>. Such a word is said to <i>complete</i> the given string <code>licensePlate</code></p>
<p>Here, for letters we ignore case. For example, <code>"P"</code> on the <code>licensePlate</code> still matches <code>"p"</code> on the word.</p>
<p>It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.</p>
<p>The license plate might have the same letter occurring multiple times. For example, given a <code>licensePlate</code> of <code>"PP"</code>, the word <code>"pair"</code> does not complete the <code>licensePlate</code>, but the word <code>"supper"</code> does.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: licensePlate = &quot;1s3 PSt&quot;, words = [&quot;step&quot;, &quot;steps&quot;, &quot;stripe&quot;, &quot;stepple&quot;]
Output: &quot;steps&quot;
Explanation: The smallest length word that contains the letters &quot;S&quot;, &quot;P&quot;, &quot;S&quot;, and &quot;T&quot;.
Note that the answer is not &quot;step&quot;, because the letter &quot;s&quot; must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: licensePlate = &quot;1s3 456&quot;, words = [&quot;looks&quot;, &quot;pest&quot;, &quot;stew&quot;, &quot;show&quot;]
Output: &quot;pest&quot;
Explanation: There are 3 smallest length words that contains the letters &quot;s&quot;.
We return the one that occurred first.</pre><p><b>Note:</b></p>
<ol>
<li><code>licensePlate</code> will be a string with length in range <code>[1, 7]</code>.</li>
<li><code>licensePlate</code> will contain digits, spaces, or letters (uppercase or lowercase).</li>
<li><code>words</code> will have a length in the range <code>[10, 1000]</code>.</li>
<li>Every <code>words[i]</code> will consist of lowercase letters, and have length in range <code>[1, 15]</code>.</li>
</ol>
<p><strong>Idea:</strong></p>
<p>Hashtable</p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: 时间复杂度 O(N*26), N is number of words.</p>
<p>Space complexity: 空间复杂度 O(26) = O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 15 ms
class Solution {
public:
    string shortestCompletingWord(string licensePlate, vector&lt;string&gt;&amp; words) {
        vector&lt;int&gt; l(26, 0);
        for (const char ch : licensePlate)
            if (isalpha(ch)) ++l[tolower(ch) - 'a'];
        string ans;
        int min_l = INT_MAX;
        for (const string&amp; word : words) {
            if (word.length() &gt;= min_l) continue;
            if (!matches(l, word)) continue;
            min_l = word.length();
            ans = word;
        }
        return ans;
    }
private:
    bool matches(const vector&lt;int&gt;&amp; l, const string&amp; word) {
        vector&lt;int&gt; c(26, 0);
        for (const char ch : word)
            ++c[tolower(ch) - 'a'];        
        for (int i = 0; i &lt; 26; ++i)
            if (c[i] &lt; l[i]) return false;
        return true;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/">花花酱 LeetCode 748. Shortest Completing Word</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-748-shortest-completing-word/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 347. Top K Frequent Elements</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-347-top-k-frequent-elements/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-347-top-k-frequent-elements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Oct 2017 07:05:08 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[Medium]]></category>
		<category><![CDATA[buckets]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=669</guid>

					<description><![CDATA[<p>Problem: Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: You&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-347-top-k-frequent-elements/">花花酱 LeetCode 347. Top K Frequent Elements</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><iframe width="500" height="375" src="https://www.youtube.com/embed/lm6pBga98-w?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a non-empty array of integers, return the k most frequent elements.</p>
<p>For example,<br />
Given [1,1,1,2,2,3] and k = 2, return [1,2].</p>
<p>Note:<br />
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.<br />
Your algorithm&#8217;s time complexity must be better than O(n log n), where n is the array&#8217;s size.</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95.png"><img class="alignnone size-full wp-image-677" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/347-ep95-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<h1>Solution 2: Priority queue / max heap</h1>
<p>Time complexity: O(n) + O(nlogk)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahuas
// Running time: 16 ms
class Solution {
public:
  vector&lt;int&gt; topKFrequent(vector&lt;int&gt;&amp; nums, int k) {
    unordered_map&lt;int, int&gt; count;        
    for (const int num : nums)
      ++count[num];
    priority_queue&lt;pair&lt;int, int&gt;&gt; q;
    for (const auto&amp; pair : count) {
      q.emplace(-pair.second, pair.first);
      if (q.size() &gt; k) q.pop();
    }
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; k; ++i) {
      ans.push_back(q.top().second);
      q.pop();
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 56 ms
class Solution {
  public List&lt;Integer&gt; topKFrequent(int[] nums, int k) {    
    Map&lt;Integer, Integer&gt; counts = new HashMap&lt;&gt;();    
    for (int num : nums)
      counts.put(num, counts.getOrDefault(num, 0) + 1);    
    
    PriorityQueue&lt;int[]&gt; queue = new PriorityQueue&lt;&gt;((x, y) -&gt; x[0] - y[0]);
    for (Integer num : counts.keySet()) {
      queue.offer(new int[]{counts.get(num), num});
      if (queue.size() &gt; k) queue.poll();
    }
        
    List&lt;Integer&gt; ans = new ArrayList&lt;&gt;();
    for (int i = 0; i &lt; k; ++i)
      ans.add(queue.poll()[1]);
    return ans;    
  }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 56 ms
"""
class Solution:
  def topKFrequent(self, nums, k):
    counts = collections.Counter(nums)
    h = []
    for num in counts.keys():
      heapq.heappush(h, (counts[num], num))
      if len(h) &gt; k: heapq.heappop(h)
    return [heapq.heappop(h)[1] for i in range(k)]</pre><p></div></div></p>
<h1><strong>Solution 3: Bucket Sort</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++/hashmap</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;int&gt; topKFrequent(vector&lt;int&gt;&amp; nums, int k) {
        unordered_map&lt;int, int&gt; count;
        int max_freq = 1;
        for (const int num : nums)
            max_freq = max(max_freq, ++count[num]);
        map&lt;int, vector&lt;int&gt;&gt; buckets;
        for (const auto&amp; kv : count)
            buckets[kv.second].push_back(kv.first);
        vector&lt;int&gt; ans;
        for (int i = max_freq; i &gt;= 1; --i) {
            auto it = buckets.find(i);
            if (it == buckets.end()) continue;
            ans.insert(ans.end(), it-&gt;second.begin(), it-&gt;second.end());
            if (ans.size() == k) return ans;
        }
        return ans;
    }
};</pre><p></div><h2 class="tabtitle">C++/array</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;int&gt; topKFrequent(vector&lt;int&gt;&amp; nums, int k) {
        unordered_map&lt;int, int&gt; count;
        for (const int num : nums)
            ++count[num];
        vector&lt;vector&lt;int&gt;&gt; buckets(nums.size() + 1);
        for (const auto&amp; kv : count)
            buckets[kv.second].push_back(kv.first);
        vector&lt;int&gt; ans;
        for (auto it = buckets.rbegin(); it != buckets.rend(); ++it) {
            const vector&lt;int&gt;&amp; keys = *it;
            if (keys.empty()) continue;
            ans.insert(ans.begin(), keys.begin(), keys.end());
            if (ans.size() == k) return ans;
        }
        return ans;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms
class Solution {
  public List&lt;Integer&gt; topKFrequent(int[] nums, int k) {
    List[] buckets = new List[nums.length + 1];
    Map&lt;Integer, Integer&gt; counts = new HashMap&lt;&gt;();

    for (int num : nums)      
      counts.put(num, counts.getOrDefault(num, 0) + 1);    
        
    for (int num : counts.keySet()) {
      int count = counts.get(num);
      if (buckets[count] == null)
        buckets[count] = new ArrayList&lt;Integer&gt;();
      buckets[count].add(num);
    }
    
    List&lt;Integer&gt; ans = new ArrayList&lt;&gt;();
    for (int i = buckets.length - 1; i &gt; 0 &amp;&amp; ans.size() &lt; k; --i) {
      if (buckets[i] != null) ans.addAll(buckets[i]);      
    }
    return ans;    
  }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 64 ms
"""
class Solution:
  def topKFrequent(self, nums, k):
    counts = collections.Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]    
    for num in counts.keys():
      buckets[counts[num]].append(num)
    ans = []
    for i in range(len(nums), 0, -1):      
      ans += buckets[i]      
      if len(ans) == k: return ans
    return ans</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/heap/leetcode-692-top-k-frequent-words/">[解题报告] LeetCode 692. Top K Frequent Words</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-347-top-k-frequent-elements/">花花酱 LeetCode 347. Top K Frequent Elements</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-347-top-k-frequent-elements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 692. Top K Frequent Words</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-692-top-k-frequent-words/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-692-top-k-frequent-words/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Oct 2017 00:51:38 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[Medium]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=661</guid>

					<description><![CDATA[<p>Problem: Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-692-top-k-frequent-words/">花花酱 LeetCode 692. Top K Frequent Words</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><iframe width="500" height="375" src="https://www.youtube.com/embed/POERw4yDVBw?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a non-empty list of words, return the <i>k</i> most frequent elements.</p>
<p>Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: [&quot;i&quot;, &quot;love&quot;, &quot;leetcode&quot;, &quot;i&quot;, &quot;love&quot;, &quot;coding&quot;], k = 2
Output: [&quot;i&quot;, &quot;love&quot;]
Explanation: &quot;i&quot; and &quot;love&quot; are the two most frequent words.
    Note that &quot;i&quot; comes before &quot;love&quot; due to a lower alphabetical order.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: [&quot;the&quot;, &quot;day&quot;, &quot;is&quot;, &quot;sunny&quot;, &quot;the&quot;, &quot;the&quot;, &quot;the&quot;, &quot;sunny&quot;, &quot;is&quot;, &quot;is&quot;], k = 4
Output: [&quot;the&quot;, &quot;is&quot;, &quot;sunny&quot;, &quot;day&quot;]
Explanation: &quot;the&quot;, &quot;is&quot;, &quot;sunny&quot; and &quot;day&quot; are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.</pre><p><b>Note:</b></p>
<ol>
<li>You may assume <i>k</i> is always valid, 1 ≤ <i>k</i> ≤ number of unique elements.</li>
<li>Input words contain only lowercase letters.</li>
</ol>
<p><b>Follow up:</b></p>
<ol>
<li>Try to solve it in <i>O</i>(<i>n</i> log <i>k</i>) time and <i>O</i>(<i>n</i>) extra space.</li>
</ol>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Priority queue / min heap</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94.png"><img class="alignnone size-full wp-image-666" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/692-ep94-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution</strong></p>
<p>C++ / priority_queue O(n log k) / O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 13 ms (&lt; 90.31 %)
class Solution {
private:
    typedef pair&lt;string, int&gt; Node;
    typedef function&lt;bool(const Node&amp;, const Node&amp;)&gt; Compare;
public:
    vector&lt;string&gt; topKFrequent(vector&lt;string&gt;&amp; words, int k) {
        unordered_map&lt;string, int&gt; count;
        for (const string&amp; word : words)
            ++count[word];
        
        Compare comparator = [](const Node&amp; a, const Node&amp; b) {
            // order by alphabet ASC
            if (a.second == b.second) 
                return  a.first &lt; b.first;
            // order by freq DESC
            return a.second &gt; b.second;
        };
        
        // Min heap by frequency
        priority_queue&lt;Node, vector&lt;Node&gt;, Compare&gt; q(comparator);
        
        // O(n*logk)
        for (const auto&amp; kv : count) {
            q.push(kv);
            if (q.size() &gt; k) q.pop();
        }
        
        vector&lt;string&gt; ans;
        
        while (!q.empty()) {
            ans.push_back(q.top().first);
            q.pop();
        }
        
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
};</pre><p><strong>Related Problems</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-347-top-k-frequent-elements/">[解题报告] LeetCode 347. Top K Frequent Elements</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-692-top-k-frequent-words/">花花酱 LeetCode 692. Top K Frequent Words</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/heap/leetcode-692-top-k-frequent-words/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 409. Longest Palindrome</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-409-longest-palindrome/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-409-longest-palindrome/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 20 Sep 2017 03:08:56 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[frequency]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=356</guid>

					<description><![CDATA[<p>https://leetcode.com/problems/longest-palindrome/description/ Problem: Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-409-longest-palindrome/">花花酱 LeetCode 409. Longest Palindrome</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><iframe width="500" height="375" src="https://www.youtube.com/embed/4GU7QvWffHQ?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><a href="https://leetcode.com/problems/longest-palindrome/description/">https://leetcode.com/problems/longest-palindrome/description/</a></p>
<p><strong>Problem:</strong></p>
<p>Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.</p>
<p>This is case sensitive, for example <code>"Aa"</code> is not considered a palindrome here.</p>
<p><b>Note:</b><br />
Assume the length of given string will not exceed 1,010.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Input:
&quot;abccccdd&quot;

Output:
7

Explanation:
One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7.</pre><p><strong>Idea:</strong></p>
<p>Greedy + Counting</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64.png"><img class="alignnone size-full wp-image-359" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/409-ep64-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Time complexity: O(n)
// Space complexity: O(128) = O(1)
// Running time: 3 ms 9/2017
class Solution {
public:
    int longestPalindrome(const string&amp; s) {
        vector&lt;int&gt; freqs(128, 0);
        for (const char c : s)            
            ++freqs[c];

        int ans = 0;
        int odd = 0;
        for (const int freq : freqs) {            
            // same as: ans += freq % 2 == 0 ? freq : freq - 1;
            // same as: ans += freq / 2 * 2;
            // same as: ans += ((freq &gt;&gt; 1) &lt;&lt; 1);            
            // same as: ans += freq &amp; (INT_MAX - 1);
            ans += freq &amp; (~1); // clear the last bit
            odd |= freq &amp; 1;
        }
        
        ans += odd;
        
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 11 ms
class Solution {
    public int longestPalindrome(String s) {        
        int[] freqs = new int[128];
        for (int i = 0; i &lt; s.length(); ++i)
            ++freqs[s.charAt(i)];
        
        int ans = 0;
        int odd = 0;
        
        for (int freq: freqs) {
            ans += freq &amp; (~1);
            odd |= freq &amp; 1;
        }
        
        return ans + odd;
    }
}</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 39 ms
"""
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        freqs = [0] * 128
        
        for c in s:
            freqs[ord(c)] += 1
        
        ans, odd = 0, 0
        for freq in freqs:
            ans += freq &amp; (~1)
            odd |= freq &amp; 1
        
        return ans + odd</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-409-longest-palindrome/">花花酱 LeetCode 409. Longest Palindrome</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-409-longest-palindrome/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 451. Sort Characters By Frequency</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-451-sort-characters-by-frequency/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-451-sort-characters-by-frequency/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Mar 2017 20:02:35 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[frequency]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=30</guid>

					<description><![CDATA[<p>Given a string, sort it in decreasing order based on the frequency of characters. Example 1: [crayon-663c91589d938555900511/] Example 2: [crayon-663c91589d93b086944046/] Example 3: [crayon-663c91589d93c860613834/] Solution: [crayon-663c91589d93d988863330/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-451-sort-characters-by-frequency/">花花酱 LeetCode 451. Sort Characters By Frequency</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, sort it in decreasing order based on the frequency of characters.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">&lt;b&gt;Input:&lt;/b&gt;
&quot;tree&quot;

&lt;b&gt;Output:&lt;/b&gt;
&quot;eert&quot;

&lt;b&gt;Explanation:&lt;/b&gt;
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore &quot;eetr&quot; is also a valid answer.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">&lt;b&gt;Input:&lt;/b&gt;
"cccaaa"

&lt;b&gt;Output:&lt;/b&gt;
"cccaaa"

&lt;b&gt;Explanation:&lt;/b&gt;
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.</pre><p><b>Example 3:</b></p><pre class="crayon-plain-tag">&lt;b&gt;Input:&lt;/b&gt;
"Aabb"

&lt;b&gt;Output:&lt;/b&gt;
"bbAa"

&lt;b&gt;Explanation:&lt;/b&gt;
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.</pre><p></p>
<div></div>
<div><strong>Solution:</strong></div>
<div>
<pre class="crayon-plain-tag">class Solution {
public:
    string frequencySort(string s) {
        map&lt;char, int&gt; f;
        for(char c:s) ++f[c];
        vector&lt;pair&lt;int,char&gt;&gt; v;
        for(auto&amp; kv : f)
            v.push_back({kv.second, kv.first});
        sort(v.rbegin(), v.rend());
        stringstream ans;
        for(auto&amp; kv : v)
            ans &lt;&lt; string(kv.first, kv.second);
        return ans.str();
    }
};</pre><br />
&nbsp;</p>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-451-sort-characters-by-frequency/">花花酱 LeetCode 451. Sort Characters By Frequency</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/leetcode/leetcode-451-sort-characters-by-frequency/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
