<?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/tag/stack/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/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/tag/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 173. Binary Search Tree Iterator</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 05:18:12 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[in order]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8908</guid>

					<description><![CDATA[<p>Implement the&#160;BSTIterator&#160;class that represents an iterator over the&#160;in-order traversal&#160;of a binary search tree (BST): BSTIterator(TreeNode root)&#160;Initializes an object of the&#160;BSTIterator&#160;class. The&#160;root&#160;of the BST is given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/">花花酱 LeetCode 173. Binary Search Tree Iterator</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&nbsp;<code>BSTIterator</code>&nbsp;class that represents an iterator over the&nbsp;<strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank" rel="noreferrer noopener">in-order traversal</a></strong>&nbsp;of a binary search tree (BST):</p>



<ul><li><code>BSTIterator(TreeNode root)</code>&nbsp;Initializes an object of the&nbsp;<code>BSTIterator</code>&nbsp;class. The&nbsp;<code>root</code>&nbsp;of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li><li><code>boolean hasNext()</code>&nbsp;Returns&nbsp;<code>true</code>&nbsp;if there exists a number in the traversal to the right of the pointer, otherwise returns&nbsp;<code>false</code>.</li><li><code>int next()</code>&nbsp;Moves the pointer to the right, then returns the number at the pointer.</li></ul>



<p>Notice that by initializing the pointer to a non-existent smallest number, the first call to&nbsp;<code>next()</code>&nbsp;will return the smallest element in the BST.</p>



<p>You may assume that&nbsp;<code>next()</code>&nbsp;calls will always be valid. That is, there will be at least a next number in the in-order traversal when&nbsp;<code>next()</code>&nbsp;is called.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
<strong>Output</strong>
</pre>


<p>[null, 3, 7, true, 9, true, 15, true, 20, false]</p>



<p><strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False</p>



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



<ul><li>The number of nodes in the tree is in the range&nbsp;<code>[1, 10<sup>5</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li>At most&nbsp;<code>10<sup>5</sup></code>&nbsp;calls will be made to&nbsp;<code>hasNext</code>, and&nbsp;<code>next</code>.</li></ul>



<p><strong>Follow up:</strong></p>



<ul><li>Could you implement&nbsp;<code>next()</code>&nbsp;and&nbsp;<code>hasNext()</code>&nbsp;to run in average&nbsp;<code>O(1)</code>&nbsp;time and use&nbsp;<code>O(h)</code>&nbsp;memory, where&nbsp;<code>h</code>&nbsp;is the height of the tree?</li></ul>



<h2><strong>Solution: In-order traversal using a stack</strong></h2>



<p>Use a stack to simulate in-order traversal.</p>



<p>Each next, we walk to the left most (smallest) node and push all the nodes along the path to the stack.</p>



<p>Then pop the top one t as return val, our next node to explore is the right child of t.</p>



<p>Time complexity: amortized O(1) for next() call.<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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
public:
  BSTIterator(TreeNode* root) : root_(root) {}

  int next() {
    while (root_) {
      s_.push(root_);
      root_ = root_-&gt;left;
    }
    TreeNode* t = s_.top(); s_.pop();
    root_ = t-&gt;right;
    return t-&gt;val;
  }

  bool hasNext() {
    return (root_ || !s_.empty());
  }
private:
  TreeNode* root_;
  stack&lt;TreeNode*&gt; s_;
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj-&gt;next();
 * bool param_2 = obj-&gt;hasNext();
 */</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/">花花酱 LeetCode 173. Binary Search Tree Iterator</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-173-binary-search-tree-iterator/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 1717. Maximum Score From Removing Substrings</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1717-maximum-score-from-removing-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1717-maximum-score-from-removing-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 03:12:39 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[removal]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7947</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;and two integers&#160;x&#160;and&#160;y. You can perform two types of operations any number of times. Remove substring&#160;"ab"&#160;and gain&#160;x&#160;points. For example, when removing&#160;"ab"&#160;from&#160;"cabxbae"&#160;it&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1717-maximum-score-from-removing-substrings/">花花酱 LeetCode 1717. Maximum Score From Removing Substrings</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 a string&nbsp;<code>s</code>&nbsp;and two integers&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>. You can perform two types of operations any number of times.</p>



<ul><li>Remove substring&nbsp;<code>"ab"</code>&nbsp;and gain&nbsp;<code>x</code>&nbsp;points.<ul><li>For example, when removing&nbsp;<code>"ab"</code>&nbsp;from&nbsp;<code>"c<u>ab</u>xbae"</code>&nbsp;it becomes&nbsp;<code>"cxbae"</code>.</li></ul></li><li>Remove substring&nbsp;<code>"ba"</code>&nbsp;and gain&nbsp;<code>y</code>&nbsp;points.<ul><li>For example, when removing&nbsp;<code>"ba"</code>&nbsp;from&nbsp;<code>"cabx<u>ba</u>e"</code>&nbsp;it becomes&nbsp;<code>"cabxe"</code>.</li></ul></li></ul>



<p>Return&nbsp;<em>the maximum points you can gain after applying the above operations on</em>&nbsp;<code>s</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "cdbcbbaaabab", x = 4, y = 5
<strong>Output:</strong> 19
<strong>Explanation:</strong>
- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabbaaxybbaabb", x = 5, y = 4
<strong>Output:</strong> 20
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= x, y &lt;= 10<sup>4</sup></code></li><li><code>s</code>&nbsp;consists of lowercase English letters.</li></ul>



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



<p>Remove the pattern with the larger score first.</p>



<p>Using a stack to remove all occurrences of a pattern in place in O(n) Time.</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 maximumGain(string s, int x, int y) {
    // Remove patttern p from s for t points each.
    // Returns the total score.
    auto remove = [&amp;](const string&amp; p, int t) {
      int total = 0;
      int i = 0;
      for (int j = 0; j &lt; s.size(); ++j, ++i) {
        s[i] = s[j];
        if (i &amp;&amp; s[i - 1] == p[0] &amp;&amp; s[i] == p[1]) {
          i -= 2;
          total += t;
        }
      }
      s.resize(i); 
      return total;
    };
    string px{&quot;ab&quot;};
    string py{&quot;ba&quot;};
    if (y &gt; x) {
      swap(px, py);
      swap(x, y);
    }    
    return remove(px, x) + remove(py, y);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1717-maximum-score-from-removing-substrings/">花花酱 LeetCode 1717. Maximum Score From Removing Substrings</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/greedy/leetcode-1717-maximum-score-from-removing-substrings/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 1504. Count Submatrices With All Ones</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1504-count-submatrices-with-all-ones/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1504-count-submatrices-with-all-ones/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Jul 2020 20:48:28 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7031</guid>

					<description><![CDATA[<p>Given a&#160;rows * columns&#160;matrix&#160;mat&#160;of ones and zeros, return how many&#160;submatrices&#160;have all ones. Example 1: Input: mat = [[1,0,1], &#160; [1,1,0], &#160; [1,1,0]] Output: 13 Explanation:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1504-count-submatrices-with-all-ones/">花花酱 LeetCode 1504. Count Submatrices With All Ones</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<code>rows * columns</code>&nbsp;matrix&nbsp;<code>mat</code>&nbsp;of ones and zeros, return how many&nbsp;<strong>submatrices</strong>&nbsp;have all ones.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,0,1],
&nbsp;             [1,1,0],
&nbsp;             [1,1,0]]
<strong>Output:</strong> 13
<strong>Explanation:
</strong>There are <strong>6</strong> rectangles of side 1x1.
There are <strong>2</strong> rectangles of side 1x2.
There are <strong>3</strong> rectangles of side 2x1.
There is <strong>1</strong> rectangle of side 2x2. 
There is <strong>1</strong> rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = <strong>13.</strong>
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,1,1,0],
&nbsp;             [0,1,1,1],
&nbsp;             [1,1,1,0]]
<strong>Output:</strong> 24
<strong>Explanation:</strong>
There are <strong>8</strong> rectangles of side 1x1.
There are <strong>5</strong> rectangles of side 1x2.
There are <strong>2</strong> rectangles of side 1x3. 
There are <strong>4</strong> rectangles of side 2x1.
There are <strong>2</strong> rectangles of side 2x2. 
There are <strong>2</strong> rectangles of side 3x1. 
There is <strong>1</strong> rectangle of side 3x2. 
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24<strong>.</strong>
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,1,1,1,1,1]]
<strong>Output:</strong> 21
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,0,1],[0,1,0],[1,0,1]]
<strong>Output:</strong> 5
</pre>



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



