<?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>query Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/query/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/query/</link>
	<description></description>
	<lastBuildDate>Wed, 15 Dec 2021 06:01:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>query Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/query/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 13 Dec 2021 02:49:45 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[range query]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9171</guid>

					<description><![CDATA[<p>Problem Solution 1: Range sum query Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/">花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2><strong><a href="http://2106. Maximum Fruits Harvested After at Most K Steps">Problem</a></strong></h2>



<p></p>



<h2><strong>Solution 1: Range sum query</strong></h2>



<p>Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of those fruits.</p>



<p>Given startPos and k, we have four options:<br>1. move i steps to the left<br>2. move i steps to the left and k &#8211; i steps to the right.<br>3. move i steps to the right<br>4. move i steps to the right and k &#8211; i steps to the left.</p>



<p>We enumerate i steps and calculate maximum range [l, r] covered by each option, and collect all the fruit in that range.</p>



<p>Time complexity: O(m + k)<br>Space complexity: O(m)<br>where m = max(max(pos), startPos)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    const int m = max(startPos, (*max_element(begin(fruits), end(fruits)))[0]);
    vector&lt;int&gt; sums(m + 2);   
    for (int i = 0, j = 0; i &lt;= m; ++i) {
      sums[i + 1] += sums[i];
      while (j &lt; fruits.size() &amp;&amp; fruits[j][0] == i)        
        sums[i + 1] += fruits[j++][1];      
    }    
    int ans = 0;
    for (int s = 0; s &lt;= k; ++s) {
      if (startPos - s &gt;= 0) {
        int l = startPos - s;
        int r = min(max(startPos, l + (k - s)), m);        
        ans = max(ans, sums[r + 1] - sums[l]);
      }
      if (startPos + s &lt;= m) {
        int r = startPos + s;
        int l = max(0, min(startPos, r - (k - s)));
        ans = max(ans, sums[r + 1] - sums[l]);
      }
    }             
    return ans;
  }
};</pre>
</div></div>



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



