<?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>Hashtable &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/hashtable/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 30 Mar 2025 00:40:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Hashtable &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2353. Design a Food Rating System</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2353-design-a-food-rating-system/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2353-design-a-food-rating-system/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Mar 2025 00:38:41 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[orderedset]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10241</guid>

					<description><![CDATA[Hashtable + TreeSet / OrderedSet 用了三个Hashtable&#8230; 菜名 -> 菜系 菜系 -> Treemap 菜名 -> 所在Treemap中的迭代器 每个菜系用一个TreeSet来保存从高到低的菜色排名，查询的时候只要拿出第一个就好了。 修改的时候，拿出迭代器，删除原来的评分，再把新的评分加入（别忘了更新迭代器） 时间复杂度：构造O(nlogn)，修改O(logn)，查询O(1) 空间复杂度：O(n) [crayon-69b0542dbaa3d944959124/]]]></description>
										<content:encoded><![CDATA[
<p>Hashtable + TreeSet / OrderedSet</p>



<p>用了三个Hashtable&#8230;</p>



<ol class="wp-block-list"><li>菜名 -> 菜系</li><li>菜系 -> Treemap</li><li>菜名 -> 所在Treemap中的迭代器</li></ol>



<p>每个菜系用一个TreeSet来保存从高到低的菜色排名，查询的时候只要拿出第一个就好了。</p>



<p>修改的时候，拿出迭代器，删除原来的评分，再把新的评分加入（别忘了更新迭代器）</p>



<p>时间复杂度：构造O(nlogn)，修改O(logn)，查询O(1)</p>



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



<pre class="urvanov-syntax-highlighter-plain-tag">class FoodRatings {
public:
  FoodRatings(vector&lt;string&gt;&amp; foods, vector&lt;string&gt;&amp; cuisines, vector&lt;int&gt;&amp; ratings) {
    const int n = foods.size();
    for (int i = 0; i &lt; n; ++i) {
      n_[foods[i]] = cuisines[i];
      m_[foods[i]] = c_[cuisines[i]].emplace(-ratings[i], foods[i]).first;
    }
  }
  
  void changeRating(string food, int newRating) {
    const string&amp; cuisine = n_[food];
    c_[cuisine].erase(m_[food]);
    m_[food] = c_[cuisine].emplace(-newRating, food).first;
  }
  
  string highestRated(string cuisine) {
    return begin(c_[cuisine])-&gt;second;
  }
private:
  unordered_map&lt;string, set&lt;pair&lt;int, string&gt;&gt;&gt; c_; // cuisine -&gt; {{-rating, name}}
  unordered_map&lt;string, string&gt; n_; // food -&gt; cuisine  
  unordered_map&lt;string, set&lt;pair&lt;int, string&gt;&gt;::iterator&gt; m_; // food -&gt; set iterator
};

/**
 * Your FoodRatings object will be instantiated and called as such:
 * FoodRatings* obj = new FoodRatings(foods, cuisines, ratings);
 * obj-&gt;changeRating(food,newRating);
 * string param_2 = obj-&gt;highestRated(cuisine);
 */</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2353-design-a-food-rating-system/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3242. Design Neighbor Sum Service</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-3242-design-neighbor-sum-service/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-3242-design-neighbor-sum-service/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Mar 2025 22:36:51 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[precompute]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10238</guid>

					<description><![CDATA[青铜 Brute Force：每次需要花费O(n*n)的时间去查找query所在的格子，求和是O(1)。总的时间复杂度达到O(n^4)，肯定会超时。 白银 Hashtable：由于所有元素的值的唯一的，我们可以使用hashtable（或者数组）来记录value所在的格子坐标，这样每次Query都是O(1)时间。时间复杂度：初始化O(n^2)，query O(1)。空间复杂度：O(n^2) [crayon-69b0542dbb6c4703762484/] 黄金 Precompute：在初始化的时候顺便求合，开两个数组一个存上下左右的，一个存对角线的。query的时候直接返回答案就可以了。时间复杂度和白银是一样的，但会快一些（省去了求合的过程）。 [crayon-69b0542dbb6d6860829647/]]]></description>
										<content:encoded><![CDATA[
<p>青铜 Brute Force：每次需要花费O(n*n)的时间去查找query所在的格子，求和是O(1)。总的时间复杂度达到O(n^4)，肯定会超时。</p>



<p>白银 Hashtable：由于所有元素的值的唯一的，我们可以使用hashtable（或者数组）来记录value所在的格子坐标，这样每次Query都是O(1)时间。<br>时间复杂度：初始化O(n^2)，query O(1)。<br>空间复杂度：O(n^2)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class NeighborSum {
public:
  NeighborSum(vector&lt;vector&lt;int&gt;&gt;&amp; grid): 
    n_(grid.size()), g_(&amp;grid), xy_(n_ * n_) {
    for (int i = 0; i &lt; n_; ++i)
      for (int j = 0; j &lt; n_; ++j)
        xy_[grid[i][j]] = {j, i};
  }
  
  int adjacentSum(int value) {
    auto [x, y] = xy_[value];
    return val(x, y - 1) + val(x, y + 1) + val(x + 1, y) + val(x - 1, y);
  }
  
  int diagonalSum(int value) {
    auto [x, y] = xy_[value];
    return val(x - 1, y - 1) + val(x - 1, y + 1) + val(x + 1, y - 1) + val(x + 1, y + 1);
  }
private:
  inline int val(int x, int y) const {
    if (x &lt; 0 || x &gt;= n_ || y &lt; 0 || y &gt;= n_) return 0;
    return (*g_)[y][x];
  }
  int n_;
  vector&lt;vector&lt;int&gt;&gt;* g_;
  vector&lt;pair&lt;int, int&gt;&gt; xy_;
};</pre>



<p>黄金 Precompute：在初始化的时候顺便求合，开两个数组一个存上下左右的，一个存对角线的。query的时候直接返回答案就可以了。<br>时间复杂度和白银是一样的，但会快一些（省去了求合的过程）。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class NeighborSum {
public:
  NeighborSum(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    int n = grid.size();
    adj_.resize(n * n);
    dia_.resize(n * n);
    auto v = [&amp;](int x, int y) -&gt; int {
      if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= n) 
        return 0;
      return grid[y][x];
    };
    for (int y = 0; y &lt; n; ++y)
      for (int x = 0; x &lt; n; ++x) {
        adj_[grid[y][x]] = v(x, y - 1) + v(x, y + 1) + v(x + 1, y) + v(x - 1, y);
        dia_[grid[y][x]] = v(x - 1, y - 1) + v(x - 1, y + 1) + v(x + 1, y - 1) + v(x + 1, y + 1);
      }
  }
  
  int adjacentSum(int value) {
    return adj_[value];
  }
  
  int diagonalSum(int value) {
    return dia_[value];
  }
private:
  vector&lt;int&gt; adj_;
  vector&lt;int&gt; dia_;
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-3242-design-neighbor-sum-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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[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;]]></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 class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 100</code></li><li><code>1 &lt;= nums[i] &lt;= 100</code></li></ul>



<h2 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 2661. First Completely Painted Row or Column</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 16:52:12 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10039</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;arr, and an&#160;m x n&#160;integer&#160;matrix&#160;mat.&#160;arr&#160;and&#160;mat&#160;both contain&#160;all&#160;the integers in the range&#160;[1, m * n]. Go through each index&#160;i&#160;in&#160;arr&#160;starting from index&#160;0&#160;and paint the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>arr</code>, and an&nbsp;<code>m x n</code>&nbsp;integer&nbsp;<strong>matrix</strong>&nbsp;<code>mat</code>.&nbsp;<code>arr</code>&nbsp;and&nbsp;<code>mat</code>&nbsp;both contain&nbsp;<strong>all</strong>&nbsp;the integers in the range&nbsp;<code>[1, m * n]</code>.</p>



<p>Go through each index&nbsp;<code>i</code>&nbsp;in&nbsp;<code>arr</code>&nbsp;starting from index&nbsp;<code>0</code>&nbsp;and paint the cell in&nbsp;<code>mat</code>&nbsp;containing the integer&nbsp;<code>arr[i]</code>.</p>



<p>Return&nbsp;<em>the smallest index</em>&nbsp;<code>i</code>&nbsp;<em>at which either a row or a column will be completely painted in</em>&nbsp;<code>mat</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://leetcode.com/problems/first-completely-painted-row-or-column/description/image%20explanation%20for%20example%201" alt=""/></figure>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2023/01/18/grid1.jpg" alt="image explanation for example 1"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2023/01/18/grid2.jpg" alt="image explanation for example 2"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The second column becomes fully painted at arr[3].
</pre>



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



<ul class="wp-block-list"><li><code>m == mat.length</code></li><li><code>n = mat[i].length</code></li><li><code>arr.length == m * n</code></li><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li><li>All the integers of&nbsp;<code>arr</code>&nbsp;are&nbsp;<strong>unique</strong>.</li><li>All the integers of&nbsp;<code>mat</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



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



<p>Use a map to store the position of each integer.</p>



<p>Use row counters and column counters to track how many elements have been painted.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int firstCompleteIndex(vector&lt;int&gt;&amp; arr, vector&lt;vector&lt;int&gt;&gt;&amp; mat) {
    const int m = mat.size();
    const int n = mat[0].size();
    vector&lt;int&gt; rows(m);
    vector&lt;int&gt; cols(n);
    vector&lt;pair&lt;int, int&gt;&gt; pos(m * n + 1);
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        pos[mat[i][j]] = {i, j};
    
    for (int i = 0; i &lt; arr.size(); ++i) {
      auto [r, c] = pos[arr[i]];
      if (++rows[r] == n) return i;
      if (++cols[c] == m) return i;
    }
    return -1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2588. Count the Number of Beautiful Subarrays</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 05:02:21 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix xor]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9984</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums. In one operation, you can: Choose two different indices&#160;i&#160;and&#160;j&#160;such that&#160;0 &#60;= i, j &#60; nums.length. Choose a non-negative integer&#160;k&#160;such that&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. In one operation, you can:</p>



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



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



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



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



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



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



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



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



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



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



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



<p>The problem is asking to find # of subarrays whose element wise xor is 0. We can use a hashtable to store the frequency of each prefix xor value, which reduces this problem to # of Subarray sum equal to k.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  long long beautifulSubarrays(vector&lt;int&gt;&amp; nums) {
    long long ans = 0;
    unordered_map&lt;int, int&gt; m{{0, 1}};
    int x = 0;
    for (int i = 0; i &lt; nums.size(); ++i) {
      x ^= nums[i];
      ans += m[x];
      m[x] += 1;
    }
    return ans;
  } 
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2588-count-the-number-of-beautiful-subarrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2564. Substring XOR Queries</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 16:50:41 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[precompute]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[xor]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9942</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



<p>Time complexity: O(n*32 + m)<br>Space complexity: O(n*32)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; substringXorQueries(string s, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    unordered_map&lt;int, vector&lt;int&gt;&gt; m;
    const int l = s.length();
    for (int i = 0; i &lt; l; ++i) {
      if (s[i] == '0') {
        if (!m.count(0)) m[0] = {i, i};
        continue;
      }
      for (int j = 0, cur = 0; j &lt; 32 &amp;&amp; i + j &lt; l; ++j) {
        cur = (cur &lt;&lt; 1) | (s[i + j] - '0');
        if (!m.count(cur))
          m[cur] = {i, i + j};
      }
    }
    vector&lt;vector&lt;int&gt;&gt; ans;    
    for (const auto&amp; q : queries) {
      int x = q[0] ^ q[1];
      if (m.count(x)) 
        ans.push_back(m[x]);
      else
        ans.push_back({-1, -1});
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2564-substring-xor-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2441. Largest Positive Integer That Exists With Its Negative</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Oct 2022 04:56:53 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[abs]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9866</guid>

					<description><![CDATA[Given an integer array&#160;nums&#160;that&#160;does not contain&#160;any zeros, find&#160;the largest positive&#160;integer&#160;k&#160;such that&#160;-k&#160;also exists in the array. Return&#160;the positive integer&#160;k. If there is no such integer, return&#160;-1.&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2441. Largest Positive Integer That Exists With Its Negative - 刷题找工作 EP404" width="500" height="281" src="https://www.youtube.com/embed/HItywpd0-yY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given an integer array&nbsp;<code>nums</code>&nbsp;that&nbsp;<strong>does not contain</strong>&nbsp;any zeros, find&nbsp;<strong>the largest positive</strong>&nbsp;integer&nbsp;<code>k</code>&nbsp;such that&nbsp;<code>-k</code>&nbsp;also exists in the array.</p>



<p>Return&nbsp;<em>the positive integer&nbsp;</em><code>k</code>. If there is no such integer, return&nbsp;<code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,2,-3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 3 is the only valid k we can find in the array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,10,6,7,-7,1]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-10,8,6,7,-2,-3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no a single valid k, we return -1.
</pre>



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



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



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



<p>We can do in one pass by checking whether -x in the hashtable and update ans with abs(x) if so.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    unordered_set&lt;int&gt; s;
    int ans = -1;
    for (int x : nums) {
      if (abs(x) &gt; ans &amp;&amp; s.count(-x))
        ans = abs(x);
      s.insert(x);
    }
    return ans;
  }
};</pre>
</div></div>



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



<p>Sort the array by abs(x) in descending order.</p>



<p>[-1,10,6,7,-7,1] becomes = [-1, 1, 6, -7, 7, 10]</p>



<p>Check whether arr[i] = -arr[i-1].</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    sort(begin(nums), end(nums), [](int a, int b){
      return abs(a) == abs(b) ? a &lt; b : abs(a) &gt; abs(b);
    });    
    for (int i = 1; i &lt; nums.size(); ++i)
      if (nums[i] == -nums[i - 1]) return nums[i];
    return -1;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 3: Two Pointers</strong></h2>



<p>Sort the array.</p>



<p>Let sum = nums[i] + nums[j], sum == 0, we find one pair, if sum &lt; 0, ++i else &#8211;j.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    sort(begin(nums), end(nums));
    int ans = -1;
    for (int i = 0, j = nums.size() - 1; i &lt; j; ) {
      const int s = nums[i] + nums[j];
      if (s == 0) {
        ans = max(ans, nums[j]);
        ++i, --j;      
      } else if (s &lt; 0) {
        ++i;
      } else {
        --j;
      }      
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2399. Check Distances Between Same Letters</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2399-check-distances-between-same-letters/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2399-check-distances-between-same-letters/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Sep 2022 15:32:25 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9821</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;string&#160;s&#160;consisting of only lowercase English letters, where each letter in&#160;s&#160;appears&#160;exactly&#160;twice. You are also given a&#160;0-indexed&#160;integer array&#160;distance&#160;of length&#160;26. Each letter in the alphabet&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>s</code>&nbsp;consisting of only lowercase English letters, where each letter in&nbsp;<code>s</code>&nbsp;appears&nbsp;<strong>exactly</strong>&nbsp;<strong>twice</strong>. You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>distance</code>&nbsp;of length&nbsp;<code>26</code>.</p>



<p>Each letter in the alphabet is numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>25</code>&nbsp;(i.e.&nbsp;<code>'a' -&gt; 0</code>,&nbsp;<code>'b' -&gt; 1</code>,&nbsp;<code>'c' -&gt; 2</code>, &#8230; ,&nbsp;<code>'z' -&gt; 25</code>).</p>



<p>In a&nbsp;<strong>well-spaced</strong>&nbsp;string, the number of letters between the two occurrences of the&nbsp;<code>i<sup>th</sup></code>&nbsp;letter is&nbsp;<code>distance[i]</code>. If the&nbsp;<code>i<sup>th</sup></code>&nbsp;letter does not appear in&nbsp;<code>s</code>, then&nbsp;<code>distance[i]</code>&nbsp;can be&nbsp;<strong>ignored</strong>.</p>



<p>Return&nbsp;<code>true</code><em>&nbsp;if&nbsp;</em><code>s</code><em>&nbsp;is a&nbsp;<strong>well-spaced</strong>&nbsp;string, otherwise return&nbsp;</em><code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
<strong>Output:</strong> true
<strong>Explanation:</strong>
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.
- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.
- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.
Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.
Return true because s is a well-spaced string.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
<strong>Output:</strong> false
<strong>Explanation:</strong>
- 'a' appears at indices 0 and 1 so there are zero letters between them.
Because distance[0] = 1, s is not a well-spaced string.
</pre>



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



<ul class="wp-block-list"><li><code>2 &lt;= s.length &lt;= 52</code></li><li><code>s</code>&nbsp;consists only of lowercase English letters.</li><li>Each letter appears in&nbsp;<code>s</code>&nbsp;exactly twice.</li><li><code>distance.length == 26</code></li><li><code>0 &lt;= distance[i] &lt;= 50</code></li></ul>



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



<p>Use a hastable to store the index of first occurrence of each letter.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool checkDistances(string s, vector&lt;int&gt;&amp; distance) {
    vector&lt;int&gt; m(26, -1);
    for (int i = 0; i &lt; s.length(); ++i) {
      int c = s[i] - 'a';
      if (m[c] &gt;= 0 &amp;&amp; i - m[c] - 1 != distance[c]) return false;
      m[c] = i;
    }
    return true;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2399-check-distances-between-same-letters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2404. Most Frequent Even Element</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2404-most-frequent-even-element%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2404-most-frequent-even-element%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Sep 2022 14:54:39 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[freq]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9804</guid>

					<description><![CDATA[Given an integer array&#160;nums, return&#160;the most frequent even element. If there is a tie, return the&#160;smallest&#160;one. If there is no such element, return&#160;-1. Example 1:&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>, return&nbsp;<em>the most frequent even element</em>.</p>



<p>If there is a tie, return the&nbsp;<strong>smallest</strong>&nbsp;one. If there is no such element, return&nbsp;<code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,2,2,4,4,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
We return the smallest one, which is 2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,4,4,9,2,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> 4 is the even element appears the most.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [29,47,21,41,13,37,25,7]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no even element.
</pre>



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



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



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



<p>Use a hashtable to store the frequency of even numbers.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int mostFrequentEven(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; m;
    int ans = -1;
    int best = 0;
    for (int x : nums) {
      if (x &amp; 1) continue;
      int cur = ++m[x];
      if (cur &gt; best) {
        best = cur;
        ans = x;
      } else if (cur == best &amp;&amp; x &lt; ans) {
        ans = x;
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2404-most-frequent-even-element%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2260. Minimum Consecutive Cards to Pick Up</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2260-minimum-consecutive-cards-to-pick-up/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2260-minimum-consecutive-cards-to-pick-up/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 04 May 2022 00:56:59 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9722</guid>

					<description><![CDATA[You are given an integer array&#160;cards&#160;where&#160;cards[i]&#160;represents the&#160;value&#160;of the&#160;ith&#160;card. A pair of cards are&#160;matching&#160;if the cards have the&#160;same&#160;value. Return&#160;the&#160;minimum&#160;number of&#160;consecutive&#160;cards you have to pick up to&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>cards</code>&nbsp;where&nbsp;<code>cards[i]</code>&nbsp;represents the&nbsp;<strong>value</strong>&nbsp;of the&nbsp;<code>i<sup>th</sup></code>&nbsp;card. A pair of cards are&nbsp;<strong>matching</strong>&nbsp;if the cards have the&nbsp;<strong>same</strong>&nbsp;value.</p>



<p>Return<em>&nbsp;the&nbsp;<strong>minimum</strong>&nbsp;number of&nbsp;<strong>consecutive</strong>&nbsp;cards you have to pick up to have a pair of&nbsp;<strong>matching</strong>&nbsp;cards among the picked cards.</em>&nbsp;If it is impossible to have matching cards, return&nbsp;<code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cards = [3,4,2,3,4,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cards = [1,0,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no way to pick up a set of consecutive cards that contain a pair of matching cards.
</pre>



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



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



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



<p>Record the last position of each number,<br>ans = min{card<sub>i</sub> &#8211; last[<meta charset="utf-8">card<sub>i</sub>]}</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumCardPickup(vector&lt;int&gt;&amp; cards) {
    const int n = cards.size();
    unordered_map&lt;int, int&gt; m;
    int ans = INT_MAX;
    for (int i = 0; i &lt; n; ++i) {
      if (m.count(cards[i]))
        ans = min(ans, i - m[cards[i]] + 1);
      m[cards[i]] = i;
    }
    return ans == INT_MAX ? -1 : ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2260-minimum-consecutive-cards-to-pick-up/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2248. Intersection of Multiple Arrays</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2248-intersection-of-multiple-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2248-intersection-of-multiple-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 27 Apr 2022 15:47:02 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9685</guid>

					<description><![CDATA[Given a 2D integer array&#160;nums&#160;where&#160;nums[i]&#160;is a non-empty array of&#160;distinct&#160;positive integers, return&#160;the list of integers that are present in&#160;each array&#160;ofnums&#160;sorted in&#160;ascending order. Example 1: Input: nums&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given a 2D integer array&nbsp;<code>nums</code>&nbsp;where&nbsp;<code>nums[i]</code>&nbsp;is a non-empty array of&nbsp;<strong>distinct</strong>&nbsp;positive integers, return&nbsp;<em>the list of integers that are present in&nbsp;<strong>each array</strong>&nbsp;of</em><code>nums</code><em>&nbsp;sorted in&nbsp;<strong>ascending order</strong></em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [[<strong>3</strong>,1,2,<strong>4</strong>,5],[1,2,<strong>3</strong>,<strong>4</strong>],[<strong>3</strong>,<strong>4</strong>,5,6]]
<strong>Output:</strong> [3,4]
<strong>Explanation:</strong> 
The only integers present in each of nums[0] = [<strong>3</strong>,1,2,<strong>4</strong>,5], nums[1] = [1,2,<strong>3</strong>,<strong>4</strong>], and nums[2] = [<strong>3</strong>,<strong>4</strong>,5,6] are 3 and 4, so we return [3,4].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [[1,2,3],[4,5,6]]
<strong>Output:</strong> []
<strong>Explanation:</strong> 
There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= sum(nums[i].length) &lt;= 1000</code></li><li><code>1 &lt;= nums[i][j] &lt;= 1000</code></li><li>All the values of&nbsp;<code>nums[i]</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; intersection(vector&lt;vector&lt;int&gt;&gt;&amp; nums) {
    vector&lt;int&gt; m(1001);
    for (const auto&amp; arr : nums)
      for (const int x : arr)
        ++m[x];
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; m.size(); ++i)
      if (m[i] == nums.size())
        ans.push_back(i);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2248-intersection-of-multiple-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2225. Find Players With Zero or One Losses</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2225-find-players-with-zero-or-one-losses/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2225-find-players-with-zero-or-one-losses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Apr 2022 04:54:47 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9620</guid>

					<description><![CDATA[You are given an integer array&#160;matches&#160;where&#160;matches[i] = [winneri, loseri]&#160;indicates that the player&#160;winneri&#160;defeated player&#160;loseri&#160;in a match. Return&#160;a list&#160;answer&#160;of size&#160;2&#160;where: answer[0]&#160;is a list of all players that&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>matches</code>&nbsp;where&nbsp;<code>matches[i] = [winner<sub>i</sub>, loser<sub>i</sub>]</code>&nbsp;indicates that the player&nbsp;<code>winner<sub>i</sub></code>&nbsp;defeated player&nbsp;<code>loser<sub>i</sub></code>&nbsp;in a match.</p>



<p>Return&nbsp;<em>a list&nbsp;</em><code>answer</code><em>&nbsp;of size&nbsp;</em><code>2</code><em>&nbsp;where:</em></p>



<ul class="wp-block-list"><li><code>answer[0]</code>&nbsp;is a list of all players that have&nbsp;<strong>not</strong>&nbsp;lost any matches.</li><li><code>answer[1]</code>&nbsp;is a list of all players that have lost exactly&nbsp;<strong>one</strong>&nbsp;match.</li></ul>



<p>The values in the two lists should be returned in&nbsp;<strong>increasing</strong>&nbsp;order.</p>



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



<ul class="wp-block-list"><li>You should only consider the players that have played&nbsp;<strong>at least one</strong>&nbsp;match.</li><li>The testcases will be generated such that&nbsp;<strong>no</strong>&nbsp;two matches will have the&nbsp;<strong>same</strong>&nbsp;outcome.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
<strong>Output:</strong> [[1,2,10],[4,5,7,8]]
<strong>Explanation:</strong>
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matches = [[2,3],[1,3],[5,4],[6,4]]
<strong>Output:</strong> [[1,2,5,6],[]]
<strong>Explanation:</strong>
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= matches.length &lt;= 10<sup>5</sup></code></li><li><code>matches[i].length == 2</code></li><li><code>1 &lt;= winner<sub>i</sub>, loser<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>winner<sub>i</sub>&nbsp;!= loser<sub>i</sub></code></li><li>All&nbsp;<code>matches[i]</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



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



<p>Use a hashtable to store the number of matches each player has lost. Note, also create an entry for those winners who never lose.</p>



<p>Time complexity: O(m), m = # of matches<br>Space complexity: O(n), n = # of players</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; findWinners(vector&lt;vector&lt;int&gt;&gt;&amp; matches) {
    unordered_map&lt;int, int&gt; m;
    for (const auto&amp; match : matches) {
      m[match[0]]; // create an entry for the winner.
      ++m[match[1]];      
    }
    vector&lt;vector&lt;int&gt;&gt; ans(2);
    for (const auto&amp; [player, loses] : m)
      if (loses &lt;= 1) ans[loses].push_back(player);      
    sort(begin(ans[0]), end(ans[0]));
    sort(begin(ans[1]), end(ans[1]));
    return ans;
  }  
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2225-find-players-with-zero-or-one-losses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2215. Find the Difference of Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2215-find-the-difference-of-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2215-find-the-difference-of-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 29 Mar 2022 02:44:45 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[distinct]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9584</guid>

					<description><![CDATA[Given two&#160;0-indexed&#160;integer arrays&#160;nums1&#160;and&#160;nums2, return&#160;a list&#160;answer&#160;of size&#160;2&#160;where: answer[0]&#160;is a list of all&#160;distinct&#160;integers in&#160;nums1&#160;which are&#160;not&#160;present in&#160;nums2. answer[1]&#160;is a list of all&#160;distinct&#160;integers in&#160;nums2&#160;which are&#160;not&#160;present in&#160;nums1. Note&#160;that the integers&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given two&nbsp;<strong>0-indexed</strong>&nbsp;integer arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>, return&nbsp;<em>a list</em>&nbsp;<code>answer</code>&nbsp;<em>of size</em>&nbsp;<code>2</code>&nbsp;<em>where:</em></p>



<ul class="wp-block-list"><li><code>answer[0]</code>&nbsp;<em>is a list of all&nbsp;<strong>distinct</strong>&nbsp;integers in</em>&nbsp;<code>nums1</code>&nbsp;<em>which are&nbsp;<strong>not</strong>&nbsp;present in</em>&nbsp;<code>nums2</code><em>.</em></li><li><code>answer[1]</code>&nbsp;<em>is a list of all&nbsp;<strong>distinct</strong>&nbsp;integers in</em>&nbsp;<code>nums2</code>&nbsp;<em>which are&nbsp;<strong>not</strong>&nbsp;present in</em>&nbsp;<code>nums1</code>.</li></ul>



<p><strong>Note</strong>&nbsp;that the integers in the lists may be returned in&nbsp;<strong>any</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4,6]
<strong>Output:</strong> [[1,3],[4,6]]
<strong>Explanation:
</strong>For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,2,3,3], nums2 = [1,1,2,2]
<strong>Output:</strong> [[3],[]]
<strong>Explanation:
</strong>For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li><li><code>-1000 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li></ul>



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



<p>Use two hashtables to store the unique numbers of array1 and array2 respectfully.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; findDifference(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    vector&lt;vector&lt;int&gt;&gt; ans(2);
    unordered_set&lt;int&gt; s1(begin(nums1), end(nums1));
    unordered_set&lt;int&gt; s2(begin(nums2), end(nums2));
    for (int x : s1)
      if (!s2.count(x)) ans[0].push_back(x);
    for (int x : s2)
      if (!s1.count(x)) ans[1].push_back(x);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2215-find-the-difference-of-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2206. Divide Array Into Equal Pairs</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2206-divide-array-into-equal-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2206-divide-array-into-equal-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Mar 2022 11:25:29 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[counter]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9577</guid>

					<description><![CDATA[You are given an integer array&#160;nums&#160;consisting of&#160;2 * n&#160;integers. You need to divide&#160;nums&#160;into&#160;n&#160;pairs such that: Each element belongs to&#160;exactly one&#160;pair. The elements present in a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;consisting of&nbsp;<code>2 * n</code>&nbsp;integers.</p>



<p>You need to divide&nbsp;<code>nums</code>&nbsp;into&nbsp;<code>n</code>&nbsp;pairs such that:</p>



<ul class="wp-block-list"><li>Each element belongs to&nbsp;<strong>exactly one</strong>&nbsp;pair.</li><li>The elements present in a pair are&nbsp;<strong>equal</strong>.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if nums can be divided into</em>&nbsp;<code>n</code>&nbsp;<em>pairs, otherwise return</em>&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,3,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> 
There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.
If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> 
There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.
</pre>



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



<ul class="wp-block-list"><li><code>nums.length == 2 * n</code></li><li><code>1 &lt;= n &lt;= 500</code></li><li><code>1 &lt;= nums[i] &lt;= 500</code></li></ul>



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



<p>Each number has to appear even numbers in order to be paired. Count the frequency of each number, return true if all of them are even numbers, return false otherwise. </p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool divideArray(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; m;
    for (int num : nums)
      ++m[num];
    return all_of(begin(m), end(m), [](const auto&amp; e) { return e.second % 2 == 0; });    
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2206-divide-array-into-equal-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2190. Most Frequent Number Following Key In an Array</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2190-most-frequent-number-following-key-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2190-most-frequent-number-following-key-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 12 Mar 2022 05:14:32 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9567</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums.&#160;You are also given an integer&#160;key, which is present in&#160;nums. For every unique integer&#160;target&#160;in&#160;nums,&#160;count&#160;the number of times&#160;target&#160;immediately follows an occurrence of&#160;key&#160;in&#160;nums.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>.<strong>&nbsp;</strong>You are also given an integer&nbsp;<code>key</code>, which is present in&nbsp;<code>nums</code>.</p>



<p>For every unique integer&nbsp;<code>target</code>&nbsp;in&nbsp;<code>nums</code>,&nbsp;<strong>count</strong>&nbsp;the number of times&nbsp;<code>target</code>&nbsp;immediately follows an occurrence of&nbsp;<code>key</code>&nbsp;in&nbsp;<code>nums</code>. In other words, count the number of indices&nbsp;<code>i</code>&nbsp;such that:</p>



<ul class="wp-block-list"><li><code>0 &lt;= i &lt;= nums.length - 2</code>,</li><li><code>nums[i] == key</code>&nbsp;and,</li><li><code>nums[i + 1] == target</code>.</li></ul>



<p>Return&nbsp;<em>the&nbsp;</em><code>target</code><em>&nbsp;with the&nbsp;<strong>maximum</strong>&nbsp;count</em>. The test cases will be generated such that the&nbsp;<code>target</code>&nbsp;with maximum count is unique.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,100,200,1,100], key = 1
<strong>Output:</strong> 100
<strong>Explanation:</strong> For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
No other integers follow an occurrence of key, so we return 100.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,2,2,2,3], key = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.
For target = 3, there is only one occurrence at index 4 which follows an occurrence of key.
target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.
</pre>



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



<ul class="wp-block-list"><li><code>2 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= nums[i] &lt;= 1000</code></li><li>The test cases will be generated such that the answer is unique.</li></ul>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int mostFrequent(vector&lt;int&gt;&amp; nums, int key) {
    const int n = nums.size();
    unordered_map&lt;int, int&gt; m;
    int count = 0;
    int ans = 0;
    for (int i = 1; i &lt; n; ++i) {
      if (nums[i - 1] == key &amp;&amp; ++m[nums[i]] &gt; count) {
        count = m[nums[i]];
        ans = nums[i];
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2190-most-frequent-number-following-key-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
