<?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/tag/hashtable/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 30 Mar 2025 15:17:54 +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 2349. Design a Number Container System</title>
		<link>https://zxi.mytechroad.com/blog/desgin/leetcode-2349-design-a-number-container-system/</link>
					<comments>https://zxi.mytechroad.com/blog/desgin/leetcode-2349-design-a-number-container-system/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Mar 2025 15:16:49 +0000</pubDate>
				<category><![CDATA[Desgin]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10244</guid>

					<description><![CDATA[两个hashtable，一个是index->number，另外一个是number -> {index}，使用treeset，自动排序。 时间复杂度：change O(logn)，find O(1)空间复杂度：O(n) [crayon-69af0c4be8fd7151606115/]]]></description>
										<content:encoded><![CDATA[
<p>两个hashtable，一个是index->number，另外一个是number -> {index}，使用treeset，自动排序。</p>



<p>时间复杂度：change O(logn)，find O(1)<br>空间复杂度：O(n)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class NumberContainers {
public:
  NumberContainers() {}
  
  void change(int index, int number) {
    if (m_.count(index)) {
      auto it = idx_.find(m_[index]);
      it-&gt;second.erase(index);
      if (it-&gt;second.empty())
        idx_.erase(it);
    }
    m_[index] = number;
    idx_[number].insert(index);
  }
  
  int find(int number) {
    auto it = idx_.find(number);
    if (it == end(idx_)) return -1;
    return *begin(it-&gt;second);
  }
private:
  unordered_map&lt;int, int&gt; m_; // index -&gt; num
  unordered_map&lt;int, set&lt;int&gt;&gt; idx_; // num -&gt; {index}
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/desgin/leetcode-2349-design-a-number-container-system/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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-69af0c4be9f73918742981/]]]></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-69af0c4bea420786134422/] 黄金 Precompute：在初始化的时候顺便求合，开两个数组一个存上下左右的，一个存对角线的。query的时候直接返回答案就可以了。时间复杂度和白银是一样的，但会快一些（省去了求合的过程）。 [crayon-69af0c4bea42f860973245/]]]></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 3408. Design Task Manager</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Mar 2025 03:45:03 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10229</guid>

					<description><![CDATA[pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId m_ 使用std::unordered_map，存储taskId -> pq_的迭代器 所有操作都是O(logn) [crayon-69af0c4bead6f017690761/]]]></description>
										<content:encoded><![CDATA[
<ol class="wp-block-list"><li>pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId</li><li>m_ 使用std::unordered_map，存储taskId -> pq_的迭代器</li></ol>



<p>所有操作都是O(logn)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class TaskManager {
public:
    TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks) {
      for (const auto&amp; task : tasks)
        add(task[0], task[1], task[2]);
    }

    void add(int userId, int taskId, int priority) {
      m_[taskId] = pq_.emplace(make_pair(priority, taskId), userId).first;
    }
    
    void edit(int taskId, int newPriority) {
      const int userId = m_[taskId]-&gt;second;
      rmv(taskId);
      add(userId, taskId, newPriority);
    }
    
    void rmv(int taskId) {
      auto it = m_.find(taskId);
      pq_.erase(it-&gt;second);
      m_.erase(it);
    }
    
    int execTop() {
      if (pq_.empty()) return -1;
      auto it = pq_.rbegin();
      const int userId = it-&gt;second;
      const int taskId = (it-&gt;first.second);
      rmv(taskId);
      return userId;
    }
  private:
    map&lt;std::pair&lt;int,int&gt;, int&gt; pq_; // (priority, taskId) -&gt; userId;
    unordered_map&lt;int, map&lt;std::pair&lt;int,int&gt;, int&gt;::iterator&gt; m_; // taskId -&gt; pq iterator
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/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 2829. Determine the Minimum Sum of a k-avoiding Array</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 16:40:51 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10085</guid>

					<description><![CDATA[You are given two integers,&#160;n&#160;and&#160;k. An array of&#160;distinct&#160;positive integers is called a&#160;k-avoiding&#160;array if there does not exist any pair of distinct elements that sum to&#160;k.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two integers,&nbsp;<code>n</code>&nbsp;and&nbsp;<code>k</code>.</p>



<p>An array of&nbsp;<strong>distinct</strong>&nbsp;positive integers is called a&nbsp;<strong>k-avoiding</strong>&nbsp;array if there does not exist any pair of distinct elements that sum to&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;possible sum of a k-avoiding array of length&nbsp;</em><code>n</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= n, k &lt;= 50</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Greedy + HashTable</strong></h2>



<p>Always choose the smallest possible number starting from 1.</p>



<p>Add all chosen numbers into a hashtable. For a new candidate i, check whether k &#8211; i is already in the hashtable.</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 minimumSum(int n, int k) {    
    int sum = 0;
    unordered_set&lt;int&gt; s;
    for (int i = 1; s.size() != n; ++i) {
      if (s.count(k - i)) continue;
      sum += i;
      s.insert(i);
    }
    return sum;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/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 2475. Number of Unequal Triplets in Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2475-number-of-unequal-triplets-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2475-number-of-unequal-triplets-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Nov 2022 23:45:24 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9886</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;array of positive integers&#160;nums. Find the number of triplets&#160;(i, j, k)&#160;that meet the following conditions: 0 &#60;= i &#60; j &#60; k&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array of positive integers&nbsp;<code>nums</code>. Find the number of triplets&nbsp;<code>(i, j, k)</code>&nbsp;that meet the following conditions:</p>



<ul class="wp-block-list"><li><code>0 &lt;= i &lt; j &lt; k &lt; nums.length</code></li><li><code>nums[i]</code>,&nbsp;<code>nums[j]</code>, and&nbsp;<code>nums[k]</code>&nbsp;are&nbsp;<strong>pairwise distinct</strong>.<ul><li>In other words,&nbsp;<code>nums[i] != nums[j]</code>,&nbsp;<code>nums[i] != nums[k]</code>, and&nbsp;<code>nums[j] != nums[k]</code>.</li></ul></li></ul>



<p>Return&nbsp;<em>the number of triplets that meet the conditions.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,4,2,4,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following triplets meet the conditions:
- (0, 2, 4) because 4 != 2 != 3
- (1, 2, 4) because 4 != 2 != 3
- (2, 3, 4) because 2 != 4 != 3
Since there are 3 triplets, we return 3.
Note that (2, 0, 4) is not a valid triplet because 2 &gt; 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1,1,1]
<strong>Output:</strong> 0
<strong>Explanation:</strong> No triplets meet the conditions so we return 0.
</pre>



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



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



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



<p>Enumerate i, j, k.</p>



<p>Time complexity: O(n<sup>3</sup>)<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 unequalTriplets(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    const int n = nums.size();
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        for (int k = j + 1; k &lt; n; ++k)
          if (nums[i] != nums[j] &amp;&amp; nums[j] != nums[k] &amp;&amp; nums[i] != nums[k])
            ++ans;
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2475-number-of-unequal-triplets-in-array/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 2405. Optimal Partition of String</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Sep 2022 15:05:35 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9807</guid>

					<description><![CDATA[Given a string&#160;s, partition the string into one or more&#160;substrings&#160;such that the characters in each substring are&#160;unique. That is, no letter appears in a single&#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 2405. Optimal Partition of String- 刷题找工作 EP401" width="500" height="281" src="https://www.youtube.com/embed/cKjQNbcSX0s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>s</code>, partition the string into one or more&nbsp;<strong>substrings</strong>&nbsp;such that the characters in each substring are&nbsp;<strong>unique</strong>. That is, no letter appears in a single substring more than&nbsp;<strong>once</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of substrings in such a partition.</em></p>



<p>Note that each character should belong to exactly one substring in a partition.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abacaba"
<strong>Output:</strong> 4
<strong>Explanation:</strong>
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ssssss"
<strong>Output:</strong> 6
<strong>Explanation:
</strong>The only valid partition is ("s","s","s","s","s","s").
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;consists of only English lowercase letters.</li></ul>



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



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



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



<p>Extend the cur string as long as possible unless a duplicate character occurs.</p>



<p>You can use hashtable / array or bitmask to mark whether a character has been seen so far.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int partitionString(string s) {
    unordered_set&lt;char&gt; m;
    int ans = 0;
    for (char c : s) {
      if (m.insert(c).second) continue;
      m.clear();
      m.insert(c);
      ++ans;
    }
    return ans + 1;
  }
};</pre>
</div></div>



<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 partitionString(string s) {
    vector&lt;int&gt; m(26);
    int ans = 0;
    for (char c : s) {
      if (++m[c - 'a'] == 1) continue;
      fill(begin(m), end(m), 0);
      m[c - 'a'] = 1;
      ++ans;
    }
    return ans + 1;
  }
};</pre>
</div></div>



<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 partitionString(string s) {
    int mask = 0;
    int ans = 0;
    for (char c : s) {
      if (mask &amp; (1 &lt;&lt; (c - 'a'))) {
        mask = 0;        
        ++ans;
      }
      mask |= 1 &lt;&lt; (c - 'a');
    }
    return ans + 1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/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>
	</channel>
</rss>