<p>Maintain a window [l, r] such that the steps to cover [l, r] from startPos is less or equal to k.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    auto steps = [&amp;](int l, int r) {
      if (r &lt;= startPos)
        return startPos - l;
      else if (l &gt;= startPos)
        return r - startPos;
      else
        return min(startPos + r - 2 * l, 2 * r - startPos - l);
    };
    int ans = 0;
    for (int r = 0, l = 0, cur = 0; r &lt; fruits.size(); ++r) {
      cur += fruits[r][1];
      while (l &lt;= r &amp;&amp; steps(fruits[l][0], fruits[r][0]) &gt; k)
        cur -= fruits[l++][1];      
      ans = max(ans, cur);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/">花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1707. Maximum XOR With an Element From Array</title>
		<link>https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/</link>
					<comments>https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 21:54:20 +0000</pubDate>
				<category><![CDATA[Trie]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[trie]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7871</guid>

					<description><![CDATA[<p>You are given an array&#160;nums&#160;consisting of non-negative integers. You are also given a&#160;queries&#160;array, where&#160;queries[i] = [xi, mi]. The answer to the&#160;ith&#160;query is the maximum bitwise&#160;XOR&#160;value&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/">花花酱 LeetCode 1707. Maximum XOR With an Element From Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1707. Maximum XOR With an Element From Array - 刷题找工作 EP377" width="500" height="281" src="https://www.youtube.com/embed/k0e9tM7gU3E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>nums</code>&nbsp;consisting of non-negative integers. You are also given a&nbsp;<code>queries</code>&nbsp;array, where&nbsp;<code>queries[i] = [x<sub>i</sub>, m<sub>i</sub>]</code>.</p>



<p>The answer to the&nbsp;<code>i<sup>th</sup></code>&nbsp;query is the maximum bitwise&nbsp;<code>XOR</code>&nbsp;value of&nbsp;<code>x<sub>i</sub></code>&nbsp;and any element of&nbsp;<code>nums</code>&nbsp;that does not exceed&nbsp;<code>m<sub>i</sub></code>. In other words, the answer is&nbsp;<code>max(nums[j] XOR x<sub>i</sub>)</code>&nbsp;for all&nbsp;<code>j</code>&nbsp;such that&nbsp;<code>nums[j] &lt;= m<sub>i</sub></code>. If all elements in&nbsp;<code>nums</code>&nbsp;are larger than&nbsp;<code>m<sub>i</sub></code>, then the answer is&nbsp;<code>-1</code>.</p>



<p>Return&nbsp;<em>an integer array&nbsp;</em><code>answer</code><em>&nbsp;where&nbsp;</em><code>answer.length == queries.length</code><em>&nbsp;and&nbsp;</em><code>answer[i]</code><em>&nbsp;is the answer to the&nbsp;</em><code>i<sup>th</sup></code><em>&nbsp;query.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
<strong>Output:</strong> [3,3,7]
<strong>Explanation:</strong>
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
</pre>



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



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



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



<ul><li><code>1 &lt;= nums.length, queries.length &lt;= 10<sup>5</sup></code></li><li><code>queries[i].length == 2</code></li><li><code>0 &lt;= nums[j], x<sub>i</sub>, m<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Trie on the fly</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-1.png" alt="" class="wp-image-7874" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-2.png" alt="" class="wp-image-7875" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-3.png" alt="" class="wp-image-7876" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1707-ep377-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Similar idea to <a href="https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/">https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/</a></p>



<p>We can build the trie on the fly by sorting nums in ascending order and queries by its limit, insert nums into the trie up the limit.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Trie {
public:
  Trie(): children{nullptr, nullptr} {}  
  Trie* children[2];
};
class Solution {
public:
  vector&lt;int&gt; maximizeXor(vector&lt;int&gt;&amp; nums, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    const int n = nums.size();
    sort(begin(nums), end(nums));    
    
    const int Q = queries.size();
    for (int i = 0; i &lt; Q; ++i)
      queries[i].push_back(i);
    sort(begin(queries), end(queries), [](const auto&amp; q1, const auto&amp; q2) {
      return q1[1] &lt; q2[1];
    });
    
    Trie root;    
    auto insert = [&amp;](int num) {
      Trie* node = &amp;root; 
      for (int i = 31; i &gt;= 0; --i) {
        int bit = (num &gt;&gt; i) &amp; 1;
        if (!node-&gt;children[bit])
          node-&gt;children[bit] = new Trie();
        node = node-&gt;children[bit];
      }
    };
        
    auto query = [&amp;](int num) {
      Trie* node = &amp;root;
      int sum = 0;
      for (int i = 31; i &gt;= 0; --i) {
        if (!node) return -1;
        int bit = (num &gt;&gt; i) &amp; 1;
        if (node-&gt;children[1 - bit]) {
          sum |= (1 &lt;&lt; i);
          node = node-&gt;children[1 - bit];
        } else {
          node = node-&gt;children[bit];
        }
      }
      return sum;
    };
    
    vector&lt;int&gt; ans(Q);
    int i = 0;
    for (const auto&amp; q : queries) {
      while (i &lt; n &amp;&amp; nums[i] &lt;= q[1]) insert(nums[i++]);
      ans[q[2]] = query(q[0]);
    }  
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/">花花酱 LeetCode 1707. Maximum XOR With an Element From Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1476. Subrectangle Queries</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-1476-subrectangle-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-1476-subrectangle-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Jun 2020 03:41:08 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[update]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6909</guid>

					<description><![CDATA[<p>Implement the class&#160;SubrectangleQueries&#160;which receives a&#160;rows x cols&#160;rectangle as a matrix of integers in the constructor and supports two methods: 1.&#160;updateSubrectangle(int row1, int col1, int row2,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1476-subrectangle-queries/">花花酱 LeetCode 1476. Subrectangle Queries</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Implement the class&nbsp;<code>SubrectangleQueries</code>&nbsp;which receives a&nbsp;<code>rows x cols</code>&nbsp;rectangle as a matrix of integers in the constructor and supports two methods:</p>



<p>1.<code>&nbsp;updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)</code></p>



<ul><li>Updates all values with&nbsp;<code>newValue</code>&nbsp;in the subrectangle whose upper left coordinate is&nbsp;<code>(row1,col1)</code>&nbsp;and bottom right coordinate is&nbsp;<code>(row2,col2)</code>.</li></ul>



<p>2.<code>&nbsp;getValue(int row, int col)</code></p>



<ul><li>Returns the current value of the coordinate&nbsp;<code>(row,col)</code>&nbsp;from&nbsp;the rectangle.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
<strong>Output</strong>
</pre>


<p>[null,1,null,5,5,null,10,5]</p>



<p><strong>Explanation</strong>
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);  
// The initial rectangle (4&#215;3) looks like:
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
subrectangleQueries.getValue(0, 2); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 5 5 5 
subrectangleQueries.getValue(0, 2); // return 5
subrectangleQueries.getValue(3, 1); // return 5
subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
// After this update the rectangle looks like:
// 5   5   5
// 5   5   5
// 5   5   5
// 10  10  10 
subrectangleQueries.getValue(3, 1); // return 10
subrectangleQueries.getValue(0, 2); // return 5
</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]
[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]
<strong>Output</strong>
</pre>


<p>[null,1,null,100,100,null,20]</p>



<p><strong>Explanation</strong>
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);
subrectangleQueries.getValue(0, 0); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);
subrectangleQueries.getValue(0, 0); // return 100
subrectangleQueries.getValue(2, 2); // return 100
subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);
subrectangleQueries.getValue(2, 2); // return 20
</p>



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



<ul><li>There will be at most&nbsp;<code>500</code>&nbsp;operations considering both methods:&nbsp;<code>updateSubrectangle</code>&nbsp;and&nbsp;<code>getValue</code>.</li><li><code>1 &lt;= rows, cols &lt;= 100</code></li><li><code>rows ==&nbsp;rectangle.length</code></li><li><code>cols == rectangle[i].length</code></li><li><code>0 &lt;= row1 &lt;= row2 &lt; rows</code></li><li><code>0 &lt;= col1 &lt;= col2 &lt; cols</code></li><li><code>1 &lt;= newValue, rectangle[i][j] &lt;= 10^9</code></li><li><code>0 &lt;= row &lt; rows</code></li><li><code>0 &lt;= col &lt; cols</code></li></ul>



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



<p>Update the matrix values.</p>



<p>Time complexity: <br>Update: O(m*n), where m*n is the area of the sub-rectangle.<br>Query: O(1)</p>



<p>Space complexity: O(rows*cols) </p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class SubrectangleQueries {
public:
  SubrectangleQueries(vector&lt;vector&lt;int&gt;&gt;&amp; rectangle): 
    m_(rectangle) {}

  void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
    for (int i = row1; i &lt;= row2; ++i)
      for (int j = col1; j &lt;= col2; ++j)
        m_[i][j] = newValue;
  }

  int getValue(int row, int col) {
    return m_[row][col];
  }
private:
  vector&lt;vector&lt;int&gt;&gt; m_;
};</pre>
</div></div>



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



<p>For each update remember the region and value.</p>



<p>For each query, find the newest updates that covers the query point. If not found, return the original value in the matrix.</p>



<p>Time complexity:<br>Update: O(1)<br>Query: O(|U|), where |U| is the number of updates so far.</p>



<p>Space complexity: O(|U|)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class SubrectangleQueries {
public:
  SubrectangleQueries(vector&lt;vector&lt;int&gt;&gt;&amp; rectangle): 
    m_(rectangle) {}

  void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
    updates_.push_front({row1, col1, row2, col2, newValue});
  }

  int getValue(int row, int col) {
    for (const auto&amp; u : updates_)
      if (row &gt;= u[0] &amp;&amp; row &lt;= u[2] &amp;&amp; col &gt;= u[1] &amp;&amp; col &lt;= u[3])
        return u[4];
    return m_[row][col];
  }
private:
  const vector&lt;vector&lt;int&gt;&gt;&amp; m_;
  deque&lt;vector&lt;int&gt;&gt; updates_;  
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1476-subrectangle-queries/">花花酱 LeetCode 1476. Subrectangle Queries</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/geometry/leetcode-1476-subrectangle-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1314. Matrix Block Sum</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1314-matrix-block-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1314-matrix-block-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 11 Jan 2020 18:28:35 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(mn)]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[range sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6071</guid>

					<description><![CDATA[<p>Given a&#160;m * n&#160;matrix&#160;mat&#160;and an integer&#160;K, return a matrix&#160;answer&#160;where each&#160;answer[i][j]&#160;is the sum of all elements&#160;mat[r][c]&#160;for&#160;i - K &#60;= r &#60;= i + K, j -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1314-matrix-block-sum/">花花酱 LeetCode 1314. Matrix Block Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<code>m * n</code>&nbsp;matrix&nbsp;<code>mat</code>&nbsp;and an integer&nbsp;<code>K</code>, return a matrix&nbsp;<code>answer</code>&nbsp;where each&nbsp;<code>answer[i][j]</code>&nbsp;is the sum of all elements&nbsp;<code>mat[r][c]</code>&nbsp;for&nbsp;<code>i - K &lt;= r &lt;= i + K, j - K &lt;= c &lt;= j + K</code>, and&nbsp;<code>(r, c)</code>&nbsp;is a valid position in the matrix.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
<strong>Output:</strong> [[12,21,16],[27,45,33],[24,39,28]]
</pre>



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



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



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



<ul><li><code>m ==&nbsp;mat.length</code></li><li><code>n ==&nbsp;mat[i].length</code></li><li><code>1 &lt;= m, n, K &lt;= 100</code></li><li><code>1 &lt;= mat[i][j] &lt;= 100</code></li></ul>



<h2><strong>Solution: 2D range query</strong></h2>



<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="crayon-plain-tag">// Author: Huahua, 20 ms
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; matrixBlockSum(vector&lt;vector&lt;int&gt;&gt;&amp; mat, int K) {
    const int n = mat.size();
    const int m = mat[0].size();
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(m + 1));
    for (int y = 1; y &lt;= n; ++y)
      for (int x = 1; x &lt;= m; ++x)
        dp[y][x] = dp[y - 1][x] + dp[y][x - 1] + mat[y - 1][x - 1] - dp[y - 1][x - 1];
    auto ans = mat;
    for (int y = 1; y &lt;= n; ++y)
      for (int x = 1; x &lt;= m; ++x) {
        int x1 = max(1, x - K);
        int x2 = min(m, x + K);
        int y1 = max(1, y - K);
        int y2 = min(n, y + K);
        ans[y - 1][x - 1] = dp[y2][x2] - dp[y1 - 1][x2] - dp[y2][x1 - 1] + dp[y1 - 1][x1 - 1];
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1314-matrix-block-sum/">花花酱 LeetCode 1314. Matrix Block Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1314-matrix-block-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 715. Range Module</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Oct 2017 23:29:45 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Geometry]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[range]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=679</guid>

					<description><![CDATA[<p>Problem: A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/">花花酱 LeetCode 715. Range Module</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/pcpB9ux3RrQ?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.</p>
<p>&nbsp;</p>
<ul>
<li><code>addRange(int left, int right)</code> Adds the half-open interval <code>[left, right)</code>, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval <code>[left, right)</code> that are not already tracked.</li>
<li><code>queryRange(int left, int right)</code> Returns true if and only if every real number in the interval <code>[left, right)</code> is currently being tracked.</li>
<li><code>removeRange(int left, int right)</code> Stops tracking every real number currently being tracked in the interval <code>[left, right)</code>.</li>
</ul>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">addRange(10, 20): null
removeRange(14, 16): null
queryRange(10, 14): true (Every number in [10, 14) is being tracked)
queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)
queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)</pre><p><b>Note:</b></p>
<ul>
<li>A half open interval <code>[left, right)</code> denotes all real numbers <code>left &lt;= x &lt; right</code>.</li>
<li><code>0 &lt; left &lt; right &lt; 10^9</code> in all calls to <code>addRange, queryRange, removeRange</code>.</li>
<li>The total number of calls to <code>addRange</code> in a single test case is at most <code>1000</code>.</li>
<li>The total number of calls to <code>queryRange</code> in a single test case is at most <code>5000</code>.</li>
<li>The total number of calls to <code>removeRange</code> in a single test case is at most <code>1000</code>.</li>
</ul>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>map / ordered ranges</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1.png"><img class="alignnone size-full wp-image-689" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a>  <a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2.png"><img class="alignnone size-full wp-image-688" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3.png"><img class="alignnone size-full wp-image-687" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-3-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4.png"><img class="alignnone size-full wp-image-686" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/715-ep96-4-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><strong>Solution:</strong></p>
<p>C++ / vector</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 276 ms
class RangeModule {
public:
    RangeModule() {}
    
    void addRange(int left, int right) {
        vector&lt;pair&lt;int, int&gt;&gt; new_ranges;
        bool inserted = false;
        for (const auto&amp; kv : ranges_) {            
            if (kv.first &gt; right &amp;&amp; !inserted) {
                new_ranges.emplace_back(left, right);
                inserted = true;
            }
            if (kv.second &lt; left || kv.first &gt; right) { 
                new_ranges.push_back(kv);
            } else {
                left = min(left, kv.first);
                right = max(right, kv.second);
            }
        }       
        if (!inserted) new_ranges.emplace_back(left, right);       
        ranges_.swap(new_ranges);
    }
    
    bool queryRange(int left, int right) {
        const int n = ranges_.size();
        int l = 0;
        int r = n - 1;
        // Binary search
        while (l &lt;= r) {
            int m = l + (r - l) / 2;
            if (ranges_[m].second &lt; left)
                l = m + 1;
            else if (ranges_[m].first &gt; right)
                r = m - 1;
            else
                return ranges_[m].first &lt;= left &amp;&amp; ranges_[m].second &gt;= right;
        }
        return false;
    }
    
    void removeRange(int left, int right) {
        vector&lt;pair&lt;int, int&gt;&gt; new_ranges;        
        for (const auto&amp; kv : ranges_) {
            if (kv.second &lt;= left || kv.first &gt;= right) {
                new_ranges.push_back(kv);
            } else {
                if (kv.first &lt; left)
                    new_ranges.emplace_back(kv.first, left);
                if (kv.second &gt; right)
                    new_ranges.emplace_back(right, kv.second);
            }        
        }
        ranges_.swap(new_ranges);
    }
    vector&lt;pair&lt;int, int&gt;&gt; ranges_;
};</pre><p>C++ / map</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 199 ms
class RangeModule {
public:
    RangeModule() {}
    
    void addRange(int left, int right) {
        IT l, r;
        getOverlapRanges(left, right, l, r);
        // At least one range overlapping with [left, right)
        if (l != r) {
            // Merge intervals into [left, right)
            auto last = r; --last;
            left = min(left, l-&gt;first);            
            right = max(right, last-&gt;second);
            // Remove all overlapped ranges
            ranges_.erase(l, r);
        }
        // Add a new/merged range
        ranges_[left] = right;
    }
    
    bool queryRange(int left, int right) {
        IT l, r;
        getOverlapRanges(left, right, l, r);
        // No overlapping range
        if (l == r) return false;
        return l-&gt;first &lt;= left &amp;&amp; l-&gt;second &gt;= right;
    }
    
    void removeRange(int left, int right) {
        IT l, r;
        getOverlapRanges(left, right, l, r);
        // No overlapping range
        if (l == r) return;
        auto last = r; --last;
        int start = min(left, l-&gt;first);        
        int end = max(right, last-&gt;second);
        // Delete overlapping ranges        
        ranges_.erase(l, r);
        if (start &lt; left) ranges_[start] = left;
        if (end &gt; right) ranges_[right] = end;
    }
private:
    typedef map&lt;int, int&gt;::iterator IT;
    map&lt;int, int&gt; ranges_;
    void getOverlapRanges(int left, int right, IT&amp; l, IT&amp; r) {
        l = ranges_.upper_bound(left);
        r = ranges_.upper_bound(right);
        if (l != ranges_.begin())
            if ((--l)-&gt;second &lt; left) l++;
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">[解题报告] LeetCode 57. Insert Interval</a></li>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">[解题报告] LeetCode 56. Merge Intervals</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/">花花酱 LeetCode 715. Range Module</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
