<?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>Simulation &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/simulation/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 11 Apr 2025 04:04:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Simulation &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2011. Final Value of Variable After Performing Operations</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2011-final-value-of-variable-after-performing-operations/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2011-final-value-of-variable-after-performing-operations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 11 Apr 2025 04:04:13 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10322</guid>

					<description><![CDATA[C++ 也能写one-liner了。 时间复杂度：O(n)空间复杂度：O(1) [crayon-67fb702f48c7a722185459/]]]></description>
										<content:encoded><![CDATA[
<p>C++ 也能写one-liner了。</p>



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



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int finalValueAfterOperations(vector&lt;string&gt;&amp; operations) {
    return accumulate(begin(operations), end(operations), 0, [](const auto s, const auto&amp; op){
      return s + (op[1] == '+' ? 1 : -1);
    });
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2011-final-value-of-variable-after-performing-operations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1992. Find All Groups of Farmland</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1992-find-all-groups-of-farmland/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1992-find-all-groups-of-farmland/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 11 Apr 2025 03:34:14 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10315</guid>

					<description><![CDATA[已经告诉你所有的农田都是规整的矩形，题目难度一下子降低了。对于每一个农田的左上角，找到它的宽度和高度即可。然后把整个农田矩形标记为林地/非农田即可。 时间复杂度：O(m*n) 每个格子最多遍历3遍。空间复杂度：O(1) [crayon-67fb702f4a112602059590/]]]></description>
										<content:encoded><![CDATA[
<p>已经告诉你所有的农田都是规整的矩形，题目难度一下子降低了。<br>对于每一个农田的左上角，找到它的宽度和高度即可。<br>然后把整个农田矩形标记为林地/非农田即可。</p>



<p>时间复杂度：O(m*n) 每个格子最多遍历3遍。<br>空间复杂度：O(1)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; findFarmland(vector&lt;vector&lt;int&gt;&gt;&amp; land) {
    const int m = land.size();
    const int n = land[0].size();
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        if (!land[i][j]) continue;
        int w = 0;
        int h = 0;
        while (j + w &lt; n &amp;&amp; land[i][j + w]) ++w;
        while (i + h &lt; m &amp;&amp; land[i + h][j]) ++h;
        ans.push_back({i, j, i + h - 1, j + w - 1});
        for (int p = 0; p &lt; h; ++p)
          for (int q = 0; q &lt; w; ++q)
            land[i + p][j + q] = 0; // mark as seen.
      }
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1992-find-all-groups-of-farmland/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3028. Ant on the Boundary</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-3028-ant-on-the-boundary/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-3028-ant-on-the-boundary/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 06 Feb 2024 01:49:25 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10110</guid>

					<description><![CDATA[An ant is on a boundary. It sometimes goes&#160;left&#160;and sometimes&#160;right. You are given an array of&#160;non-zero&#160;integers&#160;nums. The ant starts reading&#160;nums&#160;from the first element of it&#8230;]]></description>
										<content:encoded><![CDATA[
<p>An ant is on a boundary. It sometimes goes&nbsp;<strong>left</strong>&nbsp;and sometimes&nbsp;<strong>right</strong>.</p>



<p>You are given an array of&nbsp;<strong>non-zero</strong>&nbsp;integers&nbsp;<code>nums</code>. The ant starts reading&nbsp;<code>nums</code>&nbsp;from the first element of it to its end. At each step, it moves according to the value of the current element:</p>



<ul class="wp-block-list"><li>If&nbsp;<code>nums[i] &lt; 0</code>, it moves&nbsp;<strong>left</strong>&nbsp;by&nbsp;<code>-nums[i]</code>&nbsp;units.</li><li>If&nbsp;<code>nums[i] &gt; 0</code>, it moves&nbsp;<strong>right</strong>&nbsp;by&nbsp;<code>nums[i]</code>&nbsp;units.</li></ul>



<p>Return&nbsp;<em>the number of times the ant&nbsp;<strong>returns</strong>&nbsp;to the boundary.</em></p>



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



<ul class="wp-block-list"><li>There is an infinite space on both sides of the boundary.</li><li>We check whether the ant is on the boundary only after it has moved&nbsp;<code>|nums[i]|</code>&nbsp;units. In other words, if the ant crosses the boundary during its movement, it does not count.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is 2 steps to the right of the boundary.
After the fourth step, the ant is 2 steps to the left of the boundary.
The ant never returned to the boundary, so the answer is 0.
</pre>



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



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



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



<p>Simulate the position of the ant by summing up the numbers. If the position is zero (at boundary), increase the answer by 1.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int returnToBoundaryCount(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    int pos = 0;
    for (int x : nums)
      ans += !(pos += x);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-3028-ant-on-the-boundary/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2660. Determine the Winner of a Bowling Game</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2660-determine-the-winner-of-a-bowling-game/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2660-determine-the-winner-of-a-bowling-game/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 16:41:18 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10036</guid>

					<description><![CDATA[You are given two&#160;0-indexed&#160;integer arrays&#160;player1&#160;and&#160;player2, that represent the number of pins that player 1 and player 2 hit in a bowling game, respectively. The bowling&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>0-indexed</strong>&nbsp;integer arrays&nbsp;<code>player1</code>&nbsp;and&nbsp;<code>player2</code>, that represent the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p>



<p>The bowling game consists of&nbsp;<code>n</code>&nbsp;turns, and the number of pins in each turn is exactly&nbsp;<code>10</code>.</p>



<p>Assume a player hit&nbsp;<code>x<sub>i</sub></code>&nbsp;pins in the&nbsp;<code>i<sup>th</sup></code>&nbsp;turn. The value of the&nbsp;<code>i<sup>th</sup></code>&nbsp;turn for the player is:</p>



<ul class="wp-block-list"><li><code>2x<sub>i</sub></code>&nbsp;if the player hit&nbsp;<code>10</code>&nbsp;pins in any of the previous two turns.</li><li>Otherwise, It is&nbsp;<code>x<sub>i</sub></code>.</li></ul>



<p>The score of the player is the sum of the values of their&nbsp;<code>n</code>&nbsp;turns.</p>



<p>Return</p>



<ul class="wp-block-list"><li><code>1</code>&nbsp;<em>if the score of player 1 is more than the score of player 2,</em></li><li><code>2</code>&nbsp;<em>if the score of player 2 is more than the score of player 1, and</em></li><li><code>0</code>&nbsp;<em>in case of a draw.</em></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> player1 = [4,10,7,9], player2 = [6,5,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The score of player1 is 4 + 10 + 2*7 + 2*9 = 46.
The score of player2 is 6 + 5 + 2 + 3 = 16.
Score of player1 is more than the score of player2, so, player1 is the winner, and the answer is 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> player1 = [3,5,7,6], player2 = [8,10,10,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The score of player1 is 3 + 5 + 7 + 6 = 21.
The score of player2 is 8 + 10 + 2*10 + 2*2 = 42.
Score of player2 is more than the score of player1, so, player2 is the winner, and the answer is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> player1 = [2,3], player2 = [4,1]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The score of player1 is 2 + 3 = 5
The score of player2 is 4 + 1 = 5
The score of player1 equals to the score of player2, so, there is a draw, and the answer is 0.
</pre>



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



<ul class="wp-block-list"><li><code>n == player1.length == player2.length</code></li><li><code>1 &lt;= n &lt;= 1000</code></li><li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li></ul>



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



<p>We can write a function to compute the score of a player.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int isWinner(vector&lt;int&gt;&amp; player1, vector&lt;int&gt;&amp; player2) {
    auto score = [] (const vector&lt;int&gt;&amp; player) {
      int sum = 0;
      int twice = 0;
      for (int x : player) {        
        sum += twice-- &gt; 0 ? x * 2 : x;
        if (x == 10) twice = 2;
      }
      return sum;
    };
    int s1 = score(player1);
    int s2 = score(player2);
    if (s1 == s2) return 0;
    return s1 &gt; s2 ? 1 : 2;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2660-determine-the-winner-of-a-bowling-game/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2639. Find the Width of Columns of a Grid</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Apr 2023 15:22:36 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[length]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[width]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10006</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;m x n&#160;integer matrix&#160;grid. The width of a column is the maximum&#160;length&#160;of its integers. For example, if&#160;grid = [[-10], [3], [12]], the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code>&nbsp;integer matrix&nbsp;<code>grid</code>. The width of a column is the maximum&nbsp;<strong>length&nbsp;</strong>of its integers.</p>



<ul class="wp-block-list"><li>For example, if&nbsp;<code>grid = [[-10], [3], [12]]</code>, the width of the only column is&nbsp;<code>3</code>&nbsp;since&nbsp;<code>-10</code>&nbsp;is of length&nbsp;<code>3</code>.</li></ul>



<p>Return&nbsp;<em>an integer array</em>&nbsp;<code>ans</code>&nbsp;<em>of size</em>&nbsp;<code>n</code>&nbsp;<em>where</em>&nbsp;<code>ans[i]</code>&nbsp;<em>is the width of the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>column</em>.</p>



<p>The&nbsp;<strong>length</strong>&nbsp;of an integer&nbsp;<code>x</code>&nbsp;with&nbsp;<code>len</code>&nbsp;digits is equal to&nbsp;<code>len</code>&nbsp;if&nbsp;<code>x</code>&nbsp;is non-negative, and&nbsp;<code>len + 1</code>&nbsp;otherwise.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1],[22],[333]]
<strong>Output:</strong> [3]
<strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]]
<strong>Output:</strong> [3,1,2]
<strong>Explanation:</strong> 
In the 0<sup>th</sup> column, only -15 is of length 3.
In the 1<sup>st</sup> column, all integers are of length 1. 
In the 2<sup>nd</sup> column, both 12 and -2 are of length 2.
</pre>



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



<ul class="wp-block-list"><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 100</code></li><li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li></ul>



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



<p>Note: width of &#8216;0&#8217; is 1.</p>



<p>Time complexity: O(m*n*log(x))<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findColumnWidth(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    vector&lt;int&gt; ans;
    for (int j = 0; j &lt; grid[0].size(); ++j) {
      int maxWidth = 1;
      for (int i = 0; i &lt; grid.size(); ++i) {
        int x = grid[i][j];
        int width = 0;        
        if (x &lt; 0) {
          x = -x;
          ++width;
        }
        while (x) {
          x /= 10;
          ++width;
        }        
        maxWidth = max(maxWidth, width);
      }
      ans.push_back(maxWidth);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2257. Count Unguarded Cells in the Grid</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2257-count-unguarded-cells-in-the-grid/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2257-count-unguarded-cells-in-the-grid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 May 2022 05:37:13 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9710</guid>

					<description><![CDATA[You are given two integers&#160;m&#160;and&#160;n&#160;representing a&#160;0-indexed&#160;m x n&#160;grid. You are also given two 2D integer arrays&#160;guards&#160;and&#160;walls&#160;where&#160;guards[i] = [rowi, coli]&#160;and&#160;walls[j] = [rowj, colj]&#160;represent the positions of&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two integers&nbsp;<code>m</code>&nbsp;and&nbsp;<code>n</code>&nbsp;representing a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code>&nbsp;grid. You are also given two 2D integer arrays&nbsp;<code>guards</code>&nbsp;and&nbsp;<code>walls</code>&nbsp;where&nbsp;<code>guards[i] = [row<sub>i</sub>, col<sub>i</sub>]</code>&nbsp;and&nbsp;<code>walls[j] = [row<sub>j</sub>, col<sub>j</sub>]</code>&nbsp;represent the positions of the&nbsp;<code>i<sup>th</sup></code>&nbsp;guard and&nbsp;<code>j<sup>th</sup></code>&nbsp;wall respectively.</p>



<p>A guard can see&nbsp;<strong>every</strong>&nbsp;cell in the four cardinal directions (north, east, south, or west) starting from their position unless&nbsp;<strong>obstructed</strong>&nbsp;by a wall or another guard. A cell is&nbsp;<strong>guarded</strong>&nbsp;if there is&nbsp;<strong>at least</strong>&nbsp;one guard that can see it.</p>



<p>Return<em>&nbsp;the number of unoccupied cells that are&nbsp;<strong>not</strong>&nbsp;<strong>guarded</strong>.</em></p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/03/10/example1drawio2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The guarded and unguarded cells are shown in red and green respectively in the above diagram.
There are a total of 7 unguarded cells, so we return 7.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/03/10/example2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The unguarded cells are shown in green in the above diagram.
There are a total of 4 unguarded cells, so we return 4.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= guards.length, walls.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>2 &lt;= guards.length + walls.length &lt;= m * n</code></li><li><code>guards[i].length == walls[j].length == 2</code></li><li><code>0 &lt;= row<sub>i</sub>, row<sub>j</sub>&nbsp;&lt; m</code></li><li><code>0 &lt;= col<sub>i</sub>, col<sub>j</sub>&nbsp;&lt; n</code></li><li>All the positions in&nbsp;<code>guards</code>&nbsp;and&nbsp;<code>walls</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



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



<p>Enumerate each cell, for each guard, shoot rays to 4 directions, mark cells on the way to 1 and stop when hit a guard or a wall. </p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countUnguarded(int m, int n, vector&lt;vector&lt;int&gt;&gt;&amp; guards, vector&lt;vector&lt;int&gt;&gt;&amp; walls) {
    vector&lt;vector&lt;int&gt;&gt; s(m, vector&lt;int&gt;(n));
    for (const auto&amp; g : guards)
      s[g[0]][g[1]] = 2;
    
    for (const auto&amp; w : walls)
      s[w[0]][w[1]] = 3;
    
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        if (s[i][j] != 2) continue;
        for (int y = i - 1; y &gt;= 0; s[y--][j] = 1)
          if (s[y][j] &gt;= 2) break;          
        for (int y = i + 1; y &lt; m; s[y++][j] = 1)
          if (s[y][j] &gt;= 2) break;        
        for (int x = j - 1; x &gt;= 0; s[i][x--] = 1)
          if (s[i][x] &gt;= 2) break;    
        for (int x = j + 1; x &lt; n; s[i][x++] = 1)
          if (s[i][x] &gt;= 2) break;          
      }    
    int ans = 0;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        ans += !s[i][j];
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2257-count-unguarded-cells-in-the-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2221. Find Triangular Sum of an Array</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2221-find-triangular-sum-of-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2221-find-triangular-sum-of-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 02 Apr 2022 21:46:58 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9605</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums, where&#160;nums[i]&#160;is a digit between&#160;0&#160;and&#160;9&#160;(inclusive). The&#160;triangular sum&#160;of&#160;nums&#160;is the value of the only element present in&#160;nums&#160;after the following process terminates: Let&#160;nums&#160;comprise of&#160;n&#160;elements.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, where&nbsp;<code>nums[i]</code>&nbsp;is a digit between&nbsp;<code>0</code>&nbsp;and&nbsp;<code>9</code>&nbsp;(<strong>inclusive</strong>).</p>



<p>The&nbsp;<strong>triangular sum</strong>&nbsp;of&nbsp;<code>nums</code>&nbsp;is the value of the only element present in&nbsp;<code>nums</code>&nbsp;after the following process terminates:</p>



<ol class="wp-block-list"><li>Let&nbsp;<code>nums</code>&nbsp;comprise of&nbsp;<code>n</code>&nbsp;elements. If&nbsp;<code>n == 1</code>,&nbsp;<strong>end</strong>&nbsp;the process. Otherwise,&nbsp;<strong>create</strong>&nbsp;a new&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>newNums</code>&nbsp;of length&nbsp;<code>n - 1</code>.</li><li>For each index&nbsp;<code>i</code>, where&nbsp;<code>0 &lt;= i &lt;&nbsp;n - 1</code>,&nbsp;<strong>assign</strong>&nbsp;the value of&nbsp;<code>newNums[i]</code>&nbsp;as&nbsp;<code>(nums[i] + nums[i+1]) % 10</code>, where&nbsp;<code>%</code>&nbsp;denotes modulo operator.</li><li><strong>Replace</strong>&nbsp;the array&nbsp;<code>nums</code>&nbsp;with&nbsp;<code>newNums</code>.</li><li><strong>Repeat</strong>&nbsp;the entire process starting from step 1.</li></ol>



<p>Return&nbsp;<em>the triangular sum of</em>&nbsp;<code>nums</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/02/22/ex1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 8
<strong>Explanation:</strong>
The above diagram depicts the process from which we obtain the triangular sum of the array.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Since there is only one element in nums, the triangular sum is the value of that element itself.</pre>



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



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



<p>Solution 1: Simulation</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int triangularSum(vector&lt;int&gt;&amp; nums) {
    while (nums.size() != 1) {
      vector&lt;int&gt; next(nums.size() - 1);
      for (size_t i = 0; i &lt; nums.size() - 1; ++i)
        next[i] = (nums[i] + nums[i + 1]) % 10;
      swap(next, nums);
    }
    return nums[0];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2221-find-triangular-sum-of-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2169. Count Operations to Obtain Zero</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2169-count-operations-to-obtain-zero/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2169-count-operations-to-obtain-zero/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Feb 2022 13:59:06 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9499</guid>

					<description><![CDATA[You are given two&#160;non-negative&#160;integers&#160;num1&#160;and&#160;num2. In one&#160;operation, if&#160;num1 &#62;= num2, you must subtract&#160;num2&#160;from&#160;num1, otherwise subtract&#160;num1&#160;from&#160;num2. For example, if&#160;num1 = 5&#160;and&#160;num2 = 4, subtract&#160;num2&#160;from&#160;num1, thus obtaining&#160;num1 =&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>non-negative</strong>&nbsp;integers&nbsp;<code>num1</code>&nbsp;and&nbsp;<code>num2</code>.</p>



<p>In one&nbsp;<strong>operation</strong>, if&nbsp;<code>num1 &gt;= num2</code>, you must subtract&nbsp;<code>num2</code>&nbsp;from&nbsp;<code>num1</code>, otherwise subtract&nbsp;<code>num1</code>&nbsp;from&nbsp;<code>num2</code>.</p>



<ul class="wp-block-list"><li>For example, if&nbsp;<code>num1 = 5</code>&nbsp;and&nbsp;<code>num2 = 4</code>, subtract&nbsp;<code>num2</code>&nbsp;from&nbsp;<code>num1</code>, thus obtaining&nbsp;<code>num1 = 1</code>&nbsp;and&nbsp;<code>num2 = 4</code>. However, if&nbsp;<code>num1 = 4</code>&nbsp;and&nbsp;<code>num2 = 5</code>, after one operation,&nbsp;<code>num1 = 4</code>&nbsp;and&nbsp;<code>num2 = 1</code>.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>number of operations</strong>&nbsp;required to make either</em>&nbsp;<code>num1 = 0</code>&nbsp;<em>or</em>&nbsp;<code>num2 = 0</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num1 = 2, num2 = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
- Operation 1: num1 = 2, num2 = 3. Since num1 &lt; num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.
- Operation 2: num1 = 2, num2 = 1. Since num1 &gt; num2, we subtract num2 from num1.
- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.
Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.
So the total number of operations required is 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num1 = 10, num2 = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> 
- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.
Now num1 = 0 and num2 = 10. Since num1 == 0, we are done.
So the total number of operations required is 1.
</pre>



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



<ul class="wp-block-list"><li><code>0 &lt;= num1, num2 &lt;= 10<sup>5</sup></code></li></ul>



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



<p>Time complexity: O(max(n,m) /  min(n, m))<br>Space complexity: O(1)</p>



<p>No code</p>



<h2 class="wp-block-heading"><strong>Solution 2: Simualtion + Math</strong></h2>



<p>For the case of 100, 3<br>100 &#8211; 3 = 97<br>97 &#8211; 3 = 94<br>&#8230;<br>4 &#8211; 3 = 1<br>Swap<br>3 &#8211; 1 = 2<br>2 &#8211; 1 = 1<br>1 &#8211; 1 = 0<br>It takes 36 steps.</p>



<p>We can do 100 / 3 to skip 33 steps <br>100 %= 3 = 1<br>3 / 1 = 3 to skip 3 steps<br>3 %= 1 = 0<br>total is 33 + 3 = 36.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countOperations(int num1, int num2) {
    int ans = 0;
    while (num1 &amp;&amp; num2) {
      if (num1 &lt; num2) swap(num1, num2);
      ans += num1 / num2;
      num1 %= num2;      
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2169-count-operations-to-obtain-zero/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1945. Sum of Digits of String After Convert</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1945-sum-of-digits-of-string-after-convert/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1945-sum-of-digits-of-string-after-convert/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 20:23:55 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[base10]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9311</guid>

					<description><![CDATA[You are given a string&#160;s&#160;consisting of lowercase English letters, and an integer&#160;k. First,&#160;convert&#160;s&#160;into an integer by replacing each letter with its position in the alphabet&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>s</code>&nbsp;consisting of lowercase English letters, and an integer&nbsp;<code>k</code>.</p>



<p>First,&nbsp;<strong>convert</strong>&nbsp;<code>s</code>&nbsp;into an integer by replacing each letter with its position in the alphabet (i.e., replace&nbsp;<code>'a'</code>&nbsp;with&nbsp;<code>1</code>,&nbsp;<code>'b'</code>&nbsp;with&nbsp;<code>2</code>, &#8230;,&nbsp;<code>'z'</code>&nbsp;with&nbsp;<code>26</code>). Then,&nbsp;<strong>transform</strong>&nbsp;the integer by replacing it with the&nbsp;<strong>sum of its digits</strong>. Repeat the&nbsp;<strong>transform</strong>&nbsp;operation&nbsp;<code>k</code><strong>&nbsp;times</strong>&nbsp;in total.</p>



<p>For example, if&nbsp;<code>s = "zbax"</code>&nbsp;and&nbsp;<code>k = 2</code>, then the resulting integer would be&nbsp;<code>8</code>&nbsp;by the following operations:</p>



<ul class="wp-block-list"><li><strong>Convert</strong>:&nbsp;<code>"zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124</code></li><li><strong>Transform #1</strong>:&nbsp;<code>262124 ➝ 2 + 6 + 2 + 1 + 2 + 4&nbsp;➝ 17</code></li><li><strong>Transform #2</strong>:&nbsp;<code>17 ➝ 1 + 7 ➝ 8</code></li></ul>



<p>Return&nbsp;<em>the resulting integer after performing the operations described above</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "iiii", k = 1
<strong>Output:</strong> 36
<strong>Explanation:</strong> The operations are as follows:
- Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcode", k = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> The operations are as follows:
- Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
</pre>



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



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



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



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



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int getLucky(string s, int k) {
    int ans = 0;
    for (char c : s) {
      int n = c - 'a' + 1;
      ans += n % 10;
      ans += n / 10;
    }
    while (--k) {
      int n = ans;
      ans = 0;
      while (n) {
        ans += n % 10;
        n /= 10;
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1945-sum-of-digits-of-string-after-convert/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2101. Detonate the Maximum Bombs</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2101-detonate-the-maximum-bombs/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2101-detonate-the-maximum-bombs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Dec 2021 21:04:14 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9139</guid>

					<description><![CDATA[You are given a list of bombs. The&#160;range&#160;of a bomb is defined as the area where its effect can be felt. This area is in&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a list of bombs. The&nbsp;<strong>range</strong>&nbsp;of a bomb is defined as the area where its effect can be felt. This area is in the shape of a&nbsp;<strong>circle</strong>&nbsp;with the center as the location of the bomb.</p>



<p>The bombs are represented by a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>bombs</code>&nbsp;where&nbsp;<code>bombs[i] = [x<sub>i</sub>, y<sub>i</sub>, r<sub>i</sub>]</code>.&nbsp;<code>x<sub>i</sub></code>&nbsp;and&nbsp;<code>y<sub>i</sub></code>&nbsp;denote the X-coordinate and Y-coordinate of the location of the&nbsp;<code>i<sup>th</sup></code>&nbsp;bomb, whereas&nbsp;<code>r<sub>i</sub></code>&nbsp;denotes the&nbsp;<strong>radius</strong>&nbsp;of its range.</p>



<p>You may choose to detonate a&nbsp;<strong>single</strong>&nbsp;bomb. When a bomb is detonated, it will detonate&nbsp;<strong>all bombs</strong>&nbsp;that lie in its range. These bombs will further detonate the bombs that lie in their ranges.</p>



<p>Given the list of&nbsp;<code>bombs</code>, return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of bombs that can be detonated if you are allowed to detonate&nbsp;<strong>only one</strong>&nbsp;bomb</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> bombs = [[2,1,3],[6,1,4]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
The above figure shows the positions and ranges of the 2 bombs.
If we detonate the left bomb, the right bomb will not be affected.
But if we detonate the right bomb, both bombs will be detonated.
So the maximum bombs that can be detonated is max(1, 2) = 2.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> bombs = [[1,1,5],[10,10,5]]
<strong>Output:</strong> 1
<strong>Explanation:
</strong>Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/07/desmos-eg1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The best bomb to detonate is bomb 0 because:
- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.
- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.
- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.
Thus all 5 bombs are detonated.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= bombs.length&nbsp;&lt;= 100</code></li><li><code>bombs[i].length == 3</code></li><li><code>1 &lt;= x<sub>i</sub>, y<sub>i</sub>, r<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Simulation w/ BFS</strong></h2>



<p>Enumerate the bomb to detonate, and simulate the process using BFS.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumDetonation(vector&lt;vector&lt;int&gt;&gt;&amp; bombs) {
    const int n = bombs.size();    
    auto check = [&amp;](int i, int j) -&gt; bool {
      long x1 = bombs[i][0], y1 = bombs[i][1], r1 = bombs[i][2];
      long x2 = bombs[j][0], y2 = bombs[j][1], r2 = bombs[j][2];
      return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) &lt;= r1 * r1);          
    };
    int ans = 0;
    for (int s = 0; s &lt; n; ++s) {
      int count = 0;
      queue&lt;int&gt; q{{s}};
      vector&lt;int&gt; seen(n);
      seen[s] = 1;
      while (!q.empty()) {
        ++count;
        int i = q.front(); q.pop();
        for (int j = 0; j &lt; n; ++j)
          if (check(i, j) &amp;&amp; !seen[j]++)
            q.push(j);
      }
      ans = max(ans, count);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2101-detonate-the-maximum-bombs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 202. Happy Number</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Dec 2021 03:18:33 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9043</guid>

					<description><![CDATA[Write an algorithm to determine if a number&#160;n&#160;is happy. A&#160;happy number&#160;is a number defined by the following process: Starting with any positive integer, replace the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Write an algorithm to determine if a number&nbsp;<code>n</code>&nbsp;is happy.</p>



<p>A&nbsp;<strong>happy number</strong>&nbsp;is a number defined by the following process:</p>



<ul class="wp-block-list"><li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li><li>Repeat the process until the number equals 1 (where it will stay), or it&nbsp;<strong>loops endlessly in a cycle</strong>&nbsp;which does not include 1.</li><li>Those numbers for which this process&nbsp;<strong>ends in 1</strong>&nbsp;are happy.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if</em>&nbsp;<code>n</code>&nbsp;<em>is a happy number, and</em>&nbsp;<code>false</code>&nbsp;<em>if not</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 19
<strong>Output:</strong> true
<strong>Explanation:</strong>
1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
</pre>



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= n &lt;= 2<sup>31</sup>&nbsp;- 1</code></li></ul>



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



<p>We can use a hasthable to store all the number we generated so far.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool isHappy(int n) {
    auto getNext = [](int x) -&gt; int {
      int ans = 0;
      while (x) {
        ans += (x % 10) * (x % 10);
        x /= 10;
      }
      return ans;
    };
    
    unordered_set&lt;int&gt; s;
    while (n != 1) {
      if (!s.insert(n).second) return false;
      n = getNext(n);
    }
    return true;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Optimization: Space reduction</strong></h2>



<p>Since the number sequence always has a cycle, we can use slow / fast pointers to detect the cycle without using a hastable.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool isHappy(int n) {
    auto getNext = [](int x) -&amp;gt; int {
      int ans = 0;
      while (x) {
        ans += (x % 10) * (x % 10);
        x /= 10;
      }
      return ans;
    };
    
    int slow = n;
    int fast = getNext(n);
    do {      
      slow = getNext(slow);
      fast = getNext(getNext(fast));
    } while (slow != fast);
    return slow == 1;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 118. Pascal&#8217;s Triangle</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-118-pascals-triangle/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-118-pascals-triangle/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 04:44:04 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8833</guid>

					<description><![CDATA[Given an integer&#160;numRows, return the first numRows of&#160;Pascal&#8217;s triangle. In&#160;Pascal&#8217;s triangle, each number is the sum of the two numbers directly above it as shown:&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer&nbsp;<code>numRows</code>, return the first numRows of&nbsp;<strong>Pascal&#8217;s triangle</strong>.</p>



<p>In&nbsp;<strong>Pascal&#8217;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p>



<figure class="wp-block-image"><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif" alt=""/></figure>



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



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



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= numRows &lt;= 30</code></li></ul>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; generate(int numRows) {
    vector&lt;vector&lt;int&gt;&gt; ans(numRows);
    for (int i = 0; i &lt; numRows;++i) {
      ans[i].resize(i + 1);
      ans[i][0] = ans[i][i] = 1;
      for (int j = 1; j &lt; i; ++j)
        ans[i][j] = ans[i-1][j] + ans[i-1][j-1];
    }
    return ans;
  }
}</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Related Problems</strong></h2>



<ul class="wp-block-list"><li><a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-119-pascals-triangle-ii/" data-type="post" data-id="8836">花花酱 LeetCode 119. Pascal’s Triangle II</a></li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-118-pascals-triangle/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2079. Watering Plants</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2079-watering-plants/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2079-watering-plants/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Nov 2021 07:59:10 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8750</guid>

					<description><![CDATA[You want to water&#160;n&#160;plants in your garden with a watering can. The plants are arranged in a row and are labeled from&#160;0&#160;to&#160;n - 1&#160;from left&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You want to water&nbsp;<code>n</code>&nbsp;plants in your garden with a watering can. The plants are arranged in a row and are labeled from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;from left to right where the&nbsp;<code>i<sup>th</sup></code>&nbsp;plant is located at&nbsp;<code>x = i</code>. There is a river at&nbsp;<code>x = -1</code>&nbsp;that you can refill your watering can at.</p>



<p>Each plant needs a specific amount of water. You will water the plants in the following way:</p>



<ul class="wp-block-list"><li>Water the plants in order from left to right.</li><li>After watering the current plant, if you do not have enough water to&nbsp;<strong>completely</strong>&nbsp;water the next plant, return to the river to fully refill the watering can.</li><li>You&nbsp;<strong>cannot</strong>&nbsp;refill the watering can early.</li></ul>



<p>You are initially at the river (i.e.,&nbsp;<code>x = -1</code>). It takes&nbsp;<strong>one step</strong>&nbsp;to move&nbsp;<strong>one unit</strong>&nbsp;on the x-axis.</p>



<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>plants</code>&nbsp;of&nbsp;<code>n</code>&nbsp;integers, where&nbsp;<code>plants[i]</code>&nbsp;is the amount of water the&nbsp;<code>i<sup>th</sup></code>&nbsp;plant needs, and an integer&nbsp;<code>capacity</code>&nbsp;representing the watering can capacity, return&nbsp;<em>the&nbsp;<strong>number of steps</strong>&nbsp;needed to water all the plants</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> plants = [2,2,3,3], capacity = 5
<strong>Output:</strong> 14
<strong>Explanation:</strong> Start at the river with a full watering can:
- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.
- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.
- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).
- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.
- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).
- Walk to plant 3 (4 steps) and water it.
Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> plants = [1,1,1,4,2,3], capacity = 4
<strong>Output:</strong> 30
<strong>Explanation:</strong> Start at the river with a full watering can:
- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).
- Water plant 3 (4 steps). Return to river (4 steps).
- Water plant 4 (5 steps). Return to river (5 steps).
- Water plant 5 (6 steps).
Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> plants = [7,7,7,7,7,7,7], capacity = 8
<strong>Output:</strong> 49
<strong>Explanation:</strong> You have to refill before watering each plant.
Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.
</pre>



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



<ul class="wp-block-list"><li><code>n == plants.length</code></li><li><code>1 &lt;= n &lt;= 1000</code></li><li><code>1 &lt;= plants[i] &lt;= 10<sup>6</sup></code></li><li><code>max(plants[i]) &lt;= capacity &lt;= 10<sup>9</sup></code></li></ul>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int wateringPlants(vector&lt;int&gt;&amp; plants, int capacity) {
    const int n = plants.size();
    int ans = 0;
    for (int i = 0, c = capacity; i &lt; n; c -= plants[i++], ++ans) {
      if (c &gt;= plants[i]) continue;
      ans += i * 2;
      c = capacity;      
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2079-watering-plants/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2075. Decode the Slanted Ciphertext</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2075-decode-the-slanted-ciphertext/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2075-decode-the-slanted-ciphertext/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 19:27:28 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8715</guid>

					<description><![CDATA[A string&#160;originalText&#160;is encoded using a&#160;slanted transposition cipher&#160;to a string&#160;encodedText&#160;with the help of a matrix having a&#160;fixed number of rows&#160;rows. originalText&#160;is placed first in a top-left&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A string&nbsp;<code>originalText</code>&nbsp;is encoded using a&nbsp;<strong>slanted transposition cipher</strong>&nbsp;to a string&nbsp;<code>encodedText</code>&nbsp;with the help of a matrix having a&nbsp;<strong>fixed number of rows</strong>&nbsp;<code>rows</code>.</p>



<p><code>originalText</code>&nbsp;is placed first in a top-left to bottom-right manner.</p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/07/exa11.png" alt=""/></figure>



<p>The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of&nbsp;<code>originalText</code>. The arrow indicates the order in which the cells are filled. All empty cells are filled with&nbsp;<code>' '</code>. The number of columns is chosen such that the rightmost column will&nbsp;<strong>not be empty</strong>&nbsp;after filling in&nbsp;<code>originalText</code>.</p>



<p><code>encodedText</code>&nbsp;is then formed by appending all characters of the matrix in a row-wise fashion.</p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/07/exa12.png" alt=""/></figure>



<p>The characters in the blue cells are appended first to&nbsp;<code>encodedText</code>, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.</p>



<p>For example, if&nbsp;<code>originalText = "cipher"</code>&nbsp;and&nbsp;<code>rows = 3</code>, then we encode it in the following manner:</p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/25/desc2.png" alt=""/></figure>



<p>The blue arrows depict how&nbsp;<code>originalText</code>&nbsp;is placed in the matrix, and the red arrows denote the order in which&nbsp;<code>encodedText</code>&nbsp;is formed. In the above example,&nbsp;<code>encodedText = "ch ie pr"</code>.</p>



<p>Given the encoded string&nbsp;<code>encodedText</code>&nbsp;and number of rows&nbsp;<code>rows</code>, return&nbsp;<em>the original string</em>&nbsp;<code>originalText</code>.</p>



<p><strong>Note:</strong>&nbsp;<code>originalText</code>&nbsp;<strong>does not</strong>&nbsp;have any trailing spaces&nbsp;<code>' '</code>. The test cases are generated such that there is only one possible&nbsp;<code>originalText</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encodedText = "ch   ie   pr", rows = 3
<strong>Output:</strong> "cipher"
<strong>Explanation:</strong> This is the same example described in the problem description.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/26/exam1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encodedText = "iveo    eed   l te   olc", rows = 4
<strong>Output:</strong> "i love leetcode"
<strong>Explanation:</strong> The figure above denotes the matrix that was used to encode originalText. 
The blue arrows show how we can find originalText from encodedText.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/26/eg2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encodedText = "coding", rows = 1
<strong>Output:</strong> "coding"
<strong>Explanation:</strong> Since there is only 1 row, both originalText and encodedText are the same.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/26/exam3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> encodedText = " b  ac", rows = 2
<strong>Output:</strong> " abc"
<strong>Explanation:</strong> originalText cannot have trailing spaces, but it may be preceded by one or more spaces.
</pre>



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



<ul class="wp-block-list"><li><code>0 &lt;= encodedText.length &lt;= 10<sup>6</sup></code></li><li><code>encodedText</code>&nbsp;consists of lowercase English letters and&nbsp;<code>' '</code>&nbsp;only.</li><li><code>encodedText</code>&nbsp;is a valid encoding of some&nbsp;<code>originalText</code>&nbsp;that&nbsp;<strong>does not</strong>&nbsp;have trailing spaces.</li><li><code>1 &lt;= rows &lt;= 1000</code></li><li>The testcases are generated such that there is&nbsp;<strong>only one</strong>&nbsp;possible&nbsp;<code>originalText</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Simulation</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string decodeCiphertext(string encodedText, int rows) {
    const int cols = encodedText.size() / rows;    
    string ans;
    ans.reserve(encodedText.size());
    for (int i = 0; i &lt; cols; ++i)
      for (int j = 0; j &lt; rows &amp;&amp; i + j &lt; cols; ++j)      
        ans += encodedText[j * cols + j + i];
    while (ans.size() &amp;&amp; !isalpha(ans.back())) ans.pop_back();
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2075-decode-the-slanted-ciphertext/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2073. Time Needed to Buy Tickets</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 16:57:40 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8708</guid>

					<description><![CDATA[There are&#160;n&#160;people in a line queuing to buy tickets, where the&#160;0th&#160;person is at the&#160;front&#160;of the line and the&#160;(n - 1)th&#160;person is at the&#160;back&#160;of the line.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There are&nbsp;<code>n</code>&nbsp;people in a line queuing to buy tickets, where the&nbsp;<code>0<sup>th</sup></code>&nbsp;person is at the&nbsp;<strong>front</strong>&nbsp;of the line and the&nbsp;<code>(n - 1)<sup>th</sup></code>&nbsp;person is at the&nbsp;<strong>back</strong>&nbsp;of the line.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>tickets</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where the number of tickets that the&nbsp;<code>i<sup>th</sup></code>&nbsp;person would like to buy is&nbsp;<code>tickets[i]</code>.</p>



<p>Each person takes&nbsp;<strong>exactly 1 second</strong>&nbsp;to buy a ticket. A person can only buy&nbsp;<strong>1 ticket at a time</strong>&nbsp;and has to go back to&nbsp;<strong>the end</strong>&nbsp;of the line (which happens&nbsp;<strong>instantaneously</strong>) in order to buy more tickets. If a person does not have any tickets left to buy, the person will&nbsp;<strong>leave&nbsp;</strong>the line.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>time taken</strong>&nbsp;for the person at position&nbsp;</em><code>k</code><strong><em>(0-indexed)</em>&nbsp;</strong><em>to finish buying tickets</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tickets = [2,3,2], k = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> 
- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
The person at&nbsp;position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tickets = [5,1,1,1], k = 0
<strong>Output:</strong> 8
<strong>Explanation:</strong>
- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
- In the next 4 passes, only the person in position 0 is buying tickets.
The person at&nbsp;position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
</pre>



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



<ul class="wp-block-list"><li><code>n == tickets.length</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li><code>1 &lt;= tickets[i] &lt;= 100</code></li><li><code>0 &lt;= k &lt; n</code></li></ul>



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



<p>Time complexity: O(n * tickets[k])<br>Space complexity: O(n) / O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: huahua
class Solution {
public:
  int timeRequiredToBuy(vector&lt;int&gt;&amp; tickets, int k) {
    const int n = tickets.size();
    queue&lt;pair&lt;int, int&gt;&gt; q;
    for (int i = 0; i &lt; n; ++i)
      q.emplace(i, tickets[i]);
    int ans = 0;
    while (!q.empty()) {
      ++ans;
      auto [i, t] = q.front(); q.pop();      
      if (--t == 0 &amp;&amp; k == i) return ans;
      if (t) q.emplace(i, t);
    }
    return -1;
  }
};</pre>
</div></div>



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



<p>Each person before k will have tickets[k] rounds, each person after k will have tickets[k] &#8211; 1 rounds.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: huahua
class Solution {
public:
  int timeRequiredToBuy(vector&lt;int&gt;&amp; tickets, int k) {
    int ans = 0;
    for (int i = 0; i &lt; tickets.size(); ++i)
      ans += min(tickets[i], tickets[k] - (i &gt; k));
    return ans;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
