<?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>deque Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/deque/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/deque/</link>
	<description></description>
	<lastBuildDate>Sat, 03 Apr 2021 18:52:27 +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>deque Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/deque/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1813. Sentence Similarity III</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1813-sentence-similarity-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1813-sentence-similarity-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Apr 2021 18:51:07 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8300</guid>

					<description><![CDATA[<p>A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example,&#160;"Hello World",&#160;"HELLO",&#160;"hello world hello&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1813-sentence-similarity-iii/">花花酱 LeetCode 1813. Sentence Similarity III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example,&nbsp;<code>"Hello World"</code>,&nbsp;<code>"HELLO"</code>,&nbsp;<code>"hello world hello world"</code>&nbsp;are all sentences. Words consist of&nbsp;<strong>only</strong>&nbsp;uppercase and lowercase English letters.</p>



<p>Two sentences&nbsp;<code>sentence1</code>&nbsp;and&nbsp;<code>sentence2</code>&nbsp;are&nbsp;<strong>similar</strong>&nbsp;if it is possible to insert an arbitrary sentence&nbsp;<strong>(possibly empty)</strong>&nbsp;inside one of these sentences such that the two sentences become equal. For example,&nbsp;<code>sentence1 = "Hello my name is Jane"</code>&nbsp;and&nbsp;<code>sentence2 = "Hello Jane"</code>&nbsp;can be made equal by inserting&nbsp;<code>"my name is"</code>&nbsp;between&nbsp;<code>"Hello"</code>&nbsp;and&nbsp;<code>"Jane"</code>&nbsp;in&nbsp;<code>sentence2</code>.</p>



<p>Given two sentences&nbsp;<code>sentence1</code>&nbsp;and&nbsp;<code>sentence2</code>, return&nbsp;<code>true</code>&nbsp;<em>if&nbsp;</em><code>sentence1</code>&nbsp;<em>and&nbsp;</em><code>sentence2</code>&nbsp;<em>are similar.</em>&nbsp;Otherwise, return&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence1 = "My name is Haley", sentence2 = "My Haley"
<strong>Output:</strong> true
<strong>Explanation:</strong> sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence1 = "of", sentence2 = "A lot of words"
<strong>Output:</strong> false
<strong>Explanation: </strong>No single sentence can be inserted inside one of the sentences to make it equal to the other.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence1 = "Eating right now", sentence2 = "Eating"
<strong>Output:</strong> true
<strong>Explanation:</strong> sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> sentence1 = "Luky", sentence2 = "Lucccky"
<strong>Output:</strong> false
</pre>



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



<ul><li><code>1 &lt;= sentence1.length, sentence2.length &lt;= 100</code></li><li><code>sentence1</code>&nbsp;and&nbsp;<code>sentence2</code>&nbsp;consist of lowercase and uppercase English letters and spaces.</li><li>The words in&nbsp;<code>sentence1</code>&nbsp;and&nbsp;<code>sentence2</code>&nbsp;are separated by a single space.</li></ul>



<h2><strong>Solution: Dequeue / Common Prefix + Suffix</strong></h2>



<p>Break sequences to words, store them in two deques. Pop the common prefix and suffix. At least one of the deque should be empty.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool areSentencesSimilar(string s1, string s2) {    
    auto getWords = [](const string&amp; s) {
      stringstream ss(s);
      deque&lt;string&gt; words;
      while (ss) {
        words.emplace_back(&quot;&quot;);
        ss &gt;&gt; words.back();
      }
      return words;
    };
    deque&lt;string&gt; w1 = getWords(s1), w2 = getWords(s2);
    while (w1.size() &amp;&amp; w2.size() &amp;&amp; w1.front() == w2.front())
      w1.pop_front(), w2.pop_front();
    while (w1.size() &amp;&amp; w2.size() &amp;&amp; w1.back() == w2.back())
      w1.pop_back(), w2.pop_back();
    return w1.empty() || w2.empty();
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def areSentencesSimilar(self, s1: str, s2: str) -&gt; bool:
    w1 = deque(s1.split())
    w2 = deque(s2.split())
    while w1 and w2 and w1[0] == w2[0]:
      w1.popleft(), w2.popleft()
    while w1 and w2 and w1[-1] == w2[-1]:
      w1.pop(), w2.pop()
    return len(w1) * len(w2) == 0</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1813-sentence-similarity-iii/">花花酱 LeetCode 1813. Sentence Similarity III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1813-sentence-similarity-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1585. Check If String Is Transformable With Substring Sort Operations</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1585-check-if-string-is-transformable-with-substring-sort-operations/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1585-check-if-string-is-transformable-with-substring-sort-operations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Sep 2020 08:39:31 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[transform]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7374</guid>

					<description><![CDATA[<p>Given two strings&#160;s&#160;and&#160;t, you want to transform string&#160;s&#160;into string&#160;t&#160;using the following&#160;operation any number of times: Choose a&#160;non-empty&#160;substring in&#160;s&#160;and sort it in-place&#160;so the characters are in&#160;ascending&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1585-check-if-string-is-transformable-with-substring-sort-operations/">花花酱 LeetCode 1585. Check If String Is Transformable With Substring Sort Operations</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 1585. Check If String Is Transformable With Substring Sort Operations - 刷题找工作 EP356" width="500" height="281" src="https://www.youtube.com/embed/Pkd3FampKBk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given two strings&nbsp;<code>s</code>&nbsp;and&nbsp;<code>t</code>, you want to transform string&nbsp;<code>s</code>&nbsp;into string&nbsp;<code>t</code>&nbsp;using the following&nbsp;operation any number of times:</p>



<ul><li>Choose a&nbsp;<strong>non-empty</strong>&nbsp;substring in&nbsp;<code>s</code>&nbsp;and sort it in-place&nbsp;so the characters are in&nbsp;<strong>ascending order</strong>.</li></ul>



<p>For example, applying the operation on the underlined substring in&nbsp;<code>"14234"</code>&nbsp;results in&nbsp;<code>"12344"</code>.</p>



<p>Return&nbsp;<code>true</code>&nbsp;if&nbsp;<em>it is possible to transform string&nbsp;<code>s</code>&nbsp;into string&nbsp;<code>t</code></em>. Otherwise,&nbsp;return&nbsp;<code>false</code>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "84532", t = "34852"
<strong>Output:</strong> true
<strong>Explanation:</strong> You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -&gt; "84352"
"84352" (from index 0 to 2) -&gt; "34852"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "34521", t = "23415"
<strong>Output:</strong> true
<strong>Explanation:</strong> You can transform s into t using the following sort operations:
"34521" -&gt; "23451"
"23451" -&gt; "23415"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "12345", t = "12435"
<strong>Output:</strong> false
</pre>



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



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



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



<ul><li><code>s.length == t.length</code></li><li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;and&nbsp;<code>t</code>&nbsp;only contain digits from&nbsp;<code>'0'</code>&nbsp;to&nbsp;<code>'9'</code>.</li></ul>



<p><strong>Solution: Queue</strong></p>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-1.png" alt="" class="wp-image-7379" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-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/09/1585-ep356-2.png" alt="" class="wp-image-7380" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/09/1585-ep356-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>We can move a smaller digit from right to left by sorting two adjacent digits. <br>e.g. 1857<strong>2</strong> -&gt; 185<strong>2</strong>7 -&gt; 18<strong>2</strong>57 -&gt; 1<strong>2</strong>857, but we can not move a larger to the left of a smaller one.</p>



<p>Thus, for each digit in the target string, we find the first occurrence of it in s, and try to move it to the front by checking if there is any smaller one in front of it.</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  bool isTransformable(string s, string t) {
    vector&lt;deque&lt;int&gt;&gt; idx(10);
    for (int i = 0; i &lt; s.length(); ++i)
      idx[s[i] - '0'].push_back(i);
    for (char c : t) {
      const int d  = c - '0';
      if (idx[d].empty()) return false;
      for (int i = 0; i &lt; d; ++i)
        if (!idx[i].empty() &amp;&amp; idx[i].front() &lt; idx[d].front())
          return false;
      idx[d].pop_front();      
    }
    return true;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def isTransformable(self, s: str, t: str) -&gt; bool:
    idx = defaultdict(deque)
    for i, c in enumerate(s):
      idx[int(c)].append(i)
    for c in t:
      d = int(c)
      if not idx[d]: return False
      for i in range(d):
        if idx[i] and idx[i][0] &lt; idx[d][0]: return False
      idx[d].popleft()
    return True</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1585-check-if-string-is-transformable-with-substring-sort-operations/">花花酱 LeetCode 1585. Check If String Is Transformable With Substring Sort Operations</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1585-check-if-string-is-transformable-with-substring-sort-operations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 919. Complete Binary Tree Inserter</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-919-complete-binary-tree-inserter/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-919-complete-binary-tree-inserter/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Oct 2018 04:29:53 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[inserter]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4163</guid>

					<description><![CDATA[<p>Problem A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-919-complete-binary-tree-inserter/">花花酱 LeetCode 919. Complete Binary Tree Inserter</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>A <em>complete</em> binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.</p>
<p>Write a data structure <code>CBTInserter</code> that is initialized with a complete binary tree and supports the following operations:</p>
<ul>
<li><code>CBTInserter(TreeNode root)</code> initializes the data structure on a given tree with head node <code>root</code>;</li>
<li><code>CBTInserter.insert(int v)</code> will insert a <code>TreeNode</code> into the tree with value <code>node.val = v</code> so that the tree remains complete, <strong>and returns the value of the parent of the inserted <code>TreeNode</code></strong>;</li>
<li><code>CBTInserter.get_root()</code> will return the head node of the tree.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>inputs = <span id="example-input-1-1">["CBTInserter","insert","get_root"]</span>, inputs = <span id="example-input-1-2">[[[1]],[2],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,1,[1,2]]</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>inputs = <span id="example-input-2-1">["CBTInserter","insert","insert","get_root"]</span>, inputs = <span id="example-input-2-2">[[[1,2,3,4,5,6]],[7],[8],[]]</span>
<strong>Output: </strong><span id="example-output-2">[null,3,4,[1,2,3,4,5,6,7,8]]</span></pre>
<p><strong>Note:</strong></p>
<ol>
<li>The initial given tree is complete and contains between <code>1</code> and <code>1000</code> nodes.</li>
<li><code>CBTInserter.insert</code> is called at most <code>10000</code> times per test case.</li>
<li>Every value of a given or inserted node is between <code>0</code> and <code>5000</code>.</li>
</ol>
<h1><strong>Solution 2: Deque</strong></h1>
<p>Using a deck to keep track of insertable nodes (potential parents) in order.</p>
<p>Time complexity: O(1) / O(n) first call</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class CBTInserter {
public:
  CBTInserter(TreeNode* root): root_(root), d_({root}) {}

  int insert(int v) {    
    while (!d_.empty()) {
      TreeNode* r = d_.front();
      if (r-&gt;left &amp;&amp; r-&gt;right) {
        d_.push_back(r-&gt;left);
        d_.push_back(r-&gt;right);
        d_.pop_front();
      } else if (r-&gt;left) {
        r-&gt;right = new TreeNode(v);
        return r-&gt;val;
      } else {
        r-&gt;left = new TreeNode(v);        
        return r-&gt;val;
      }
    }
  }

  TreeNode* get_root() { return root_; }
private:
  std::deque&lt;TreeNode*&gt; d_;
  TreeNode* root_;
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-919-complete-binary-tree-inserter/">花花酱 LeetCode 919. Complete Binary Tree Inserter</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/tree/leetcode-919-complete-binary-tree-inserter/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 641. Design Circular Deque</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-641-design-circular-deque/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-641-design-circular-deque/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Jul 2018 03:58:04 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[circular]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[desgin]]></category>
		<category><![CDATA[easy]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3147</guid>

					<description><![CDATA[<p>Problem Design your implementation of the circular double-ended queue (deque). Your implementation should support following operations: MyCircularDeque(k): Constructor, set the size of the deque to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-641-design-circular-deque/">花花酱 LeetCode 641. Design Circular Deque</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Design your implementation of the circular double-ended queue (deque).<br />
Your implementation should support following operations:</p>
<ul>
<li>MyCircularDeque(k): Constructor, set the size of the deque to be k.</li>
<li>insertFront(): Adds an item at the front of Deque. Return true if the operation is successful.</li>
<li>insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.</li>
<li>deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.</li>
<li>deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.</li>
<li>getFront(): Gets the front item from the Deque. If the deque is empty, return -1.</li>
<li>getRear(): Gets the last item from Deque. If the deque is empty, return -1.</li>
<li>isEmpty(): Checks whether Deque is empty or not.</li>
<li>isFull(): Checks whether Deque is full or not.</li>
</ul>
<p><strong>Example:</strong></p>
<pre class="crayon:false ">MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3
circularDeque.insertLast(1);			// return true
circularDeque.insertLast(2);			// return true
circularDeque.insertFront(3);			// return true
circularDeque.insertFront(4);			// return false, the queue is full
circularDeque.getRear();  				// return 32
circularDeque.isFull();				// return true
circularDeque.deleteLast();			// return true
circularDeque.insertFront(4);			// return true
circularDeque.getFront();				// return 4
</pre>
<p><strong>Note:</strong></p>
<ul>
<li>All values will be in the range of [1, 1000].</li>
<li>The number of operations will be in the range of [1, 1000].</li>
<li>Please do not use the built-in Deque library.</li>
</ul>
<h1><strong>Solution</strong></h1>
<p>Using head and tail to pointer to the head and the tail in the circular buffer.</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 20 ms
class MyCircularDeque {
public:
  /** Initialize your data structure here. Set the size of the deque to be k. */
  MyCircularDeque(int k): k_(k), q_(k), head_(1), tail_(-1), size_(0) {}

  /** Adds an item at the front of Deque. Return true if the operation is successful. */
  bool insertFront(int value) {
    if (isFull()) return false;
    head_ = (head_ - 1 + k_) % k_;
    q_[head_] = value;
    if (size_ == 0) tail_ = head_;
    ++size_;
    return true;
  }

  /** Adds an item at the rear of Deque. Return true if the operation is successful. */
  bool insertLast(int value) {
    if (isFull()) return false;
    tail_ = (tail_ + 1 + k_) % k_;
    q_[tail_] = value;
    if (size_ == 0) head_ = tail_;
    ++size_;
    return true;  
  }

  /** Deletes an item from the front of Deque. Return true if the operation is successful. */
  bool deleteFront() {
    if (isEmpty()) return false;
    head_ = (head_ + 1 + k_) % k_;
    --size_;
    return true;
  }

  /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
  bool deleteLast() {
    if (isEmpty()) return false;
    tail_ = (tail_ - 1 + k_) % k_;
    --size_;
    return true;
  }

  /** Get the front item from the deque. */
  int getFront() {
    if (isEmpty()) return -1;
    return q_[head_];
  }

  /** Get the last item from the deque. */
  int getRear() {
    if (isEmpty()) return -1;
    return q_[tail_];
  }

  /** Checks whether the circular deque is empty or not. */
  bool isEmpty() {
    return size_ == 0;
  }

  /** Checks whether the circular deque is full or not. */
  bool isFull() {
    return size_ == k_;
  }
private:
  const int k_;
  int head_;
  int tail_;
  int size_;
  vector&lt;int&gt; q_;
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/uncategorized/leetcode-622-design-circular-queue/">花花酱 LeetCode 622. Design Circular Queue</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-641-design-circular-deque/">花花酱 LeetCode 641. Design Circular Deque</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-641-design-circular-deque/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 622. Design Circular Queue</title>
		<link>https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/</link>
					<comments>https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 05:37:46 +0000</pubDate>
				<category><![CDATA[Desgin]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3104</guid>

					<description><![CDATA[<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/">花花酱 LeetCode 622. Design Circular Queue</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>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called &#8220;Ring Buffer&#8221;.</p>



<p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p>



<p>Your implementation should support following operations:</p>



<ul><li><code>MyCircularQueue(k)</code>: Constructor, set the size of the queue to be k.</li><li><code>Front</code>: Get the front item from the queue. If the queue is empty, return -1.</li><li><code>Rear</code>: Get the last item from the queue. If the queue is empty, return -1.</li><li><code>enQueue(value)</code>: Insert an element into the circular queue. Return true if the operation is successful.</li><li><code>deQueue()</code>: Delete an element from the circular queue. Return true if the operation is successful.</li><li><code>isEmpty()</code>: Checks whether the circular queue is empty or not.</li><li><code>isFull()</code>: Checks whether the circular queue is full or not.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false">MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
circularQueue.enQueue(1); &nbsp;// return true
circularQueue.enQueue(2); &nbsp;// return true
circularQueue.enQueue(3); &nbsp;// return true
circularQueue.enQueue(4); &nbsp;// return false, the queue is full
circularQueue.Rear(); &nbsp;// return 3
circularQueue.isFull(); &nbsp;// return true
circularQueue.deQueue(); &nbsp;// return true
circularQueue.enQueue(4); &nbsp;// return true
circularQueue.Rear(); &nbsp;// return 4
</pre>



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



<ul><li>All values will be in the range of [0, 1000].</li><li>The number of operations will be in the range of&nbsp;[1, 1000].</li><li>Please do not use the built-in Queue library.</li></ul>



<h2><strong>Solution: Simulate with an array</strong></h2>



<p>We need a fixed length array, and the head location as well as the size of the current queue.</p>



<p>We can use q[head] to access the front, and q[(head + size &#8211; 1) % k] to access the rear.</p>



<p>Time complexity: O(1) for all the operations.<br>Space complexity: O(k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class MyCircularQueue {
public:
  MyCircularQueue(int k): q_(k) {}
  
  bool enQueue(int value) {
    if (isFull()) return false;
    q_[(head_ + size_) % q_.size()] = value;    
    ++size_;
    return true;
  }
  
  bool deQueue() {
    if (isEmpty()) return false;
    head_ = (head_ + 1) % q_.size();
    --size_;
    return true;
  }

  int Front() { return isEmpty() ? -1 : q_[head_]; }

  int Rear() { return isEmpty() ? -1 : q_[(head_ + size_ - 1) % q_.size()]; }

  bool isEmpty() { return size_ == 0; }

  bool isFull() { return size_ == q_.size(); }
private:
  vector&lt;int&gt; q_;
  int head_ = 0;
  int size_ = 0;
};</pre>

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

<pre class="crayon-plain-tag">class MyCircularQueue {
  private int[] q;
  private int head;
  private int size;
  
  public MyCircularQueue(int k) {
    this.q = new int[k];
    this.head = 0;
    this.size = 0;
  }
  
  public boolean enQueue(int value) {
    if (this.isFull()) return false;    
    this.q[(this.head + this.size) % this.q.length] = value;
    ++this.size;
    return true;
  }

  public boolean deQueue() {
    if (this.isEmpty()) return false;
    this.head = (this.head + 1) % this.q.length;
    --this.size;
    return true;
  }

  public int Front() {
    return this.isEmpty() ? -1 : this.q[this.head];
  }

  public int Rear() {
    return this.isEmpty() ? -1 : this.q[(this.head + this.size - 1) % this.q.length];
  }

  public boolean isEmpty() { return this.size == 0; }  

  public boolean isFull() { return this.size == this.q.length; }
}</pre>

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

<pre class="crayon-plain-tag">class MyCircularQueue:
  def __init__(self, k: int):
    self.q = [0] * k
    self.k = k
    self.head = self.size = 0


  def enQueue(self, value: int) -&gt; bool:
    if self.isFull(): return False
    self.q[(self.head + self.size) % self.k] = value
    self.size += 1
    return True


  def deQueue(self) -&gt; bool:
    if self.isEmpty(): return False
    self.head = (self.head + 1) % self.k
    self.size -= 1
    return True


  def Front(self) -&gt; int:
    return -1 if self.isEmpty() else self.q[self.head]


  def Rear(self) -&gt; int:
    return -1 if self.isEmpty() else self.q[(self.head + self.size - 1) % self.k]


  def isEmpty(self) -&gt; bool:
    return self.size == 0


  def isFull(self) -&gt; bool:
    return self.size == self.k</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/">花花酱 LeetCode 622. Design Circular Queue</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/desgin/leetcode-622-design-circular-queue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 239. Sliding Window Maximum</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 25 Jan 2018 05:17:37 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1650</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，让你输出移动窗口的最大值。 Problem: https://leetcode.com/problems/sliding-window-maximum/ Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</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/2SXqBsTR6a8?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，让你输出移动窗口的最大值。</p>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/sliding-window-maximum/">https://leetcode.com/problems/sliding-window-maximum/</a></p>
<p>Given an array <i>nums</i>, there is a sliding window of size <i>k</i> which is moving from the very left of the array to the very right. You can only see the <i>k</i> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>For example,<br />
Given <i>nums</i> = <code>[1,3,-1,-3,5,3,6,7]</code>, and <i>k</i> = 3.</p><pre class="crayon-plain-tag">Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7</pre><p>Therefore, return the max sliding window as <code>[3,3,5,5,6,7]</code>.</p>
<p><b>Note: </b><br />
You may assume <i>k</i> is always valid, ie: 1 ≤ k ≤ input array&#8217;s size for non-empty array.</p>
<p><b>Follow up:</b><br />
Could you solve it in linear time?</p>
<p><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></p>
<p><strong>Idea:</strong></p>
<p><img class="alignnone size-full wp-image-1657" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1656" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>&nbsp;</p>
<h1><strong>Solution 1: Brute Force</strong></h1>
<p>Time complexity: O((n &#8211; k + 1) * k)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 180 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;int&gt; ans;
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      ans.push_back(*max_element(nums.begin() + i - k + 1, nums.begin() + i + 1));
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 80 ms
class Solution {
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (k == 0) return new int[0];
    
    int[] ans = new int[nums.length - k + 1];    
    for (int i = k - 1; i &lt; nums.length; ++i) {
      int maxNum = nums[i];
      for (int j = 1; j &lt; k; ++j)
        if (nums[i - j] &gt; maxNum) maxNum = nums[i - j];
      ans[i - k + 1] = maxNum;
    }
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1044 ms
"""
class Solution:
  def maxSlidingWindow(self, nums, k):
    if not nums: return []    
    return [max(nums[i:i+k]) for i in range(len(nums) - k + 1)]</pre><p></div></div></p>
<h1><strong>Solution 2: BST</strong></h1>
<p>Time complexity: O((n &#8211; k + 1) * logk)</p>
<p>Space complexity: O(k)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 82 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    vector&lt;int&gt; ans;
    if (nums.empty()) return ans;
    multiset&lt;int&gt; window(nums.begin(), nums.begin() + k - 1);
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      window.insert(nums[i]);
      ans.push_back(*window.rbegin());
      if (i - k + 1 &gt;= 0)
        window.erase(window.equal_range(nums[i - k + 1]).first);      
    }
    return ans;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 3: Monotonic Queue</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(k)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 70 ms
class MonotonicQueue {
public:
  void push(int e) {
    while(!data_.empty() &amp;&amp; e &gt; data_.back()) data_.pop_back();
    data_.push_back(e);
  } 
  
  void pop() {
    data_.pop_front();
  }
  
  int max() const { return data_.front(); }
private:
  deque&lt;int&gt; data_;
};

class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    MonotonicQueue q;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      q.push(nums[i]);
      if (i - k + 1 &gt;= 0) {
        ans.push_back(q.max());
        if (nums[i - k + 1] == q.max()) q.pop();
      }      
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">C++ V2</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 65 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    deque&lt;int&gt; index;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      while (!index.empty() &amp;&amp; nums[i] &gt;= nums[index.back()]) index.pop_back();
      index.push_back(i);      
      if (i - k + 1 &gt;= 0) ans.push_back(nums[index.front()]);
      if (i - k + 1 &gt;= index.front()) index.pop_front();
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">C++ V3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 67 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    deque&lt;int&gt; q;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      while (!q.empty() &amp;&amp; nums[i] &gt; q.back()) q.pop_back();
      q.push_back(nums[i]);
      const int s = i - k + 1;
      if (s &lt; 0) continue;      
      ans.push_back(q.front());
      if (nums[s] == q.front()) q.pop_front();
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 19 ms
class Solution {
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (k == 0) return nums;
    
    int[] ans = new int[nums.length - k + 1];
    Deque&lt;Integer&gt; indices = new LinkedList&lt;&gt;();
    
    for (int i = 0; i &lt; nums.length; ++i) {
      while (indices.size() &gt; 0 &amp;&amp; nums[i] &gt;= nums[indices.getLast()])
        indices.removeLast();
      
      indices.addLast(i);
      if (i - k + 1 &gt;= 0) ans[i - k + 1] = nums[indices.getFirst()];
      if (i - k + 1 &gt;= indices.getFirst()) indices.removeFirst();
    }
             
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 238 ms
"""
class MaxQueue:
  def __init__(self):
    self.q_ = collections.deque()
  
  def push(self, e):
    while self.q_ and e &gt; self.q_[-1]: self.q_.pop()
    self.q_.append(e)
  
  def pop(self):
    self.q_.popleft()
  
  def max(self):
    return self.q_[0]
    
class Solution:
  def maxSlidingWindow(self, nums, k):
    q = MaxQueue()
    ans = []
    for i in range(len(nums)):
      q.push(nums[i])
      if i &gt;= k - 1: 
        ans.append(q.max())
        if nums[i - k + 1] == q.max(): q.pop()
    return ans</pre><p></div><h2 class="tabtitle">Python3 V2</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 193 ms
"""
class Solution:
  def maxSlidingWindow(self, nums, k):
    indices = collections.deque()
    ans = []
    for i in range(len(nums)):
      while indices and nums[i] &gt;= nums[indices[-1]]: indices.pop()
      indices.append(i)
      if i &gt;= k - 1: ans.append(nums[indices[0]])
      if i - k + 1 == indices[0]: indices.popleft()
    return ans</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
