<?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>bitset Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/bitset/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/bitset/</link>
	<description></description>
	<lastBuildDate>Sun, 30 Apr 2023 15:17:54 +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>bitset Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/bitset/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2657. Find the Prefix Common Array of Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 15:10:21 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[mask]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10027</guid>

					<description><![CDATA[<p>You are given two&#160;0-indexed&#160;integer&#160;permutations&#160;A&#160;and&#160;B&#160;of length&#160;n. A&#160;prefix common array&#160;of&#160;A&#160;and&#160;B&#160;is an array&#160;C&#160;such that&#160;C[i]&#160;is equal to the count of numbers that are present at or before the index&#160;i&#160;in&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/">花花酱 LeetCode 2657. Find the Prefix Common Array of Two Arrays</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 two&nbsp;<strong>0-indexed&nbsp;</strong>integer<strong>&nbsp;</strong>permutations&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;of length&nbsp;<code>n</code>.</p>



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



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



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



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



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



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



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



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



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



<h2><strong>Solution 1: Bitset</strong></h2>



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



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



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

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



<h2><strong>Solution 2: Counter</strong></h2>



<p>Use a counter to track the frequency of each element, when the counter[x] == 2, we found a pair.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findThePrefixCommonArray(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    vector&lt;int&gt; count(A.size() + 1);
    vector&lt;int&gt; ans;
    for (int i = 0, s = 0; i &lt; A.size(); ++i) {
      if (++count[A[i]] == 2) ++s;
      if (++count[B[i]] == 2) ++s;
      ans.push_back(s);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2657-find-the-prefix-common-array-of-two-arrays/">花花酱 LeetCode 2657. Find the Prefix Common Array of Two Arrays</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-2657-find-the-prefix-common-array-of-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2133. Check if Every Row and Column Contains All Numbers</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2133-check-if-every-row-and-column-contains-all-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2133-check-if-every-row-and-column-contains-all-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Jan 2022 14:09:12 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[easy]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9421</guid>

					<description><![CDATA[<p>An&#160;n x n&#160;matrix is&#160;valid&#160;if every row and every column contains&#160;all&#160;the integers from&#160;1&#160;to&#160;n&#160;(inclusive). Given an&#160;n x n&#160;integer matrix&#160;matrix, return&#160;true&#160;if the matrix is&#160;valid.&#160;Otherwise, return&#160;false. Example 1: Input:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2133-check-if-every-row-and-column-contains-all-numbers/">花花酱 LeetCode 2133. Check if Every Row and Column Contains All 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>An&nbsp;<code>n x n</code>&nbsp;matrix is&nbsp;<strong>valid</strong>&nbsp;if every row and every column contains&nbsp;<strong>all</strong>&nbsp;the integers from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>&nbsp;(<strong>inclusive</strong>).</p>



<p>Given an&nbsp;<code>n x n</code>&nbsp;integer matrix&nbsp;<code>matrix</code>, return&nbsp;<code>true</code>&nbsp;<em>if the matrix is&nbsp;<strong>valid</strong>.</em>&nbsp;Otherwise, return&nbsp;<code>false</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/21/example1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,2,3],[3,1,2],[2,3,1]]
<strong>Output:</strong> true
<strong>Explanation:</strong> In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.
Hence, we return true.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/21/example2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,1,1],[1,2,3],[1,2,3]]
<strong>Output:</strong> false
<strong>Explanation:</strong> In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.
Hence, we return false.
</pre>



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



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



<h2><strong>Solution: Bitset / hashtable</strong></h2>



<p>Time complexity: O(n<sup>2</sup>)<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:
  bool checkValid(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int n = matrix.size();
    for (int i = 0; i &lt; n; ++i) {
      bitset&lt;101&gt; row;
      bitset&lt;101&gt; col;
      for (int j = 0; j &lt; n; ++j)
        col[matrix[i][j]] = row[matrix[j][i]] = true;      
      if (row.count() != n || col.count() != n) 
        return false;
    }
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2133-check-if-every-row-and-column-contains-all-numbers/">花花酱 LeetCode 2133. Check if Every Row and Column Contains All 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-2133-check-if-every-row-and-column-contains-all-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1935. Maximum Number of Words You Can Type</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1935-maximum-number-of-words-you-can-type/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1935-maximum-number-of-words-you-can-type/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 13:03:44 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9298</guid>

					<description><![CDATA[<p>There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string&#160;text&#160;of words separated&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1935-maximum-number-of-words-you-can-type/">花花酱 LeetCode 1935. Maximum Number of Words You Can Type</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.</p>



<p>Given a string&nbsp;<code>text</code>&nbsp;of words separated by a single space (no leading or trailing spaces) and a string&nbsp;<code>brokenLetters</code>&nbsp;of all&nbsp;<strong>distinct</strong>&nbsp;letter keys that are broken, return&nbsp;<em>the&nbsp;<strong>number of words</strong>&nbsp;in</em>&nbsp;<code>text</code>&nbsp;<em>you can fully type using this keyboard</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "hello world", brokenLetters = "ad"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We cannot type "world" because the 'd' key is broken.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "leet code", brokenLetters = "lt"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We cannot type "leet" because the 'l' and 't' keys are broken.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> text = "leet code", brokenLetters = "e"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We cannot type either word because the 'e' key is broken.
</pre>



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



<ul><li><code>1 &lt;= text.length &lt;= 10<sup>4</sup></code></li><li><code>0 &lt;= brokenLetters.length &lt;= 26</code></li><li><code>text</code>&nbsp;consists of words separated by a single space without any leading or trailing spaces.</li><li>Each word only consists of lowercase English letters.</li><li><code>brokenLetters</code>&nbsp;consists of&nbsp;<strong>distinct</strong>&nbsp;lowercase English letters.</li></ul>



<h2><strong>Solution: Hashset / bitset</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int canBeTypedWords(string text, string brokenLetters) {
    const int n = text.size();
    
    bitset&lt;26&gt; b;
    for (char c : brokenLetters) b.set(c - 'a');
    
    int ans = 0;
    for (int i = 0, broken = 0; i &lt;= n; ++i) {
      if (i == n || text[i] == ' ') {
        if (!broken) ++ans;
        broken = 0;
      } else {
        broken |= b[text[i] - 'a'];
      }
    }
    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1935-maximum-number-of-words-you-can-type/">花花酱 LeetCode 1935. Maximum Number of Words You Can Type</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-1935-maximum-number-of-words-you-can-type/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 06:28:26 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9293</guid>

					<description><![CDATA[<p>Given a string&#160;s, return&#160;the number of&#160;unique palindromes of length three&#160;that are a&#160;subsequence&#160;of&#160;s. Note that even if there are multiple ways to obtain the same subsequence,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/">花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</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>unique palindromes of length three</strong>&nbsp;that are a&nbsp;<strong>subsequence</strong>&nbsp;of&nbsp;</em><code>s</code>.</p>



<p>Note that even if there are multiple ways to obtain the same subsequence, it is still only counted&nbsp;<strong>once</strong>.</p>



<p>A&nbsp;<strong>palindrome</strong>&nbsp;is a string that reads the same forwards and backwards.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>



<ul><li>For example,&nbsp;<code>"ace"</code>&nbsp;is a subsequence of&nbsp;<code>"<u>a</u>b<u>c</u>d<u>e</u>"</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabca"
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "adc"
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no palindromic subsequences of length 3 in "adc".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "bbcbaba"
<strong>Output:</strong> 4
<strong>Explanation:</strong> The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
</pre>



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



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



<h2><strong>Solution: Enumerate first <meta charset="utf-8">character of a palindrome</strong></h2>



<p>For a length 3 palindrome, we just need to enumerate the first character c.<br>We found the first and last occurrence of c in original string and scan the middle part to see how many unique characters there.<br><br>e.g. <meta charset="utf-8">aabca<br>Enumerate from a to z, looking for a*a, b*b, &#8230;, z*z.<br>For a*a, <meta charset="utf-8"><span style="text-decoration: underline;"><strong><span class="has-inline-color has-vivid-cyan-blue-color">a</span></strong></span><span class="has-inline-color has-vivid-red-color"><strong>abc</strong></span><span style="text-decoration: underline;"><span class="has-inline-color has-vivid-cyan-blue-color"><strong>a</strong></span></span>, we found first and last a, in between is <meta charset="utf-8"><span class="has-inline-color has-vivid-red-color"><strong>abc</strong></span>, which has 3 unique letters. <br>We can use a hastable or a bitset to track unique letters.</p>



<p>Time complexity: O(26*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 countPalindromicSubsequence(string s) {
    auto count = [&amp;](char c) -&gt; int {
      int l = s.find_first_of(c);
      int r = s.find_last_of(c);
      if (l == string::npos || r == string::npos) return 0;
      bitset&lt;26&gt; m;
      for (int i = l + 1; i &lt; r; ++i)
        m.set(s[i] - 'a');
      return m.count();
    };
    int ans = 0;
    for (char c = 'a'; c &lt;= 'z'; ++c)
      ans += count(c);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/">花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</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-1930-unique-length-3-palindromic-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1719. Number Of Ways To Reconstruct A Tree</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1719-number-of-ways-to-reconstruct-a-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1719-number-of-ways-to-reconstruct-a-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 06:12:41 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7954</guid>

					<description><![CDATA[<p>You are given an array&#160;pairs, where&#160;pairs[i] = [xi, yi], and: There are no duplicates. xi&#160;&#60; yi Let&#160;ways&#160;be the number of rooted trees that satisfy the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1719-number-of-ways-to-reconstruct-a-tree/">花花酱 LeetCode 1719. Number Of Ways To Reconstruct A Tree</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>pairs</code>, where&nbsp;<code>pairs[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>, and:</p>



<ul><li>There are no duplicates.</li><li><code>x<sub>i</sub>&nbsp;&lt; y<sub>i</sub></code></li></ul>



<p>Let&nbsp;<code>ways</code>&nbsp;be the number of rooted trees that satisfy the following conditions:</p>



<ul><li>The tree consists of nodes whose values appeared in&nbsp;<code>pairs</code>.</li><li>A pair&nbsp;<code>[x<sub>i</sub>, y<sub>i</sub>]</code>&nbsp;exists in&nbsp;<code>pairs</code>&nbsp;<strong>if and only if</strong>&nbsp;<code>x<sub>i</sub></code>&nbsp;is an ancestor of&nbsp;<code>y<sub>i</sub></code>&nbsp;or&nbsp;<code>y<sub>i</sub></code>&nbsp;is an ancestor of&nbsp;<code>x<sub>i</sub></code>.</li><li><strong>Note:</strong>&nbsp;the tree does not have to be a binary tree.</li></ul>



<p>Two ways are considered to be different if there is at least one node that has different parents in both ways.</p>



<p>Return:</p>



<ul><li><code>0</code>&nbsp;if&nbsp;<code>ways == 0</code></li><li><code>1</code>&nbsp;if&nbsp;<code>ways == 1</code></li><li><code>2</code>&nbsp;if&nbsp;<code>ways &gt; 1</code></li></ul>



<p>A&nbsp;<strong>rooted tree</strong>&nbsp;is a tree that has a single root node, and all edges are oriented to be outgoing from the root.</p>



<p>An&nbsp;<strong>ancestor</strong>&nbsp;of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/03/trees2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> pairs = [[1,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is exactly one valid rooted tree, which is shown in the above figure.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/03/tree.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> pairs = [[1,2],[2,3],[1,3]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are multiple valid rooted trees. Three of them are shown in the above figures.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> pairs = [[1,2],[2,3],[2,4],[1,5]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no valid rooted trees.</pre>



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



<ul><li><code>1 &lt;= pairs.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= x<sub>i&nbsp;</sub>&lt; y<sub>i</sub>&nbsp;&lt;= 500</code></li><li>The elements in&nbsp;<code>pairs</code>&nbsp;are unique.</li></ul>



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



<p>Time complexity: O(E*V)<br>Space complexity: O(V^2)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int checkWays(vector&lt;vector&lt;int&gt;&gt;&amp; pairs) {
    // Construct a map, key is the node, value is the accessible nodes.
    unordered_map&lt;int, bitset&lt;501&gt;&gt; m;
    for (auto&amp; e : pairs) 
      m[e[0]][e[0]] = m[e[1]][e[1]] = m[e[0]][e[1]] = m[e[1]][e[0]] = 1;
    
    // The tree must have one+ node/root that has paths to all the nodes.
    if (!any_of(begin(m), end(m), [&amp;m](const auto&amp; kv) {
      return kv.second.count() == m.size();})) return 0;
    
    int multiple = 0;
    for (const auto&amp; e : pairs) {
      // For each pair, check whether one can be the parent of another
      // that can conver all the children nodes.
      const auto&amp; all = m[e[0]] | m[e[1]];
      const int r0 = m[e[0]] == all;
      const int r1 = m[e[1]] == all;
      if (r0 + r1 == 0) return 0;
      // If both can be parents, there can be multiple trees.
      multiple |= r0 * r1;
    }
    return 1 + multiple;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def checkWays(self, pairs: List[List[int]]) -&gt; int:
    m = defaultdict(set)
    for u, v in pairs:
      m[u] |= set((u, v))
      m[v] |= set((u, v))
    
    if not any(len(m[x]) == len(m) for x in m):
      return 0
    
    multiple = 0
    for u, v in pairs:
      union = m[u] | m[v]
      ru, rv = int(m[u] == union), int(m[v] == union)
      if not ru + rv: return 0
      multiple |= ru * rv
    return 1 + multiple</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1719-number-of-ways-to-reconstruct-a-tree/">花花酱 LeetCode 1719. Number Of Ways To Reconstruct A Tree</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/graph/leetcode-1719-number-of-ways-to-reconstruct-a-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 575. Distribute Candies</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-575-distribute-candies/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-575-distribute-candies/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 05 Mar 2018 16:11:09 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1964</guid>

					<description><![CDATA[<p>题目大意：有一些不同种类的糖果，男生女生各得一半数量的糖果，问女生最多可能得到多少种不同种类的糖果。 Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-575-distribute-candies/">花花酱 LeetCode 575. Distribute Candies</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>题目大意：有一些不同种类的糖果，男生女生各得一半数量的糖果，问女生最多可能得到多少种不同种类的糖果。</p>
<p>Given an integer array with <b>even</b> length, where different numbers in this array represent different <b>kinds</b> of candies. Each number means one candy of the corresponding kind. You need to distribute these candies <b>equally</b> in number to brother and sister. Return the maximum number of <b>kinds</b> of candies the sister could gain.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. 
The sister has three different kinds of candies.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. 
The sister has two different kinds of candies, the brother has only one kind of candies.</pre><p><b>Note:</b></p>
<ol>
<li>The length of the given array is in range [2, 10,000], and will be even.</li>
<li>The number in given array is in range [-100,000, 100,000].</li>
</ol>
<p><strong>Solution 1: Greedy</strong></p>
<p>Give all unique candies to sisters until they have n/2 candies.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>C++ Hashset</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 258 ms
class Solution {
public:
  int distributeCandies(vector&lt;int&gt;&amp; candies) {
    unordered_set&lt;int&gt; kinds(candies.begin(), candies.end());
    return min(kinds.size(), candies.size() / 2);
  }
};</pre><p>C++ Bitset</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 195 ms (beats 97.61%)
class Solution {
public:
  int distributeCandies(vector&lt;int&gt;&amp; candies) {
    constexpr int kMaxKinds = 200001;
    constexpr int kOffset = 100000;
    bitset&lt;kMaxKinds&gt; s;    
    for (int candy : candies)
      if (!s.test(candy + kOffset))
          s.set(candy + kOffset);
    return std::min(s.count(), candies.size() / 2);
  }
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-575-distribute-candies/">花花酱 LeetCode 575. Distribute Candies</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-575-distribute-candies/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
