<?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>Stack Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/stack/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/stack/</link>
	<description></description>
	<lastBuildDate>Tue, 14 Feb 2023 00:01:34 +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>Stack Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/stack/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2553. Separate the Digits in an Array</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-2553-separate-the-digits-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-2553-separate-the-digits-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 14 Feb 2023 00:00:21 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9948</guid>

					<description><![CDATA[<p>Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums. To separate&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2553-separate-the-digits-in-an-array/">花花酱 LeetCode 2553. Separate the Digits in an 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[
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p>



<p>To separate the digits of an integer is to get all the digits it has in the same order.</p>



<ul><li>For example, for the integer&nbsp;<code>10921</code>, the separation of its digits is&nbsp;<code>[1,0,9,2,1]</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [13,25,83,77]
<strong>Output:</strong> [1,3,2,5,8,3,7,7]
<strong>Explanation:</strong> 
- The separation of 13 is [1,3].
- The separation of 25 is [2,5].
- The separation of 83 is [8,3].
- The separation of 77 is [7,7].
answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [7,1,3,9]
<strong>Output:</strong> [7,1,3,9]
<strong>Explanation:</strong> The separation of each integer in nums is itself.
answer = [7,1,3,9].
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>Time complexity: O(sum(log(nums[i]))<br>Space complexity: O(log(nums[i]))</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; separateDigits(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; ans;
    for (int n : nums) {
      stack&lt;int&gt; cur;
      for (int x = n; x; x /= 10)
        cur.push(x % 10);
      while (!cur.empty())      
        ans.push_back(cur.top()), cur.pop();
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2553-separate-the-digits-in-an-array/">花花酱 LeetCode 2553. Separate the Digits in an 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/stack/leetcode-2553-separate-the-digits-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2197. Replace Non-Coprime Numbers in Array</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 08 Mar 2022 12:18:45 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[co-prime]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[lcm]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9561</guid>

					<description><![CDATA[<p>You are given an array of integers&#160;nums. Perform the following steps: Find&#160;any&#160;two&#160;adjacent&#160;numbers in&#160;nums&#160;that are&#160;non-coprime. If no such numbers are found,&#160;stop&#160;the process. Otherwise, delete the two&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/">花花酱 LeetCode 2197. Replace Non-Coprime Numbers in 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[
<p>You are given an array of integers&nbsp;<code>nums</code>. Perform the following steps:</p>



<ol><li>Find&nbsp;<strong>any</strong>&nbsp;two&nbsp;<strong>adjacent</strong>&nbsp;numbers in&nbsp;<code>nums</code>&nbsp;that are&nbsp;<strong>non-coprime</strong>.</li><li>If no such numbers are found,&nbsp;<strong>stop</strong>&nbsp;the process.</li><li>Otherwise, delete the two numbers and&nbsp;<strong>replace</strong>&nbsp;them with their&nbsp;<strong>LCM (Least Common Multiple)</strong>.</li><li><strong>Repeat</strong>&nbsp;this process as long as you keep finding two adjacent non-coprime numbers.</li></ol>



<p>Return&nbsp;<em>the&nbsp;<strong>final</strong>&nbsp;modified array.</em>&nbsp;It can be shown that replacing adjacent non-coprime numbers in&nbsp;<strong>any</strong>&nbsp;arbitrary order will lead to the same result.</p>



<p>The test cases are generated such that the values in the final array are&nbsp;<strong>less than or equal</strong>&nbsp;to&nbsp;<code>10<sup>8</sup></code>.</p>



<p>Two values&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>&nbsp;are&nbsp;<strong>non-coprime</strong>&nbsp;if&nbsp;<code>GCD(x, y) &gt; 1</code>&nbsp;where&nbsp;<code>GCD(x, y)</code>&nbsp;is the&nbsp;<strong>Greatest Common Divisor</strong>&nbsp;of&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [6,4,3,2,7,6,2]
<strong>Output:</strong> [12,7,6]
<strong>Explanation:</strong> 
- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [<strong><u>12</u></strong>,3,2,7,6,2].
- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [<strong><u>12</u></strong>,2,7,6,2].
- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [<strong><u>12</u></strong>,7,6,2].
- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,<strong>6</strong>].
There are no more adjacent non-coprime numbers in nums.
Thus, the final modified array is [12,7,6].
Note that there are other ways to obtain the same resultant array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,2,1,1,3,3,3]
<strong>Output:</strong> [2,1,1,3]
<strong>Explanation:</strong> 
- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,<strong>3</strong>,3].
- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,<strong>3</strong>].
- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [<strong>2</strong>,1,1,3].
There are no more adjacent non-coprime numbers in nums.
Thus, the final modified array is [2,1,1,3].
Note that there are other ways to obtain the same resultant array.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li>The test cases are generated such that the values in the final array are&nbsp;<strong>less than or equal</strong>&nbsp;to&nbsp;<code>10<sup>8</sup></code>.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>&#8220;&#8221;&#8221;It can be shown that replacing adjacent non-coprime numbers in&nbsp;<strong>any</strong>&nbsp;arbitrary order will lead to the same result.&#8221;&#8221;&#8221;</p>



<p>So that we can do it in one pass from left to right using a stack/vector.</p>



<p>Push the current number onto stack, and merge top two if they are not co-prime.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; replaceNonCoprimes(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; ans;
    for (int x : nums) {
      ans.push_back(x);
      while (ans.size() &gt; 1) {
        const int n1 = ans[ans.size() - 1]; 
        const int n2 = ans[ans.size() - 2]; 
        const int d = gcd(n1, n2);
        if (d == 1) break;
        ans.pop_back();
        ans.pop_back();
        ans.push_back(n1 / d * n2);
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-2197-replace-non-coprime-numbers-in-array/">花花酱 LeetCode 2197. Replace Non-Coprime Numbers in 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/stack/leetcode-2197-replace-non-coprime-numbers-in-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 155. Min Stack</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-155-min-stack/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-155-min-stack/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 22:01:10 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8870</guid>

					<description><![CDATA[<p>Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the&#160;MinStack&#160;class: MinStack()&#160;initializes the stack object. void push(int val)&#160;pushes&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-155-min-stack/">花花酱 LeetCode 155. Min Stack</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 a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p>



<p>Implement the&nbsp;<code>MinStack</code>&nbsp;class:</p>



<ul><li><code>MinStack()</code>&nbsp;initializes the stack object.</li><li><code>void push(int val)</code>&nbsp;pushes the element&nbsp;<code>val</code>&nbsp;onto the stack.</li><li><code>void pop()</code>&nbsp;removes the element on the top of the stack.</li><li><code>int top()</code>&nbsp;gets the top element of the stack.</li><li><code>int getMin()</code>&nbsp;retrieves the minimum element in the stack.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

<strong>Output</strong>
</pre>


<p>[null,null,null,null,-3,null,0,-2]</p>



<p><strong>Explanation</strong> MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2</p>



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



<ul><li><code>-2<sup>31</sup>&nbsp;&lt;= val &lt;= 2<sup>31</sup>&nbsp;- 1</code></li><li>Methods&nbsp;<code>pop</code>,&nbsp;<code>top</code>&nbsp;and&nbsp;<code>getMin</code>&nbsp;operations will always be called on&nbsp;<strong>non-empty</strong>&nbsp;stacks.</li><li>At most&nbsp;<code>3 * 10<sup>4</sup></code>&nbsp;calls will be made to&nbsp;<code>push</code>,&nbsp;<code>pop</code>,&nbsp;<code>top</code>, and&nbsp;<code>getMin</code>.</li></ul>



<h2><strong>Solution 1: Two Stack</strong>s</h2>



<p>One normal stack, one monotonic stack to store the min values.</p>



<p>Time complexity: O(1) per op<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 MinStack {
public:
  void push(int x) {
    m_data.push(x);
    if (m_s.empty() || x &lt;= m_s.top())
      m_s.push(x);
  }

  void pop() {
    if (!m_s.empty() &amp;&amp; m_data.top() == m_s.top())
      m_s.pop();
    m_data.pop();
  }

  int top() {
    return m_data.top();
  }

  int getMin() {
    return m_s.empty() ? m_data.top() : m_s.top();
  }
private:
  stack&lt;int&gt; m_data;
  stack&lt;int&gt; m_s;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-155-min-stack/">花花酱 LeetCode 155. Min Stack</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/stack/leetcode-155-min-stack/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1776. Car Fleet II</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Feb 2021 07:45:38 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8176</guid>

					<description><![CDATA[<p>There are&#160;n&#160;cars traveling at different speeds in the same direction along a one-lane road. You are given an array&#160;cars&#160;of length&#160;n, where&#160;cars[i] = [positioni, speedi]&#160;represents: positioni&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/">花花酱 LeetCode 1776. Car Fleet II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There are&nbsp;<code>n</code>&nbsp;cars traveling at different speeds in the same direction along a one-lane road. You are given an array&nbsp;<code>cars</code>&nbsp;of length&nbsp;<code>n</code>, where&nbsp;<code>cars[i] = [position<sub>i</sub>, speed<sub>i</sub>]</code>&nbsp;represents:</p>



<ul><li><code>position<sub>i</sub></code>&nbsp;is the distance between the&nbsp;<code>i<sup>th</sup></code>&nbsp;car and the beginning of the road in meters. It is guaranteed that&nbsp;<code>position<sub>i</sub>&nbsp;&lt; position<sub>i+1</sub></code>.</li><li><code>speed<sub>i</sub></code>&nbsp;is the initial speed of the&nbsp;<code>i<sup>th</sup></code>&nbsp;car in meters per second.</li></ul>



<p>For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the&nbsp;<strong>slowest</strong>&nbsp;car in the fleet.</p>



<p>Return an array&nbsp;<code>answer</code>, where&nbsp;<code>answer[i]</code>&nbsp;is the time, in seconds, at which the&nbsp;<code>i<sup>th</sup></code>&nbsp;car collides with the next car, or&nbsp;<code>-1</code>&nbsp;if the car does not collide with the next car. Answers within&nbsp;<code>10<sup>-5</sup></code>&nbsp;of the actual answers are accepted.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cars = [[1,2],[2,1],[4,3],[7,2]]
<strong>Output:</strong> [1.00000,-1.00000,3.00000,-1.00000]
<strong>Explanation:</strong> After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cars = [[3,4],[5,4],[6,3],[9,1]]
<strong>Output:</strong> [2.00000,1.00000,1.50000,-1.00000]
</pre>



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



<ul><li><code>1 &lt;= cars.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= position<sub>i</sub>, speed<sub>i</sub>&nbsp;&lt;= 10<sup>6</sup></code></li><li><code>position<sub>i</sub>&nbsp;&lt; position<sub>i+1</sub></code></li></ul>



<h2><strong>Solution: Monotonic Stack</strong></h2>



<p>Key observation: If my speed is slower than the speed of the previous car, not only mine but also all cars behind me will NEVER be able to catch/collide with the previous car. Such that we can throw it away.</p>



<p>Maintain a stack that stores the indices of cars with increasing speed.</p>



<p>Process car from right to left, for each car, pop the stack (throw the fastest car away) if any of the following conditions hold.<br>1)  speed &lt;= stack.top().speed<br>2) There are more than one car before me and it takes more than to collide the fastest car than time the fastest took to collide.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;double&gt; getCollisionTimes(vector&lt;vector&lt;int&gt;&gt;&amp; cars) {
    auto collide = [&amp;](int i, int j) -&gt; double {
      return static_cast&lt;double&gt;(cars[i][0] - cars[j][0]) /
        (cars[j][1] - cars[i][1]);
    };
    const int n = cars.size();
    vector&lt;double&gt; ans(n, -1);
    stack&lt;int&gt; s;
    for (int i = n - 1; i &gt;= 0; --i) {
      while (!s.empty() &amp;&amp; (cars[i][1] &lt;= cars[s.top()][1] ||
                           (s.size() &gt; 1 &amp;&amp; collide(i, s.top()) &gt; ans[s.top()])))
        s.pop();
      ans[i] = s.empty() ? -1 : collide(i, s.top());
      s.push(i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/">花花酱 LeetCode 1776. Car Fleet II</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/stack/leetcode-1776-car-fleet-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1614. Maximum Nesting Depth of the Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Oct 2020 04:56:20 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[parentheses]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7474</guid>

					<description><![CDATA[<p>A string is a&#160;valid parentheses string&#160;(denoted&#160;VPS) if it meets one of the following: It is an empty string&#160;"", or a single character not equal to&#160;"("&#160;or&#160;")",&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/">花花酱 LeetCode 1614. Maximum Nesting Depth of the Parentheses</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 string is a&nbsp;<strong>valid parentheses string</strong>&nbsp;(denoted&nbsp;<strong>VPS</strong>) if it meets one of the following:</p>



<ul><li>It is an empty string&nbsp;<code>""</code>, or a single character not equal to&nbsp;<code>"("</code>&nbsp;or&nbsp;<code>")"</code>,</li><li>It can be written as&nbsp;<code>AB</code>&nbsp;(<code>A</code>&nbsp;concatenated with&nbsp;<code>B</code>), where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s, or</li><li>It can be written as&nbsp;<code>(A)</code>, where&nbsp;<code>A</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<p>We can similarly define the&nbsp;<strong>nesting depth</strong>&nbsp;<code>depth(S)</code>&nbsp;of any VPS&nbsp;<code>S</code>&nbsp;as follows:</p>



<ul><li><code>depth("") = 0</code></li><li><code>depth(A + B) = max(depth(A), depth(B))</code>, where&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s</li><li><code>depth("(" + A + ")") = 1 + depth(A)</code>, where&nbsp;<code>A</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<p>For example,&nbsp;<code>""</code>,&nbsp;<code>"()()"</code>, and&nbsp;<code>"()(()())"</code>&nbsp;are&nbsp;<strong>VPS</strong>&#8216;s (with nesting depths 0, 1, and 2), and&nbsp;<code>")("</code>&nbsp;and&nbsp;<code>"(()"</code>&nbsp;are not&nbsp;<strong>VPS</strong>&#8216;s.</p>



<p>Given a&nbsp;<strong>VPS</strong>&nbsp;represented as string&nbsp;<code>s</code>, return&nbsp;<em>the&nbsp;<strong>nesting depth</strong>&nbsp;of&nbsp;</em><code>s</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(1+(2*3)+((8)/4))+1"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Digit 8 is inside of 3 nested parentheses in the string.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(1)+((2))+(((3)))"
<strong>Output:</strong> 3
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1+(2*3)/(2-1)"
<strong>Output:</strong> 1
</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 100</code></li><li><code>s</code>&nbsp;consists of digits&nbsp;<code>0-9</code>&nbsp;and characters&nbsp;<code>'+'</code>,&nbsp;<code>'-'</code>,&nbsp;<code>'*'</code>,&nbsp;<code>'/'</code>,&nbsp;<code>'('</code>, and&nbsp;<code>')'</code>.</li><li>It is guaranteed that parentheses expression&nbsp;<code>s</code>&nbsp;is a&nbsp;<strong>VPS</strong>.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>We only need to deal with &#8216;(&#8216; and &#8216;)&#8217;</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 maxDepth(string s) {
    int ans = 0;
    int d = 0;
    for (char c : s) {
      if (c == '(') ans = max(ans, ++d);
      else if (c == ')') --d;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/">花花酱 LeetCode 1614. Maximum Nesting Depth of the Parentheses</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/stack/leetcode-1614-maximum-nesting-depth-of-the-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1544. Make The String Great</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1544-make-the-string-great/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1544-make-the-string-great/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 10 Aug 2020 07:51:16 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7225</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;of lower and upper case English letters. A good string is a string which doesn&#8217;t have&#160;two adjacent characters&#160;s[i]&#160;and&#160;s[i + 1]&#160;where: 0 &#60;= i&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1544-make-the-string-great/">花花酱 LeetCode 1544. Make The String Great</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>&nbsp;of lower and upper case English letters.</p>



<p>A good string is a string which doesn&#8217;t have&nbsp;<strong>two adjacent characters</strong>&nbsp;<code>s[i]</code>&nbsp;and&nbsp;<code>s[i + 1]</code>&nbsp;where:</p>



<ul><li><code>0 &lt;= i &lt;= s.length - 2</code></li><li><code>s[i]</code>&nbsp;is a lower-case letter and&nbsp;<code>s[i + 1]</code>&nbsp;is the same letter but in upper-case&nbsp;or&nbsp;<strong>vice-versa</strong>.</li></ul>



<p>To make the string good, you can choose&nbsp;<strong>two adjacent</strong>&nbsp;characters that make the string bad and remove them. You can keep doing this until the string becomes good.</p>



<p>Return&nbsp;<em>the string</em>&nbsp;after making it good. The answer is guaranteed to be unique under the given constraints.</p>



<p><strong>Notice</strong>&nbsp;that an empty string is also good.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leEeetcode"
<strong>Output:</strong> "leetcode"
<strong>Explanation:</strong> In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abBAcC"
<strong>Output:</strong> ""
<strong>Explanation:</strong> We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --&gt; "aAcC" --&gt; "cC" --&gt; ""
"abBAcC" --&gt; "abBA" --&gt; "aA" --&gt; ""
</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 100</code></li><li><code>s</code>&nbsp;contains only lower and upper case English letters.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>Iterator over the string, compare current char with top of the stack, if they are a bad pair, pop the stack (remove both of them). Otherwise, push the current char onto the stack.</p>



<p>input: &#8220;abBAcC&#8221;<br>&#8220;a&#8221;<br>&#8220;ab&#8221;<br>&#8220;a<s>bB</s>&#8221; -> &#8220;a&#8221;<br>&#8220;<s>aA</s>&#8221; -> &#8220;&#8221;<br>&#8220;c&#8221;<br>&#8220;<s>cC</s>&#8221; -> &#8220;&#8221;<br>ans = &#8220;&#8221;</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:
  string makeGood(string s) {
    string ans;
    for (char c : s) {      
      if (ans.length() &amp;&amp; 
          abs(ans.back() - c) == abs('a' - 'A'))
        ans.pop_back();        
      else
        ans.push_back(c);
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution {
  public String makeGood(String s) {
    var sb = new StringBuilder();
    for (int i = 0; i &lt; s.length(); ++i) {
      int l = sb.length();
      if (l &gt; 0 &amp;&amp; Math.abs(sb.charAt(l - 1) - s.charAt(i)) == 32) {
        sb.setLength(l - 1); // remove last char
      } else {
        sb.append(s.charAt(i));
      }
    }
    return sb.toString();
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def makeGood(self, s: str) -&gt; str:
    ans = []
    for c in s:
      if ans and abs(ord(ans[-1]) - ord(c)) == 32:
        ans.pop()
      else:
        ans.append(c)
    return &quot;&quot;.join(ans)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1544-make-the-string-great/">花花酱 LeetCode 1544. Make The String Great</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/stack/leetcode-1544-make-the-string-great/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 13 Jun 2020 17:04:18 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6901</guid>

					<description><![CDATA[<p>Given the array&#160;prices&#160;where&#160;prices[i]&#160;is the price of the&#160;ith&#160;item in a shop. There is a special discount for items in the shop, if you buy the&#160;ith&#160;item, then&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/">花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</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-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode1475. Final Prices With a Special Discount in a Shop  - 刷题找工作 EP334" width="500" height="375" src="https://www.youtube.com/embed/X98Yc4YtgyA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the array&nbsp;<code>prices</code>&nbsp;where&nbsp;<code>prices[i]</code>&nbsp;is the price of the&nbsp;<code>ith</code>&nbsp;item in a shop. There is a special discount for items in the shop, if you buy the&nbsp;<code>ith</code>&nbsp;item, then you will receive a discount equivalent to&nbsp;<code>prices[j]</code>&nbsp;where&nbsp;<code>j</code>&nbsp;is the&nbsp;<strong>minimum</strong>&nbsp;index such that&nbsp;<code>j &gt; i</code>&nbsp;and&nbsp;<code>prices[j] &lt;= prices[i]</code>, otherwise, you will not receive any discount at all.</p>



<p><em>Return an array where the&nbsp;<code>ith</code>&nbsp;element is the final price you will pay for the&nbsp;<code>ith</code>&nbsp;item of the shop considering the special discount.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [8,4,6,2,3]
<strong>Output:</strong> [4,2,4,2,3]
<strong>Explanation:</strong>&nbsp;
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.&nbsp;
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.&nbsp;
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.&nbsp;
For items 3 and 4 you will not receive any discount at all.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [1,2,3,4,5]
<strong>Output:</strong> [1,2,3,4,5]
<strong>Explanation:</strong> In this case, for all items, you will not receive any discount at all.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [10,1,1,6]
<strong>Output:</strong> [9,0,1,6]
</pre>



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



<ul><li><code>1 &lt;= prices.length &lt;= 500</code></li><li><code>1 &lt;= prices[i] &lt;= 10^3</code></li></ul>



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



<p>Time complexity: O(n^2)<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:
  vector&lt;int&gt; finalPrices(vector&lt;int&gt; prices) {
    const int n = prices.size();
    for (int i = 0; i &lt; n; ++i)      
      for (int j = i + 1; j &lt; n; ++j)
        if (prices[j] &lt;= prices[i]) {
          prices[i] -= prices[j];
          break;
        }     
    return prices;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Monotonic Stack</strong></h2>



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



<p>Use a stack to store monotonically increasing items, when the current item is cheaper than the top of the stack, we get the discount and pop that item. Repeat until the current item is no longer cheaper or the stack becomes empty.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; finalPrices(vector&lt;int&gt; prices) {
    // stores pointers of monotonically incraseing elements.
    stack&lt;int*&gt; s; 
    for (int&amp; p : prices) {
      while (!s.empty() &amp;&amp; *s.top() &gt;= p) {
        *s.top() -= p;
        s.pop();
      }
      s.push(&amp;p);
    }      
    return prices;
  }
};</pre>
</div></div>



<p>index version</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; finalPrices(vector&lt;int&gt; prices) {
    // stores indices of monotonically incraseing elements.
    stack&lt;int&gt; s; 
    for (int i = 0; i &lt; prices.size(); ++i) {
      while (!s.empty() &amp;&amp; prices[s.top()] &gt;= prices[i]) {
        prices[s.top()] -= prices[i];
        s.pop();
      }
      s.push(i);
    }      
    return prices;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/">花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</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/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1381. Design a Stack With Increment Operation</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1381-design-a-stack-with-increment-operation/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1381-design-a-stack-with-increment-operation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Mar 2020 08:30:22 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[desgin]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6497</guid>

					<description><![CDATA[<p>Design a stack which supports the following operations. Implement the&#160;CustomStack&#160;class: CustomStack(int maxSize)&#160;Initializes the object with&#160;maxSize&#160;which is the maximum number of elements in the stack or&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1381-design-a-stack-with-increment-operation/">花花酱 LeetCode 1381. Design a Stack With Increment Operation</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 a stack which supports the following operations.</p>



<p>Implement the&nbsp;<code>CustomStack</code>&nbsp;class:</p>



<ul><li><code>CustomStack(int maxSize)</code>&nbsp;Initializes the object with&nbsp;<code>maxSize</code>&nbsp;which is the maximum number of elements in the stack or do nothing if the stack reached the&nbsp;<code>maxSize</code>.</li><li><code>void push(int x)</code>&nbsp;Adds&nbsp;<code>x</code>&nbsp;to the top of the stack if the stack hasn&#8217;t reached the&nbsp;<code>maxSize</code>.</li><li><code>int pop()</code>&nbsp;Pops and returns the top of stack or&nbsp;<strong>-1</strong>&nbsp;if the stack is empty.</li><li><code>void inc(int k, int val)</code>&nbsp;Increments the bottom&nbsp;<code>k</code>&nbsp;elements of the stack by&nbsp;<code>val</code>. If there are less than&nbsp;<code>k</code>&nbsp;elements in the stack, just increment all the elements in the stack.</li></ul>



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



<pre class="wp-block-preformatted wp-block-preformatted;crayon:false"><strong>Input</strong>
["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
<strong>Output</strong>
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
<strong>Explanation</strong>
CustomStack customStack = new CustomStack(3); // Stack is Empty []
customStack.push(1);                          // stack becomes [1]
customStack.push(2);                          // stack becomes [1, 2]
customStack.pop();                            // return 2 --&gt; Return top of the stack 2, stack becomes [1]
customStack.push(2);                          // stack becomes [1, 2]
customStack.push(3);                          // stack becomes [1, 2, 3]
customStack.push(4);                          // stack still [1, 2, 3], Don't add another elements as size is 4
customStack.increment(5, 100);                // stack becomes [101, 102, 103]
customStack.increment(2, 100);                // stack becomes [201, 202, 103]
customStack.pop();                            // return 103 --&gt; Return top of the stack 103, stack becomes [201, 202]
customStack.pop();                            // return 202 --&gt; Return top of the stack 102, stack becomes [201]
customStack.pop();                            // return 201 --&gt; Return top of the stack 101, stack becomes []
customStack.pop();                            // return -1 --&gt; Stack is empty return -1.
</pre>



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



<p>Time complexity: <br>init: O(1)<br>pop: O(1)<br>push: O(1)<br>inc: O(k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class CustomStack {
public:
  CustomStack(int maxSize): max_size_(maxSize) {}

  void push(int x) {
    if (data_.size() == max_size_) return;
    data_.push_back(x);
  }

  int pop() {
    if (data_.empty()) return -1;
    int val = data_.back();
    data_.pop_back();
    return val;
  }

  void increment(int k, int val) {
    for (int i = 0; i &lt; min(static_cast&lt;size_t&gt;(k), 
                            data_.size()); ++i)
      data_[i] += val;
  }
private:
  int max_size_;
  vector&lt;int&gt; data_;
};

/**
 * Your CustomStack object will be instantiated and called as such:
 * CustomStack* obj = new CustomStack(maxSize);
 * obj-&gt;push(x);
 * int param_2 = obj-&gt;pop();
 * obj-&gt;increment(k,val);
 */</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1381-design-a-stack-with-increment-operation/">花花酱 LeetCode 1381. Design a Stack With Increment Operation</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/stack/leetcode-1381-design-a-stack-with-increment-operation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 227. Basic Calculator II</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Mar 2020 01:24:59 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[calculator]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6442</guid>

					<description><![CDATA[<p>Implement a basic calculator to evaluate a simple expression string. The expression string contains only&#160;non-negative&#160;integers,&#160;+,&#160;-,&#160;*,&#160;/&#160;operators and empty spaces&#160;. The integer division should truncate toward zero.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/">花花酱 LeetCode 227. Basic Calculator II</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 a basic calculator to evaluate a simple expression string.</p>



<p>The expression string contains only&nbsp;<strong>non-negative</strong>&nbsp;integers,&nbsp;<code>+</code>,&nbsp;<code>-</code>,&nbsp;<code>*</code>,&nbsp;<code>/</code>&nbsp;operators and empty spaces&nbsp;. The integer division should truncate toward zero.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>"3+2*2"
<strong>Output:</strong> 7
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> " 3+5 / 2 "
<strong>Output:</strong> 5
</pre>



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



<ul><li>You may assume that the given expression is always valid.</li><li><strong>Do not</strong>&nbsp;use the&nbsp;<code>eval</code>&nbsp;built-in library function.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>if operator is ‘+’ or ‘-’, push the current num * sign onto stack.<br>if operator &#8216;*&#8217; or &#8216;/&#8217;, pop the last num from stack and * or / by the current num and push it back to stack.</p>



<p>The answer is the sum of numbers on stack.</p>



<p>3+2*2 =&gt; {3}, {3,2}, {3, 2*2} = {3, 4} =&gt; ans = 7<br>3 +5/2 =&gt; {3}, {3,5}, {3, 5/2} = {3, 2} =&gt; ans = 5<br>1 + 2*3 &#8211; 5 =&gt; {1}, {1,2}, {1,2*3} = {1,6}, {1, 6, -5} =&gt; ans = 2</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int calculate(string s) {
    vector&lt;int&gt; nums;    
    char op = '+';
    int cur = 0;
    int pos = 0;
    while (pos &lt; s.size()) {
      if (s[pos] == ' ') {
        ++pos;
        continue;
      }
      while (isdigit(s[pos]) &amp;&amp; pos &lt; s.size())
        cur = cur * 10 + (s[pos++] - '0');      
      if (op == '+' || op == '-') {
        nums.push_back(cur * (op == '+' ? 1 : -1));
      } else if (op == '*') {
        nums.back() *= cur;
      } else if (op == '/') {
        nums.back() /= cur;
      }
      cur = 0;      
      op = s[pos++];
    }
    return accumulate(begin(nums), end(nums), 0);
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def calculate(self, s: str) -&gt; int:
    nums = []
    op = '+'
    cur = 0
    i = 0
    while i &lt; len(s):
      if s[i] == ' ': 
        i += 1
        continue
      while i &lt; len(s) and s[i].isdigit():
        cur = cur * 10 + ord(s[i]) - ord('0')
        i += 1      
      if op in '+-':
        nums.append(cur * (1 if op == '+' else -1))
      elif op == '*':
        nums[-1] *= cur
      elif op == '/':
        sign = -1 if nums[-1] &lt; 0 or cur &lt; 0 else 1
        nums[-1] = abs(nums[-1]) // abs(cur) * sign
      cur = 0
      if (i &lt; len(s)): op = s[i]
      i += 1    
    return sum(nums)</pre>
</div></div>



<h2><strong>Related Problems</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/</a></li><li><a href="https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/">https://zxi.mytechroad.com/blog/recursion/leetcode-736-parse-lisp-expression/</a></li><li><a href="https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/">https://zxi.mytechroad.com/blog/searching/leetcode-282-expression-add-operators/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-227-basic-calculator-ii/">花花酱 LeetCode 227. Basic Calculator II</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/stack/leetcode-227-basic-calculator-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 84. Largest Rectangle in Histogram</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 14 Feb 2020 08:14:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6313</guid>

					<description><![CDATA[<p>Given&#160;n&#160;non-negative integers representing the histogram&#8217;s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/">花花酱 LeetCode 84. Largest Rectangle in Histogram</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&nbsp;<em>n</em>&nbsp;non-negative integers representing the histogram&#8217;s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/10/12/histogram.png" alt=""/></figure>



<p><br>Above is a histogram where width of each bar is 1, given height =&nbsp;<code>[2,1,5,6,2,3]</code>.</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/10/12/histogram_area.png" alt=""/></figure>



<p><br>The largest rectangle is shown in the shaded area, which has area =&nbsp;<code>10</code>&nbsp;unit.</p>



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



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



<h2><strong>Solution 1: Monotonic Stack</strong></h2>



<p>Use a monotonic stack to maintain the higher bars&#8217;s indices in ascending order.<br>When encounter a lower bar, pop the tallest bar and use it as the bottleneck to compute the area.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, 12ms, 10.7MB
class Solution {
public:
  int largestRectangleArea(vector&lt;int&gt;&amp; heights) {
    heights.push_back(0);
    const int n = heights.size();
    stack&lt;int&gt; s;
    int ans = 0;
    int i = 0;
    while (i &lt; n) {
      if (s.empty() || heights[i] &gt;= heights[s.top()]) {
        s.push(i++);
      } else {
        int h = heights[s.top()]; s.pop();
        int w = s.empty() ? i : i - s.top() - 1;        
        ans = max(ans, h * w);
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/">花花酱 LeetCode 84. Largest Rectangle in Histogram</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/stack/leetcode-84-largest-rectangle-in-histogram/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 71. Simplify Path</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-71-simplify-path/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-71-simplify-path/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 01 Oct 2019 07:40:13 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5684</guid>

					<description><![CDATA[<p>Given an&#160;absolute path&#160;for a file (Unix-style), simplify it. Or in other words, convert it to the&#160;canonical path. In a UNIX-style file system, a period&#160;.&#160;refers to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-71-simplify-path/">花花酱 LeetCode 71. Simplify Path</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 an&nbsp;<strong>absolute path</strong>&nbsp;for a file (Unix-style), simplify it. Or in other words, convert it to the&nbsp;<strong>canonical path</strong>.</p>



<p>In a UNIX-style file system, a period&nbsp;<code>.</code>&nbsp;refers to the current directory. Furthermore, a double period&nbsp;<code>..</code>&nbsp;moves the directory up a level. For more information, see:&nbsp;<a href="https://www.linuxnix.com/abslute-path-vs-relative-path-in-linuxunix/" target="_blank" rel="noreferrer noopener">Absolute path&nbsp;vs&nbsp;relative&nbsp;path&nbsp;in&nbsp;Linux/Unix</a></p>



<p>Note that the returned canonical path must always begin&nbsp;with a slash&nbsp;<code>/</code>, and there must be only a single slash&nbsp;<code>/</code>&nbsp;between two directory names.&nbsp;The last directory name (if it exists)&nbsp;<strong>must not</strong>&nbsp;end with a trailing&nbsp;<code>/</code>. Also, the canonical path must be the&nbsp;<strong>shortest</strong>&nbsp;string&nbsp;representing the absolute path.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/home/"
<strong>Output: "</strong>/home"
<strong>Explanation:</strong> Note that there is no trailing slash after the last directory name.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/../"
<strong>Output: "</strong>/"
<strong>Explanation:</strong> Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/home//foo/"
<strong>Output: "</strong>/home/foo"
<strong>Explanation: </strong>In the canonical path, multiple consecutive slashes are replaced by a single one.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/a/./b/../../c/"
<strong>Output: "</strong>/c"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/a/../../b/../c//.//"
<strong>Output: "</strong>/c"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: "</strong>/a//b////c/d//././/.."
<strong>Output: "</strong>/a/b/c"</pre>



<h2><strong>Solution: Stack</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string simplifyPath(string path) {
    vector&lt;string&gt; s;
    int start = 1;
    for (int i = 1; i &lt;= path.length(); ++i) {
      if (i == path.length() || path[i] == '/') {
        string p = path.substr(start, i - start);
        if (p == &quot;/&quot;) continue;
        if (p == &quot;..&quot;) {
          if (!s.empty()) s.pop_back();
        } else if (p.length() &gt; 0 &amp;&amp; p != &quot;.&quot;) {
          s.push_back(std::move(p));
        }
        start = i + 1;
      }
    }

    string ans;
    for (int i = 0; i &lt; s.size(); ++i)
      ans += &quot;/&quot; + s[i];
    return ans.empty() ? &quot;/&quot; : ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-71-simplify-path/">花花酱 LeetCode 71. Simplify Path</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/stack/leetcode-71-simplify-path/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1209. Remove All Adjacent Duplicates in String II</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1209-remove-all-adjacent-duplicates-in-string-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1209-remove-all-adjacent-duplicates-in-string-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Sep 2019 07:47:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5597</guid>

					<description><![CDATA[<p>Given a string&#160;s, a&#160;k&#160;duplicate removal&#160;consists of choosing&#160;k&#160;adjacent and equal letters from&#160;s&#160;and removing&#160;them causing the left and the right side of the deleted substring to concatenate&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1209-remove-all-adjacent-duplicates-in-string-ii/">花花酱 LeetCode 1209. Remove All Adjacent Duplicates in String II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>, a&nbsp;<em>k</em>&nbsp;<em>duplicate removal</em>&nbsp;consists of choosing&nbsp;<code>k</code>&nbsp;adjacent and equal letters from&nbsp;<code>s</code>&nbsp;and removing&nbsp;them causing the left and the right side of the deleted substring to concatenate together.</p>



<p>We repeatedly make&nbsp;<code>k</code>&nbsp;duplicate removals on&nbsp;<code>s</code>&nbsp;until we no longer can.</p>



<p>Return the final string after all such duplicate removals have been made.</p>



<p>It is guaranteed that the answer is unique.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcd", k = 2
<strong>Output:</strong> "abcd"
<strong>Explanation: </strong>There's nothing to delete.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "deeedbbcccbdaa", k = 3
<strong>Output:</strong> "aa"
<strong>Explanation: 
</strong>First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"</pre>



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>2 &lt;= k &lt;= 10^4</code></li><li><code>s</code>&nbsp;only contains lower case English letters.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string removeDuplicates(string s, int k) {
    vector&lt;pair&lt;char, int&gt;&gt; st{{'*', 0}};
    for (char c : s)
      if (c != st.back().first)
        st.emplace_back(c, 1);
      else if (++st.back().second == k)
        st.pop_back();      
    string ans;
    for (const auto&amp; p : st)
      ans.append(p.second, p.first);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1209-remove-all-adjacent-duplicates-in-string-ii/">花花酱 LeetCode 1209. Remove All Adjacent Duplicates in String II</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/stack/leetcode-1209-remove-all-adjacent-duplicates-in-string-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Sep 2019 22:16:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5550</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;that consists of lower case English letters and brackets.&#160; Reverse the strings&#160;in each&#160;pair of matching parentheses, starting&#160;from the innermost one. Your result should&#160;not&#160;contain&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>&nbsp;that consists of lower case English letters and brackets.&nbsp;</p>



<p>Reverse the strings&nbsp;in each&nbsp;pair of matching parentheses, starting&nbsp;from the innermost one.</p>



<p>Your result should&nbsp;<strong>not</strong>&nbsp;contain any bracket.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(abcd)"
<strong>Output:</strong> "dcba"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(u(love)i)"
<strong>Output:</strong> "iloveu"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(ed(et(oc))el)"
<strong>Output:</strong> "leetcode"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a(bcdefghijkl(mno)p)q"
<strong>Output:</strong> "apmnolkjihgfedcbq"
</pre>



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



<ul><li><code>0 &lt;= s.length &lt;= 2000</code></li><li><code>s</code>&nbsp;only contains lower case English characters and parentheses.</li><li>It&#8217;s guaranteed that all parentheses are balanced.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>Use a stack of strings to track all the active strings.<br>Iterate over the input string:<br>1. Whenever there is a &#8216;(&#8216;, push an empty string to the stack.<br>2. Whenever this is a &#8216;)&#8217;, pop the top string and append the reverse of it to the new stack top.<br>3. Otherwise, append the letter to the string on top the of stack.<br><br>Once done, the (only) string on the top of the stack is the answer.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseParentheses(string s) {
    stack&lt;string&gt; st;
    st.push(&quot;&quot;);
    for (char c : s) {
      if (c == '(') st.push(&quot;&quot;);
      else if (c != ')') st.top() += c;
      else {
        string t = st.top(); st.pop();
        st.top().insert(end(st.top()), rbegin(t), rend(t));
      }
    }
    return st.top();
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</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/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1172. Dinner Plate Stacks</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1172-dinner-plate-stacks/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1172-dinner-plate-stacks/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Aug 2019 05:59:35 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5490</guid>

					<description><![CDATA[<p>You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same&#160;maximum&#160;capacity.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1172-dinner-plate-stacks/">花花酱 LeetCode 1172. Dinner Plate Stacks</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-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/DUsOp0HMQQg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same&nbsp;maximum&nbsp;<code>capacity</code>.</p>



<p>Implement the&nbsp;<code>DinnerPlates</code>&nbsp;class:</p>



<ul><li><code>DinnerPlates(int capacity)</code>&nbsp;Initializes the object with the maximum&nbsp;<code>capacity</code>&nbsp;of the stacks.</li><li><code>void push(int val)</code>&nbsp;pushes the given positive integer&nbsp;<code>val</code>&nbsp;into the leftmost stack with size less than&nbsp;<code>capacity</code>.</li><li><code>int pop()</code>&nbsp;returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns&nbsp;<code>-1</code>&nbsp;if all stacks are empty.</li><li><code>int popAtStack(int index)</code>&nbsp;returns the value at the top of the stack with the given&nbsp;<code>index</code>&nbsp;and removes it from that stack, and returns -1 if the stack with that&nbsp;given&nbsp;<code>index</code>&nbsp;is empty.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>
["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
[[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
<strong>Output: </strong>
</pre>


<p>[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]</p>



<pre class="wp-block-preformatted;crayon:false">
<p><strong>Explanation: </strong>
DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5);         // The stacks are now:  2 &nbsp;4
&nbsp;                                          1 &nbsp;3 &nbsp;5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 2.  The stacks are now:    &nbsp;4
            &nbsp;                                          1 &nbsp;3 &nbsp;5
                                                       ﹈ ﹈ ﹈
D.push(20);        // The stacks are now: 20  4
&nbsp;                                          1 &nbsp;3 &nbsp;5
                                           ﹈ ﹈ ﹈
D.push(21);        // The stacks are now: 20  4 21
&nbsp;                                          1 &nbsp;3 &nbsp;5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
             &nbsp;                                          1 &nbsp;3 &nbsp;5
                                                        ﹈ ﹈ ﹈
D.popAtStack(2);   // Returns 21.  The stacks are now:     4
             &nbsp;                                          1 &nbsp;3 &nbsp;5
                                                        ﹈ ﹈ ﹈ 
D.pop()            // Returns 5.  The stacks are now:      4
             &nbsp;                                          1 &nbsp;3 
                                                        ﹈ ﹈  
D.pop()            // Returns 4.  The stacks are now:   1 &nbsp;3 
                                                        ﹈ ﹈   
D.pop()            // Returns 3.  The stacks are now:   1 
                                                        ﹈   
D.pop()            // Returns 1.  There are no stacks.
D.pop()            // Returns -1.  There are still no stacks.
</p>
</pre>



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



<ul><li><code>1 &lt;= capacity&nbsp;&lt;= 20000</code></li><li><code>1 &lt;= val&nbsp;&lt;= 20000</code></li><li><code>0 &lt;= index&nbsp;&lt;= 100000</code></li><li>At most&nbsp;<code>200000</code>&nbsp;calls will be made to&nbsp;<code>push</code>,&nbsp;<code>pop</code>, and&nbsp;<code>popAtStack</code>.</li></ul>



<h2><strong>Solution: Array of stacks + TreeSet</strong></h2>



<p>Store all the stacks in an array, and store the indices of all free stacks in a tree set.<br>1. push(): find the first free stack and push onto it, if it becomes full, remove it from free set.<br>2. pop(): pop element from the last stack by calling popAtIndex(stacks.size()-1).<br>3. popAtIndex(): pop element from given index<br>  3.1 add it to free set if it was full <br>  3.2 remove it from free set if it becomes empty <br>     3.2.1 remove it from stack array if it is the last stack</p>



<p>Time complexity:  <br>Push: O(logn)<br>Pop: O(logn)<br>PopAtIndex: O(logn)</p>



<p>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 DinnerPlates {
public:
  DinnerPlates(int capacity): cap_(capacity) {}

  void push(int val) {  
    int index = aval_.empty() ? stacks_.size() : *begin(aval_);
    if (index == stacks_.size()) stacks_.emplace_back();
    stack&lt;int&gt;&amp; s = stacks_[index];
    s.push(val);
    if (s.size() == cap_)
      aval_.erase(index);
    else if (s.size() == 1) // only insert for the first element
      aval_.insert(index);
  }

  int pop() { return popAtStack(stacks_.size() - 1); }

  int popAtStack(int index) {
    if (index &lt; 0 || index &gt;= stacks_.size() || stacks_[index].empty()) return -1;
    stack&lt;int&gt;&amp; s = stacks_[index];
    int val = s.top(); s.pop();
    if (s.size() == cap_ - 1) aval_.insert(index);    
    
    // Amortized O(1)
    auto it = prev(end(aval_));
    while (stacks_.size() &amp;&amp; stacks_.back().empty()) {
      stacks_.pop_back();
      aval_.erase(it--);
    }
    return val;
  }
private:
  int cap_;
  set&lt;int&gt; aval_;
  vector&lt;stack&lt;int&gt;&gt; stacks_;
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1172-dinner-plate-stacks/">花花酱 LeetCode 1172. Dinner Plate Stacks</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/stack/leetcode-1172-dinner-plate-stacks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 232. Implement Queue using Stacks</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-232-implement-queue-using-stacks/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-232-implement-queue-using-stacks/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 23 Jul 2019 05:10:16 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5334</guid>

					<description><![CDATA[<p>Implement the following operations of a queue using stacks. push(x) &#8212; Push element x to the back of queue. pop() &#8212; Removes the element from&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-232-implement-queue-using-stacks/">花花酱 LeetCode 232. Implement Queue using Stacks</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 following operations of a queue using stacks.</p>



<ul><li>push(x) &#8212; Push element x to the back of queue.</li><li>pop() &#8212; Removes the element from in front of queue.</li><li>peek() &#8212; Get the front element.</li><li>empty() &#8212; Return whether the queue is empty.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false">MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false</pre>



<p><strong>Notes:</strong></p>



<ul><li>You must use&nbsp;<em>only</em>&nbsp;standard operations of a stack &#8212; which means only&nbsp;<code>push to top</code>,&nbsp;<code>peek/pop from top</code>,&nbsp;<code>size</code>, and&nbsp;<code>is empty</code>&nbsp;operations are valid.</li><li>Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.</li><li>You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).</li></ul>



<h2><strong>Solution: Use two stacks</strong></h2>



<p>amortized cost: O(1)</p>



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

<pre class="crayon-plain-tag">class MyQueue {
public:
  /** Initialize your data structure here. */
  MyQueue() {}

  /** Push element x to the back of queue. */
  void push(int x) {
    s1_.push(x);
  }

  /** Removes the element from in front of queue and returns that element. */
  int pop() {
    if (s2_.empty()) move();
    int top = s2_.top();
    s2_.pop();
    return top;
  }

  /** Get the front element. */
  int peek() {
    if (s2_.empty()) move();
    return s2_.top();
  }

  /** Returns whether the queue is empty. */
  bool empty() {
    return s1_.empty() &amp;&amp; s2_.empty();
  }
private:
  stack&lt;int&gt; s1_;
  stack&lt;int&gt; s2_;
  
  void move() {
    while (!s1_.empty()) {
      s2_.push(s1_.top());
      s1_.pop();
    }
  }    
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-232-implement-queue-using-stacks/">花花酱 LeetCode 232. Implement Queue using Stacks</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/stack/leetcode-232-implement-queue-using-stacks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