<ul><li><code>1 &lt;= rows &lt;= 150</code></li><li><code>1 &lt;= columns &lt;= 150</code></li><li><code>0 &lt;= mat[i][j] &lt;= 1</code></li></ul>



<h2><strong>Solution 1: Brute Force w/ Pruning</strong></h2>



<p>Time complexity: O(m^2*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:
  int numSubmat(vector&lt;vector&lt;int&gt;&gt;&amp; mat) {    
    const int R = mat.size();
    const int C = mat[0].size();
    // # of sub matrices with top-left at (sr, sc)
    auto subMats = [&amp;](int sr, int sc) {
      int max_c = C;
      int count = 0;
      for (int r = sr; r &lt; R; ++r)
        for (int c = sc; c &lt; max_c; ++c)
          if (mat[r][c]) {
            ++count;
          } else {
            max_c = c;
          }
      return count;
    };    
    int ans = 0;
    for (int r = 0; r &lt; R; ++r)
      for (int c = 0; c &lt; C; ++c)
        ans += subMats(r, c);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1504-count-submatrices-with-all-ones/">花花酱 LeetCode 1504. Count Submatrices With All Ones</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1504-count-submatrices-with-all-ones/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1441. Build an Array With Stack Operations</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1441-build-an-array-with-stack-operations/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1441-build-an-array-with-stack-operations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 11 May 2020 20:19:14 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6736</guid>

					<description><![CDATA[<p>Given an array&#160;target&#160;and&#160;an integer&#160;n. In each iteration, you will read a number from &#160;list = {1,2,3..., n}. Build the&#160;target&#160;array&#160;using the following operations: Push: Read a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1441-build-an-array-with-stack-operations/">花花酱 LeetCode 1441. Build an Array With Stack 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[
<p>Given an array&nbsp;<code>target</code>&nbsp;and&nbsp;an integer&nbsp;<code>n</code>. In each iteration, you will read a number from &nbsp;<code>list = {1,2,3..., n}</code>.</p>



<p>Build the&nbsp;<code>target</code>&nbsp;array&nbsp;using the following operations:</p>



<ul><li><strong>Push</strong>: Read a new element from the beginning&nbsp;<code>list</code>, and push it in the array.</li><li><strong>Pop</strong>: delete the last element of&nbsp;the array.</li><li>If the target array is already&nbsp;built, stop reading more elements.</li></ul>



<p>You are guaranteed that the target array is strictly&nbsp;increasing, only containing&nbsp;numbers between 1 to&nbsp;<code>n</code>&nbsp;inclusive.</p>



<p>Return the operations to build the target array.</p>



<p>You are guaranteed that the answer is unique.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = [1,3], n = 3
<strong>Output:</strong> ["Push","Push","Pop","Push"]
<strong>Explanation: 
</strong>Read number 1 and automatically push in the array -&gt; [1]
Read number 2 and automatically push in the array then Pop it -&gt; [1]
Read number 3 and automatically push in the array -&gt; [1,3]
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = [1,2], n = 4
<strong>Output:</strong> ["Push","Push"]
<strong>Explanation: </strong>You only need to read the first 2 numbers and stop.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = [2,3,4], n = 4
<strong>Output:</strong> ["Push","Pop","Push","Push","Push"]
</pre>



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



<ul><li><code>1 &lt;= target.length &lt;= 100</code></li><li><code>1 &lt;= target[i]&nbsp;&lt;= 100</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li><code>target</code>&nbsp;is strictly&nbsp;increasing.</li></ul>



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



<p>For each number in target, keep discarding i if i != num by &#8220;Push&#8221; + &#8220;Pop&#8221;, until i == num. One more &#8220;Push&#8221;.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n) or O(1) w/o output.</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;string&gt; buildArray(vector&lt;int&gt;&amp; target, int n) {
    vector&lt;string&gt; ans;
    int i = 1;
    for (int num : target) {      
      while (i != num) {
        ans.push_back(&quot;Push&quot;);     
        ans.push_back(&quot;Pop&quot;);
        ++i;
      }
      ans.push_back(&quot;Push&quot;);
      ++i;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1441-build-an-array-with-stack-operations/">花花酱 LeetCode 1441. Build an Array With Stack 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/simulation/leetcode-1441-build-an-array-with-stack-operations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1419. Minimum Number of Frogs Croaking</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1419-minimum-number-of-frogs-croaking/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1419-minimum-number-of-frogs-croaking/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 07:58:46 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6649</guid>

					<description><![CDATA[<p>Given the string&#160;croakOfFrogs, which represents a combination of the string &#8220;croak&#8221; from different frogs, that is, multiple frogs can croak at the same time, so&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1419-minimum-number-of-frogs-croaking/">花花酱 LeetCode 1419. Minimum Number of Frogs Croaking</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 the string&nbsp;<code>croakOfFrogs</code>, which represents a combination of the string &#8220;croak&#8221; from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed.&nbsp;<em>Return the minimum number of&nbsp;</em>different<em>&nbsp;frogs to finish all the croak in the given string.</em></p>



<p>A valid &#8220;croak&#8221;&nbsp;means a frog is printing 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’&nbsp;<strong>sequentially</strong>.&nbsp;The frogs have to print all five letters to finish a croak.&nbsp;If the given string is not a combination of valid&nbsp;&#8220;croak&#8221;&nbsp;return -1.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> croakOfFrogs = "croakcroak"
<strong>Output:</strong> 1 
<strong>Explanation:</strong> One frog yelling "croak<strong>"</strong> twice.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> croakOfFrogs = "crcoakroak"
<strong>Output:</strong> 2 
<strong>Explanation:</strong> The minimum number of frogs is two.&nbsp;
The first frog could yell "<strong>cr</strong>c<strong>oak</strong>roak".
The second frog could yell later "cr<strong>c</strong>oak<strong>roak</strong>".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> croakOfFrogs = "croakcrook"
<strong>Output:</strong> -1
<strong>Explanation:</strong> The given string is an invalid combination of "croak<strong>"</strong> from different frogs.
</pre>



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



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



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



<ul><li><code>1 &lt;=&nbsp;croakOfFrogs.length &lt;= 10^5</code></li><li>All characters in the string are:&nbsp;<code>'c'</code>,&nbsp;<code>'r'</code>,&nbsp;<code>'o'</code>,&nbsp;<code>'a'</code>&nbsp;or&nbsp;<code>'k'</code>.</li></ul>



<h2><strong>Solution: Hashtable</strong></h2>



<p>Count the frequency of the letters, we need to make sure f[c] &gt;= f[r] &gt;= f[o] &gt;= f[a] &gt;= f[k] holds all the time, otherwise return -1.<br>whenever encounter c, increase the current frog, whenever there is k, decrease the frog count.<br>Don&#8217;t forget to check the current frog number, should be 0 in the end, otherwise there are open letters.</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 minNumberOfFrogs(string croakOfFrogs) {
    vector&lt;int&gt; idx(26);
    idx['c' - 'a'] = 0;
    idx['r' - 'a'] = 1;
    idx['o' - 'a'] = 2;
    idx['a' - 'a'] = 3;
    idx['k' - 'a'] = 4;
    vector&lt;int&gt; count(5);
    int cur = 0;
    int ans = 0;    
    for (char ch : croakOfFrogs) {
      const int i = idx[ch - 'a'];
      ++count[i];
      if (ch == 'c') {
        ans = max(ans, ++cur);
        continue;
      }
      if (count[i] &gt; count[i - 1]) return -1;
      if (ch == 'k') --cur;
    }
    return cur ? -1 : ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1419-minimum-number-of-frogs-croaking/">花花酱 LeetCode 1419. Minimum Number of Frogs Croaking</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/hashtable/leetcode-1419-minimum-number-of-frogs-croaking/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1417. Reformat The String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 07:13:16 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[interleaving]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6643</guid>

					<description><![CDATA[<p>Given alphanumeric string&#160;s. (Alphanumeric string&#160;is a string consisting of lowercase English letters and digits). You have to find a permutation of&#160;the string where no letter&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/">花花酱 LeetCode 1417. Reformat The String</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 alphanumeric string&nbsp;<code>s</code>. (<strong>Alphanumeric string</strong>&nbsp;is a string consisting of lowercase English letters and digits).</p>



<p>You have to find a permutation of&nbsp;the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.</p>



<p>Return&nbsp;<em>the reformatted string</em>&nbsp;or return&nbsp;<strong>an empty string</strong>&nbsp;if it is impossible to reformat the string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a0b1c2"
<strong>Output:</strong> "0a1b2c"
<strong>Explanation:</strong> No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcode"
<strong>Output:</strong> ""
<strong>Explanation:</strong> "leetcode" has only characters so we cannot separate them by digits.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1229857369"
<strong>Output:</strong> ""
<strong>Explanation:</strong> "1229857369" has only digits so we cannot separate them by characters.
</pre>



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



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



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



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



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



<ul><li><code>1 &lt;= s.length &lt;= 500</code></li><li><code>s</code>&nbsp;consists of only lowercase English letters and/or digits.</li></ul>



<h2><strong>Solution: Two streams</strong></h2>



<p>Create two stacks, one for alphas, another for numbers. If the larger stack has more than one element than the other one then no solution, return &#8220;&#8221;. Otherwise, interleave two stacks, start with the larger one.</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:
  string reformat(string s) {
    string q1;
    string q2;
    for (char c : s) {
      if (isalpha(c))
        q1 += c;
      else
        q2 += c;
    }    
    if (q1.length() &lt; q2.length())
      swap(q1, q2);
    if (q1.length() &gt; q2.length() + 1) 
      return &quot;&quot;;
    string ans;
    while (!q1.empty()) {
      ans += q1.back();
      q1.pop_back();
      if (q2.empty()) break;
      ans += q2.back();
      q2.pop_back();
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/">花花酱 LeetCode 1417. Reformat The String</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-1417-reformat-the-string/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>
	</channel>
</rss>
