id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
361
Bomb Enemy
Medium
<p>Given an <code>m x n</code> matrix <code>grid</code> where each cell is either a wall <code>&#39;W&#39;</code>, an enemy <code>&#39;E&#39;</code> or empty <code>&#39;0&#39;</code>, return <em>the maximum enemies you can kill using one bomb</em>. You can only place the bomb in an empty cell.</p> <p>The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb1-grid.jpg" style="width: 600px; height: 187px;" /> <pre> <strong>Input:</strong> grid = [[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;0&quot;,&quot;W&quot;,&quot;E&quot;],[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;]] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb2-grid.jpg" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> grid = [[&quot;W&quot;,&quot;W&quot;,&quot;W&quot;],[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>grid[i][j]</code> is either <code>&#39;W&#39;</code>, <code>&#39;E&#39;</code>, or <code>&#39;0&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maxKilledEnemies(vector<vector<char>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> g(m, vector<int>(n)); for (int i = 0; i < m; ++i) { int t = 0; for (int j = 0; j < n; ++j) { if (grid[i][j] == 'W') t = 0; else if (grid[i][j] == 'E') ++t; g[i][j] += t; } t = 0; for (int j = n - 1; j >= 0; --j) { if (grid[i][j] == 'W') t = 0; else if (grid[i][j] == 'E') ++t; g[i][j] += t; } } for (int j = 0; j < n; ++j) { int t = 0; for (int i = 0; i < m; ++i) { if (grid[i][j] == 'W') t = 0; else if (grid[i][j] == 'E') ++t; g[i][j] += t; } t = 0; for (int i = m - 1; i >= 0; --i) { if (grid[i][j] == 'W') t = 0; else if (grid[i][j] == 'E') ++t; g[i][j] += t; } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '0') ans = max(ans, g[i][j]); } } return ans; } };
361
Bomb Enemy
Medium
<p>Given an <code>m x n</code> matrix <code>grid</code> where each cell is either a wall <code>&#39;W&#39;</code>, an enemy <code>&#39;E&#39;</code> or empty <code>&#39;0&#39;</code>, return <em>the maximum enemies you can kill using one bomb</em>. You can only place the bomb in an empty cell.</p> <p>The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb1-grid.jpg" style="width: 600px; height: 187px;" /> <pre> <strong>Input:</strong> grid = [[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;0&quot;,&quot;W&quot;,&quot;E&quot;],[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;]] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb2-grid.jpg" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> grid = [[&quot;W&quot;,&quot;W&quot;,&quot;W&quot;],[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>grid[i][j]</code> is either <code>&#39;W&#39;</code>, <code>&#39;E&#39;</code>, or <code>&#39;0&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Go
func maxKilledEnemies(grid [][]byte) int { m, n := len(grid), len(grid[0]) g := make([][]int, m) for i := range g { g[i] = make([]int, n) } for i := 0; i < m; i++ { t := 0 for j := 0; j < n; j++ { if grid[i][j] == 'W' { t = 0 } else if grid[i][j] == 'E' { t++ } g[i][j] += t } t = 0 for j := n - 1; j >= 0; j-- { if grid[i][j] == 'W' { t = 0 } else if grid[i][j] == 'E' { t++ } g[i][j] += t } } for j := 0; j < n; j++ { t := 0 for i := 0; i < m; i++ { if grid[i][j] == 'W' { t = 0 } else if grid[i][j] == 'E' { t++ } g[i][j] += t } t = 0 for i := m - 1; i >= 0; i-- { if grid[i][j] == 'W' { t = 0 } else if grid[i][j] == 'E' { t++ } g[i][j] += t } } ans := 0 for i, row := range grid { for j, v := range row { if v == '0' && ans < g[i][j] { ans = g[i][j] } } } return ans }
361
Bomb Enemy
Medium
<p>Given an <code>m x n</code> matrix <code>grid</code> where each cell is either a wall <code>&#39;W&#39;</code>, an enemy <code>&#39;E&#39;</code> or empty <code>&#39;0&#39;</code>, return <em>the maximum enemies you can kill using one bomb</em>. You can only place the bomb in an empty cell.</p> <p>The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb1-grid.jpg" style="width: 600px; height: 187px;" /> <pre> <strong>Input:</strong> grid = [[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;0&quot;,&quot;W&quot;,&quot;E&quot;],[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;]] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb2-grid.jpg" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> grid = [[&quot;W&quot;,&quot;W&quot;,&quot;W&quot;],[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>grid[i][j]</code> is either <code>&#39;W&#39;</code>, <code>&#39;E&#39;</code>, or <code>&#39;0&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int maxKilledEnemies(char[][] grid) { int m = grid.length; int n = grid[0].length; int[][] g = new int[m][n]; for (int i = 0; i < m; ++i) { int t = 0; for (int j = 0; j < n; ++j) { if (grid[i][j] == 'W') { t = 0; } else if (grid[i][j] == 'E') { ++t; } g[i][j] += t; } t = 0; for (int j = n - 1; j >= 0; --j) { if (grid[i][j] == 'W') { t = 0; } else if (grid[i][j] == 'E') { ++t; } g[i][j] += t; } } for (int j = 0; j < n; ++j) { int t = 0; for (int i = 0; i < m; ++i) { if (grid[i][j] == 'W') { t = 0; } else if (grid[i][j] == 'E') { ++t; } g[i][j] += t; } t = 0; for (int i = m - 1; i >= 0; --i) { if (grid[i][j] == 'W') { t = 0; } else if (grid[i][j] == 'E') { ++t; } g[i][j] += t; } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '0') { ans = Math.max(ans, g[i][j]); } } } return ans; } }
361
Bomb Enemy
Medium
<p>Given an <code>m x n</code> matrix <code>grid</code> where each cell is either a wall <code>&#39;W&#39;</code>, an enemy <code>&#39;E&#39;</code> or empty <code>&#39;0&#39;</code>, return <em>the maximum enemies you can kill using one bomb</em>. You can only place the bomb in an empty cell.</p> <p>The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb1-grid.jpg" style="width: 600px; height: 187px;" /> <pre> <strong>Input:</strong> grid = [[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;0&quot;,&quot;W&quot;,&quot;E&quot;],[&quot;0&quot;,&quot;E&quot;,&quot;0&quot;,&quot;0&quot;]] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0361.Bomb%20Enemy/images/bomb2-grid.jpg" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> grid = [[&quot;W&quot;,&quot;W&quot;,&quot;W&quot;],[&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>grid[i][j]</code> is either <code>&#39;W&#39;</code>, <code>&#39;E&#39;</code>, or <code>&#39;0&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maxKilledEnemies(self, grid: List[List[str]]) -> int: m, n = len(grid), len(grid[0]) g = [[0] * n for _ in range(m)] for i in range(m): t = 0 for j in range(n): if grid[i][j] == 'W': t = 0 elif grid[i][j] == 'E': t += 1 g[i][j] += t t = 0 for j in range(n - 1, -1, -1): if grid[i][j] == 'W': t = 0 elif grid[i][j] == 'E': t += 1 g[i][j] += t for j in range(n): t = 0 for i in range(m): if grid[i][j] == 'W': t = 0 elif grid[i][j] == 'E': t += 1 g[i][j] += t t = 0 for i in range(m - 1, -1, -1): if grid[i][j] == 'W': t = 0 elif grid[i][j] == 'E': t += 1 g[i][j] += t return max( [g[i][j] for i in range(m) for j in range(n) if grid[i][j] == '0'], default=0, )
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
C++
class HitCounter { public: HitCounter() { } void hit(int timestamp) { ts.push_back(timestamp); } int getHits(int timestamp) { return ts.end() - lower_bound(ts.begin(), ts.end(), timestamp - 300 + 1); } private: vector<int> ts; }; /** * Your HitCounter object will be instantiated and called as such: * HitCounter* obj = new HitCounter(); * obj->hit(timestamp); * int param_2 = obj->getHits(timestamp); */
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
Go
type HitCounter struct { ts []int } func Constructor() HitCounter { return HitCounter{} } func (this *HitCounter) Hit(timestamp int) { this.ts = append(this.ts, timestamp) } func (this *HitCounter) GetHits(timestamp int) int { return len(this.ts) - sort.SearchInts(this.ts, timestamp-300+1) } /** * Your HitCounter object will be instantiated and called as such: * obj := Constructor(); * obj.Hit(timestamp); * param_2 := obj.GetHits(timestamp); */
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
Java
class HitCounter { private List<Integer> ts = new ArrayList<>(); public HitCounter() { } public void hit(int timestamp) { ts.add(timestamp); } public int getHits(int timestamp) { int l = search(timestamp - 300 + 1); return ts.size() - l; } private int search(int x) { int l = 0, r = ts.size(); while (l < r) { int mid = (l + r) >> 1; if (ts.get(mid) >= x) { r = mid; } else { l = mid + 1; } } return l; } } /** * Your HitCounter object will be instantiated and called as such: * HitCounter obj = new HitCounter(); * obj.hit(timestamp); * int param_2 = obj.getHits(timestamp); */
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
Python
class HitCounter: def __init__(self): self.ts = [] def hit(self, timestamp: int) -> None: self.ts.append(timestamp) def getHits(self, timestamp: int) -> int: return len(self.ts) - bisect_left(self.ts, timestamp - 300 + 1) # Your HitCounter object will be instantiated and called as such: # obj = HitCounter() # obj.hit(timestamp) # param_2 = obj.getHits(timestamp)
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
Rust
struct HitCounter { ts: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl HitCounter { fn new() -> Self { HitCounter { ts: Vec::new() } } fn hit(&mut self, timestamp: i32) { self.ts.push(timestamp); } fn get_hits(&self, timestamp: i32) -> i32 { let l = self.search(timestamp - 300 + 1); (self.ts.len() - l) as i32 } fn search(&self, x: i32) -> usize { let (mut l, mut r) = (0, self.ts.len()); while l < r { let mid = (l + r) / 2; if self.ts[mid] >= x { r = mid; } else { l = mid + 1; } } l } }
362
Design Hit Counter
Medium
<p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p> <p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p> <p>Implement the <code>HitCounter</code> class:</p> <ul> <li><code>HitCounter()</code> Initializes the object of the hit counter system.</li> <li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li> <li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;HitCounter&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;hit&quot;, &quot;getHits&quot;, &quot;getHits&quot;] [[], [1], [2], [3], [4], [300], [300], [301]] <strong>Output</strong> [null, null, null, null, 3, null, 4, 3] <strong>Explanation</strong> HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li> <li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li> <li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
Design; Queue; Array; Binary Search; Data Stream
TypeScript
class HitCounter { private ts: number[] = []; constructor() {} hit(timestamp: number): void { this.ts.push(timestamp); } getHits(timestamp: number): number { const search = (x: number) => { let [l, r] = [0, this.ts.length]; while (l < r) { const mid = (l + r) >> 1; if (this.ts[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; return this.ts.length - search(timestamp - 300 + 1); } } /** * Your HitCounter object will be instantiated and called as such: * var obj = new HitCounter() * obj.hit(timestamp) * var param_2 = obj.getHits(timestamp) */
363
Max Sum of Rectangle No Larger Than K
Hard
<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p> <p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/images/sum-grid.jpg" style="width: 255px; height: 176px;" /> <pre> <strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[2,2,-1]], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>
Array; Binary Search; Matrix; Ordered Set; Prefix Sum
C++
class Solution { public: int maxSumSubmatrix(vector<vector<int>>& matrix, int k) { int m = matrix.size(), n = matrix[0].size(); const int inf = 1 << 30; int ans = -inf; for (int i = 0; i < m; ++i) { vector<int> nums(n); for (int j = i; j < m; ++j) { for (int h = 0; h < n; ++h) { nums[h] += matrix[j][h]; } set<int> ts; int s = 0; ts.insert(0); for (int x : nums) { s += x; auto it = ts.lower_bound(s - k); if (it != ts.end()) { ans = max(ans, s - *it); } ts.insert(s); } } } return ans; } };
363
Max Sum of Rectangle No Larger Than K
Hard
<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p> <p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/images/sum-grid.jpg" style="width: 255px; height: 176px;" /> <pre> <strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[2,2,-1]], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>
Array; Binary Search; Matrix; Ordered Set; Prefix Sum
Go
func maxSumSubmatrix(matrix [][]int, k int) int { m, n := len(matrix), len(matrix[0]) const inf = 1 << 30 ans := -inf for i := 0; i < m; i++ { nums := make([]int, n) for j := i; j < m; j++ { for h := 0; h < n; h++ { nums[h] += matrix[j][h] } s := 0 rbt := redblacktree.NewWithIntComparator() rbt.Put(0, nil) for _, x := range nums { s += x if y, ok := rbt.Ceiling(s - k); ok { ans = max(ans, s-y.Key.(int)) } rbt.Put(s, nil) } } } return ans }
363
Max Sum of Rectangle No Larger Than K
Hard
<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p> <p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/images/sum-grid.jpg" style="width: 255px; height: 176px;" /> <pre> <strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[2,2,-1]], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>
Array; Binary Search; Matrix; Ordered Set; Prefix Sum
Java
class Solution { public int maxSumSubmatrix(int[][] matrix, int k) { int m = matrix.length; int n = matrix[0].length; final int inf = 1 << 30; int ans = -inf; for (int i = 0; i < m; ++i) { int[] nums = new int[n]; for (int j = i; j < m; ++j) { for (int h = 0; h < n; ++h) { nums[h] += matrix[j][h]; } int s = 0; TreeSet<Integer> ts = new TreeSet<>(); ts.add(0); for (int x : nums) { s += x; Integer y = ts.ceiling(s - k); if (y != null) { ans = Math.max(ans, s - y); } ts.add(s); } } } return ans; } }
363
Max Sum of Rectangle No Larger Than K
Hard
<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p> <p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/images/sum-grid.jpg" style="width: 255px; height: 176px;" /> <pre> <strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[2,2,-1]], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>
Array; Binary Search; Matrix; Ordered Set; Prefix Sum
Python
class Solution: def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) ans = -inf for i in range(m): nums = [0] * n for j in range(i, m): for h in range(n): nums[h] += matrix[j][h] s = 0 ts = SortedSet([0]) for x in nums: s += x p = ts.bisect_left(s - k) if p != len(ts): ans = max(ans, s - ts[p]) ts.add(s) return ans
363
Max Sum of Rectangle No Larger Than K
Hard
<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p> <p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/images/sum-grid.jpg" style="width: 255px; height: 176px;" /> <pre> <strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[2,2,-1]], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li> <li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>
Array; Binary Search; Matrix; Ordered Set; Prefix Sum
TypeScript
function maxSumSubmatrix(matrix: number[][], k: number): number { const m = matrix.length; const n = matrix[0].length; let ans = -Infinity; for (let i = 0; i < m; ++i) { const nums: number[] = new Array(n).fill(0); for (let j = i; j < m; ++j) { for (let h = 0; h < n; ++h) { nums[h] += matrix[j][h]; } let s = 0; const ts: TreeSet<number> = new TreeSet<number>(); ts.add(0); for (const x of nums) { s += x; const p = ts.ceil(s - k); if (p !== undefined) { ans = Math.max(ans, s - p); } ts.add(s); } } } return ans; } type Compare<T> = (lhs: T, rhs: T) => number; class RBTreeNode<T = number> { data: T; count: number; left: RBTreeNode<T> | null; right: RBTreeNode<T> | null; parent: RBTreeNode<T> | null; color: number; constructor(data: T) { this.data = data; this.left = this.right = this.parent = null; this.color = 0; this.count = 1; } sibling(): RBTreeNode<T> | null { if (!this.parent) return null; // sibling null if no parent return this.isOnLeft() ? this.parent.right : this.parent.left; } isOnLeft(): boolean { return this === this.parent!.left; } hasRedChild(): boolean { return ( Boolean(this.left && this.left.color === 0) || Boolean(this.right && this.right.color === 0) ); } } class RBTree<T> { root: RBTreeNode<T> | null; lt: (l: T, r: T) => boolean; constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) { this.root = null; this.lt = (l: T, r: T) => compare(l, r) < 0; } rotateLeft(pt: RBTreeNode<T>): void { const right = pt.right!; pt.right = right.left; if (pt.right) pt.right.parent = pt; right.parent = pt.parent; if (!pt.parent) this.root = right; else if (pt === pt.parent.left) pt.parent.left = right; else pt.parent.right = right; right.left = pt; pt.parent = right; } rotateRight(pt: RBTreeNode<T>): void { const left = pt.left!; pt.left = left.right; if (pt.left) pt.left.parent = pt; left.parent = pt.parent; if (!pt.parent) this.root = left; else if (pt === pt.parent.left) pt.parent.left = left; else pt.parent.right = left; left.right = pt; pt.parent = left; } swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.color; p1.color = p2.color; p2.color = tmp; } swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.data; p1.data = p2.data; p2.data = tmp; } fixAfterInsert(pt: RBTreeNode<T>): void { let parent = null; let grandParent = null; while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) { parent = pt.parent; grandParent = pt.parent.parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent === grandParent?.left) { const uncle = grandParent.right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle && uncle.color === 0) { grandParent.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt === parent.right) { this.rotateLeft(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ this.rotateRight(grandParent); this.swapColor(parent!, grandParent); pt = parent!; } } else { /* Case : B Parent of pt is right child of Grand-parent of pt */ const uncle = grandParent!.left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle != null && uncle.color === 0) { grandParent!.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent!; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt === parent.left) { this.rotateRight(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ this.rotateLeft(grandParent!); this.swapColor(parent!, grandParent!); pt = parent!; } } } this.root!.color = 1; } delete(val: T): boolean { const node = this.find(val); if (!node) return false; node.count--; if (!node.count) this.deleteNode(node); return true; } deleteAll(val: T): boolean { const node = this.find(val); if (!node) return false; this.deleteNode(node); return true; } deleteNode(v: RBTreeNode<T>): void { const u = BSTreplace(v); // True when u and v are both black const uvBlack = (u === null || u.color === 1) && v.color === 1; const parent = v.parent!; if (!u) { // u is null therefore v is leaf if (v === this.root) this.root = null; // v is root, making root null else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v this.fixDoubleBlack(v); } else { // u or v is red if (v.sibling()) { // sibling is not null, make it red" v.sibling()!.color = 0; } } // delete v from the tree if (v.isOnLeft()) parent.left = null; else parent.right = null; } return; } if (!v.left || !v.right) { // v has 1 child if (v === this.root) { // v is root, assign the value of u to v, and delete u v.data = u.data; v.left = v.right = null; } else { // Detach v from tree and move u up if (v.isOnLeft()) parent.left = u; else parent.right = u; u.parent = parent; if (uvBlack) this.fixDoubleBlack(u); // u and v both black, fix double black at u else u.color = 1; // u or v red, color u black } return; } // v has 2 children, swap data with successor and recurse this.swapData(u, v); this.deleteNode(u); // find node that replaces a deleted node in BST function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null { // when node have 2 children if (x.left && x.right) return successor(x.right); // when leaf if (!x.left && !x.right) return null; // when single child return x.left ?? x.right; } // find node that do not have a left child // in the subtree of the given node function successor(x: RBTreeNode<T>): RBTreeNode<T> { let temp = x; while (temp.left) temp = temp.left; return temp; } } fixDoubleBlack(x: RBTreeNode<T>): void { if (x === this.root) return; // Reached root const sibling = x.sibling(); const parent = x.parent!; if (!sibling) { // No sibiling, double black pushed up this.fixDoubleBlack(parent); } else { if (sibling.color === 0) { // Sibling red parent.color = 0; sibling.color = 1; if (sibling.isOnLeft()) this.rotateRight(parent); // left case else this.rotateLeft(parent); // right case this.fixDoubleBlack(x); } else { // Sibling black if (sibling.hasRedChild()) { // at least 1 red children if (sibling.left && sibling.left.color === 0) { if (sibling.isOnLeft()) { // left left sibling.left.color = sibling.color; sibling.color = parent.color; this.rotateRight(parent); } else { // right left sibling.left.color = parent.color; this.rotateRight(sibling); this.rotateLeft(parent); } } else { if (sibling.isOnLeft()) { // left right sibling.right!.color = parent.color; this.rotateLeft(sibling); this.rotateRight(parent); } else { // right right sibling.right!.color = sibling.color; sibling.color = parent.color; this.rotateLeft(parent); } } parent.color = 1; } else { // 2 black children sibling.color = 0; if (parent.color === 1) this.fixDoubleBlack(parent); else parent.color = 1; } } } } insert(data: T): boolean { // search for a position to insert let parent = this.root; while (parent) { if (this.lt(data, parent.data)) { if (!parent.left) break; else parent = parent.left; } else if (this.lt(parent.data, data)) { if (!parent.right) break; else parent = parent.right; } else break; } // insert node into parent const node = new RBTreeNode(data); if (!parent) this.root = node; else if (this.lt(node.data, parent.data)) parent.left = node; else if (this.lt(parent.data, node.data)) parent.right = node; else { parent.count++; return false; } node.parent = parent; this.fixAfterInsert(node); return true; } find(data: T): RBTreeNode<T> | null { let p = this.root; while (p) { if (this.lt(data, p.data)) { p = p.left; } else if (this.lt(p.data, data)) { p = p.right; } else break; } return p ?? null; } *inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.inOrder(root.left!)) yield v; yield root.data; for (const v of this.inOrder(root.right!)) yield v; } *reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.reverseInOrder(root.right!)) yield v; yield root.data; for (const v of this.reverseInOrder(root.left!)) yield v; } } class TreeSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size += successful ? 1 : 0; return successful; } delete(val: T): boolean { const deleted = this.tree.deleteAll(val); this._size -= deleted ? 1 : 0; return deleted; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { for (const val of this.values()) yield val; } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) yield val; return undefined; } /** * Return a generator for reverse order traversing the set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) yield val; return undefined; } } class TreeMultiSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size++; return successful; } delete(val: T): boolean { const successful = this.tree.delete(val); if (!successful) return false; this._size--; return true; } count(val: T): number { const node = this.tree.find(val); return node ? node.count : 0; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { yield* this.values(); } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } /** * Return a generator for reverse order traversing the multi-set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } }
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
C++
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Constructor initializes an empty nested list. * NestedInteger(); * * // Constructor initializes a single integer. * NestedInteger(int value); * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Set this NestedInteger to hold a single integer. * void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * void add(const NestedInteger &ni); * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ class Solution { public: int depthSumInverse(vector<NestedInteger>& nestedList) { int maxDepth = 0, ws = 0, s = 0; function<void(NestedInteger&, int)> dfs = [&](NestedInteger& x, int d) { maxDepth = max(maxDepth, d); if (x.isInteger()) { ws += x.getInteger() * d; s += x.getInteger(); } else { for (auto& y : x.getList()) { dfs(y, d + 1); } } }; for (auto& x : nestedList) { dfs(x, 1); } return (maxDepth + 1) * s - ws; } };
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
Go
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * func (n NestedInteger) IsInteger() bool {} * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * // So before calling this method, you should have a check * func (n NestedInteger) GetInteger() int {} * * // Set this NestedInteger to hold a single integer. * func (n *NestedInteger) SetInteger(value int) {} * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * func (n *NestedInteger) Add(elem NestedInteger) {} * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The list length is zero if this NestedInteger holds a single integer * // You can access NestedInteger's List element directly if you want to modify it * func (n NestedInteger) GetList() []*NestedInteger {} */ func depthSumInverse(nestedList []*NestedInteger) int { var maxDepth, ws, s int var dfs func(*NestedInteger, int) dfs = func(x *NestedInteger, d int) { maxDepth = max(maxDepth, d) if x.IsInteger() { ws += x.GetInteger() * d s += x.GetInteger() } else { for _, y := range x.GetList() { dfs(y, d+1) } } } for _, x := range nestedList { dfs(x, 1) } return (maxDepth+1)*s - ws }
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
Java
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { private int maxDepth; private int ws; private int s; public int depthSumInverse(List<NestedInteger> nestedList) { for (NestedInteger x : nestedList) { dfs(x, 1); } return (maxDepth + 1) * s - ws; } private void dfs(NestedInteger x, int d) { maxDepth = Math.max(maxDepth, d); if (x.isInteger()) { ws += x.getInteger() * d; s += x.getInteger(); } else { for (NestedInteger y : x.getList()) { dfs(y, d + 1); } } } }
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
JavaScript
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @param {NestedInteger[]} nestedList * @return {number} */ var depthSumInverse = function (nestedList) { let [maxDepth, ws, s] = [0, 0, 0]; const dfs = (x, d) => { maxDepth = Math.max(maxDepth, d); if (x.isInteger()) { ws += x.getInteger() * d; s += x.getInteger(); } else { for (const y of x.getList()) { dfs(y, d + 1); } } }; for (const x of nestedList) { dfs(x, 1); } return (maxDepth + 1) * s - ws; };
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
Python
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: def dfs(x, d): nonlocal maxDepth, s, ws maxDepth = max(maxDepth, d) if x.isInteger(): s += x.getInteger() ws += x.getInteger() * d else: for y in x.getList(): dfs(y, d + 1) maxDepth = s = ws = 0 for x in nestedList: dfs(x, 1) return (maxDepth + 1) * s - ws
364
Nested List Weight Sum II
Medium
<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer&#39;s value set to its <strong>depth</strong>. Let <code>maxDepth</code> be the <strong>maximum depth</strong> of any integer.</p> <p>The <strong>weight</strong> of an integer is <code>maxDepth - (the depth of the integer) + 1</code>.</p> <p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>weight</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex1.png" style="width: 426px; height: 181px;" /> <pre> <strong>Input:</strong> nestedList = [[1,1],2,[1,1]] <strong>Output:</strong> 8 <strong>Explanation:</strong> Four 1&#39;s with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/images/nestedlistweightsumiiex2.png" style="width: 349px; height: 192px;" /> <pre> <strong>Input:</strong> nestedList = [1,[4,[6]]] <strong>Output:</strong> 17 <strong>Explanation:</strong> One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1. 1*3 + 4*2 + 6*1 = 17 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nestedList.length &lt;= 50</code></li> <li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li> <li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li> <li>There are no empty lists.</li> </ul>
Stack; Depth-First Search; Breadth-First Search
TypeScript
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * If value is provided, then it holds a single integer * Otherwise it holds an empty nested list * constructor(value?: number) { * ... * }; * * Return true if this NestedInteger holds a single integer, rather than a nested list. * isInteger(): boolean { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * getInteger(): number | null { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * setInteger(value: number) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * add(elem: NestedInteger) { * ... * }; * * Return the nested list that this NestedInteger holds, * or an empty list if this NestedInteger holds a single integer * getList(): NestedInteger[] { * ... * }; * }; */ function depthSumInverse(nestedList: NestedInteger[]): number { let [maxDepth, ws, s] = [0, 0, 0]; const dfs = (x: NestedInteger, d: number) => { maxDepth = Math.max(maxDepth, d); if (x.isInteger()) { ws += x.getInteger() * d; s += x.getInteger(); } else { for (const y of x.getList()) { dfs(y, d + 1); } } }; for (const x of nestedList) { dfs(x, 1); } return (maxDepth + 1) * s - ws; }
365
Water and Jug Problem
Medium
<p>You are given two jugs with capacities <code>x</code> liters and <code>y</code> liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach <code>target</code> using the following operations:</p> <ul> <li>Fill either jug completely with water.</li> <li>Completely empty either jug.</li> <li>Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 3, y = 5, target = 4 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong></p> <p>Follow these steps to reach a total of 4 liters:</p> <ol> <li>Fill the 5-liter jug (0, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).</li> <li>Empty the 3-liter jug (0, 2).</li> <li>Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).</li> <li>Fill the 5-liter jug again (2, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).</li> <li>Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).</li> </ol> <p>Reference: The <a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01" target="_blank">Die Hard</a> example.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 2, y = 6, target = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> false </span></p> </div> <p><strong class="example">Example 3: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 1, y = 2, target = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong> Fill both jugs. The total amount of water in both jugs is equal to 3 now.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Math
C++
class Solution { public: bool canMeasureWater(int x, int y, int z) { using pii = pair<int, int>; stack<pii> stk; stk.emplace(0, 0); auto hash_function = [](const pii& o) { return hash<int>()(o.first) ^ hash<int>()(o.second); }; unordered_set<pii, decltype(hash_function)> vis(0, hash_function); while (stk.size()) { auto st = stk.top(); stk.pop(); if (vis.count(st)) { continue; } vis.emplace(st); auto [i, j] = st; if (i == z || j == z || i + j == z) { return true; } stk.emplace(x, j); stk.emplace(i, y); stk.emplace(0, j); stk.emplace(i, 0); int a = min(i, y - j); int b = min(j, x - i); stk.emplace(i - a, j + a); stk.emplace(i + b, j - b); } return false; } };
365
Water and Jug Problem
Medium
<p>You are given two jugs with capacities <code>x</code> liters and <code>y</code> liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach <code>target</code> using the following operations:</p> <ul> <li>Fill either jug completely with water.</li> <li>Completely empty either jug.</li> <li>Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 3, y = 5, target = 4 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong></p> <p>Follow these steps to reach a total of 4 liters:</p> <ol> <li>Fill the 5-liter jug (0, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).</li> <li>Empty the 3-liter jug (0, 2).</li> <li>Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).</li> <li>Fill the 5-liter jug again (2, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).</li> <li>Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).</li> </ol> <p>Reference: The <a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01" target="_blank">Die Hard</a> example.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 2, y = 6, target = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> false </span></p> </div> <p><strong class="example">Example 3: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 1, y = 2, target = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong> Fill both jugs. The total amount of water in both jugs is equal to 3 now.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Math
Go
func canMeasureWater(x int, y int, z int) bool { type pair struct{ x, y int } vis := map[pair]bool{} var dfs func(int, int) bool dfs = func(i, j int) bool { st := pair{i, j} if vis[st] { return false } vis[st] = true if i == z || j == z || i+j == z { return true } if dfs(x, j) || dfs(i, y) || dfs(0, j) || dfs(i, 0) { return true } a := min(i, y-j) b := min(j, x-i) return dfs(i-a, j+a) || dfs(i+b, j-b) } return dfs(0, 0) }
365
Water and Jug Problem
Medium
<p>You are given two jugs with capacities <code>x</code> liters and <code>y</code> liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach <code>target</code> using the following operations:</p> <ul> <li>Fill either jug completely with water.</li> <li>Completely empty either jug.</li> <li>Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 3, y = 5, target = 4 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong></p> <p>Follow these steps to reach a total of 4 liters:</p> <ol> <li>Fill the 5-liter jug (0, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).</li> <li>Empty the 3-liter jug (0, 2).</li> <li>Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).</li> <li>Fill the 5-liter jug again (2, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).</li> <li>Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).</li> </ol> <p>Reference: The <a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01" target="_blank">Die Hard</a> example.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 2, y = 6, target = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> false </span></p> </div> <p><strong class="example">Example 3: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 1, y = 2, target = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong> Fill both jugs. The total amount of water in both jugs is equal to 3 now.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Math
Java
class Solution { private Set<Long> vis = new HashSet<>(); private int x, y, z; public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { x = jug1Capacity; y = jug2Capacity; z = targetCapacity; return dfs(0, 0); } private boolean dfs(int i, int j) { long st = f(i, j); if (!vis.add(st)) { return false; } if (i == z || j == z || i + j == z) { return true; } if (dfs(x, j) || dfs(i, y) || dfs(0, j) || dfs(i, 0)) { return true; } int a = Math.min(i, y - j); int b = Math.min(j, x - i); return dfs(i - a, j + a) || dfs(i + b, j - b); } private long f(int i, int j) { return i * 1000000L + j; } }
365
Water and Jug Problem
Medium
<p>You are given two jugs with capacities <code>x</code> liters and <code>y</code> liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach <code>target</code> using the following operations:</p> <ul> <li>Fill either jug completely with water.</li> <li>Completely empty either jug.</li> <li>Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 3, y = 5, target = 4 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong></p> <p>Follow these steps to reach a total of 4 liters:</p> <ol> <li>Fill the 5-liter jug (0, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).</li> <li>Empty the 3-liter jug (0, 2).</li> <li>Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).</li> <li>Fill the 5-liter jug again (2, 5).</li> <li>Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).</li> <li>Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).</li> </ol> <p>Reference: The <a href="https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01" target="_blank">Die Hard</a> example.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 2, y = 6, target = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> false </span></p> </div> <p><strong class="example">Example 3: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> x = 1, y = 2, target = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> true </span></p> <p><strong>Explanation:</strong> Fill both jugs. The total amount of water in both jugs is equal to 3 now.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li> </ul>
Depth-First Search; Breadth-First Search; Math
Python
class Solution: def canMeasureWater(self, x: int, y: int, z: int) -> bool: def dfs(i: int, j: int) -> bool: if (i, j) in vis: return False vis.add((i, j)) if i == z or j == z or i + j == z: return True if dfs(x, j) or dfs(i, y) or dfs(0, j) or dfs(i, 0): return True a = min(i, y - j) b = min(j, x - i) return dfs(i - a, j + a) or dfs(i + b, j - b) vis = set() return dfs(0, 0)
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * 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 Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> ans; function<int(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return 0; } int l = dfs(root->left); int r = dfs(root->right); int h = max(l, r); if (ans.size() == h) { ans.push_back({}); } ans[h].push_back(root->val); return h + 1; }; dfs(root); return ans; } };
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public IList<IList<int>> FindLeaves(TreeNode root) { var ans = new List<IList<int>>(); int Dfs(TreeNode node) { if (node == null) { return 0; } int l = Dfs(node.left); int r = Dfs(node.right); int h = Math.Max(l, r); if (ans.Count == h) { ans.Add(new List<int>()); } ans[h].Add(node.val); return h + 1; } Dfs(root); return ans; } }
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findLeaves(root *TreeNode) (ans [][]int) { var dfs func(*TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } l, r := dfs(root.Left), dfs(root.Right) h := max(l, r) if len(ans) == h { ans = append(ans, []int{}) } ans[h] = append(ans[h], root.Val) return h + 1 } dfs(root) return }
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private List<List<Integer>> ans = new ArrayList<>(); public List<List<Integer>> findLeaves(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int l = dfs(root.left); int r = dfs(root.right); int h = Math.max(l, r); if (ans.size() == h) { ans.add(new ArrayList<>()); } ans.get(h).add(root.val); return h + 1; } }
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l, r = dfs(root.left), dfs(root.right) h = max(l, r) if len(ans) == h: ans.append([]) ans[h].append(root.val) return h + 1 ans = [] dfs(root) return ans
366
Find Leaves of Binary Tree
Medium
<p>Given the <code>root</code> of a binary tree, collect a tree&#39;s nodes as if you were doing this:</p> <ul> <li>Collect all the leaf nodes.</li> <li>Remove all the leaf&nbsp;nodes.</li> <li>Repeat until the tree is empty.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/images/remleaves-tree.jpg" style="width: 500px; height: 215px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5] <strong>Output:</strong> [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function findLeaves(root: TreeNode | null): number[][] { const ans: number[][] = []; const dfs = (root: TreeNode | null): number => { if (root === null) { return 0; } const l = dfs(root.left); const r = dfs(root.right); const h = Math.max(l, r); if (ans.length === h) { ans.push([]); } ans[h].push(root.val); return h + 1; }; dfs(root); return ans; }
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
C++
class Solution { public: bool isPerfectSquare(int num) { int l = 1, r = num; while (l < r) { int mid = l + (r - l) / 2; if (1LL * mid * mid >= num) { r = mid; } else { l = mid + 1; } } return 1LL * l * l == num; } };
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Go
func isPerfectSquare(num int) bool { l := sort.Search(num, func(i int) bool { return i*i >= num }) return l*l == num }
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Java
class Solution { public boolean isPerfectSquare(int num) { int l = 1, r = num; while (l < r) { int mid = (l + r) >>> 1; if (1L * mid * mid >= num) { r = mid; } else { l = mid + 1; } } return l * l == num; } }
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Python
class Solution: def isPerfectSquare(self, num: int) -> bool: l = bisect_left(range(1, num + 1), num, key=lambda x: x * x) + 1 return l * l == num
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Rust
impl Solution { pub fn is_perfect_square(num: i32) -> bool { let mut l = 1; let mut r = num as i64; while l < r { let mid = (l + r) / 2; if mid * mid >= (num as i64) { r = mid; } else { l = mid + 1; } } l * l == (num as i64) } }
367
Valid Perfect Square
Easy
<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p> <p>You must not use any built-in library function, such as <code>sqrt</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 16 <strong>Output:</strong> true <strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 14 <strong>Output:</strong> false <strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
TypeScript
function isPerfectSquare(num: number): boolean { let [l, r] = [1, num]; while (l < r) { const mid = (l + r) >> 1; if (mid >= num / mid) { r = mid; } else { l = mid + 1; } } return l * l === num; }
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
C++
class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { ranges::sort(nums); int n = nums.size(); int f[n]; int k = 0; for (int i = 0; i < n; ++i) { f[i] = 1; for (int j = 0; j < i; ++j) { if (nums[i] % nums[j] == 0) { f[i] = max(f[i], f[j] + 1); } } if (f[k] < f[i]) { k = i; } } int m = f[k]; vector<int> ans; for (int i = k; m > 0; --i) { if (nums[k] % nums[i] == 0 && f[i] == m) { ans.push_back(nums[i]); k = i; --m; } } return ans; } };
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
Go
func largestDivisibleSubset(nums []int) (ans []int) { sort.Ints(nums) n := len(nums) f := make([]int, n) k := 0 for i := 0; i < n; i++ { f[i] = 1 for j := 0; j < i; j++ { if nums[i]%nums[j] == 0 { f[i] = max(f[i], f[j]+1) } } if f[k] < f[i] { k = i } } m := f[k] for i := k; m > 0; i-- { if nums[k]%nums[i] == 0 && f[i] == m { ans = append(ans, nums[i]) k = i m-- } } return }
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
Java
class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { Arrays.sort(nums); int n = nums.length; int[] f = new int[n]; Arrays.fill(f, 1); int k = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { if (nums[i] % nums[j] == 0) { f[i] = Math.max(f[i], f[j] + 1); } } if (f[k] < f[i]) { k = i; } } int m = f[k]; List<Integer> ans = new ArrayList<>(); for (int i = k; m > 0; --i) { if (nums[k] % nums[i] == 0 && f[i] == m) { ans.add(nums[i]); k = i; --m; } } return ans; } }
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
Python
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) f = [1] * n k = 0 for i in range(n): for j in range(i): if nums[i] % nums[j] == 0: f[i] = max(f[i], f[j] + 1) if f[k] < f[i]: k = i m = f[k] i = k ans = [] while m: if nums[k] % nums[i] == 0 and f[i] == m: ans.append(nums[i]) k, m = i, m - 1 i -= 1 return ans
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
Rust
impl Solution { pub fn largest_divisible_subset(nums: Vec<i32>) -> Vec<i32> { let mut nums = nums; nums.sort(); let n = nums.len(); let mut f = vec![1; n]; let mut k = 0; for i in 0..n { for j in 0..i { if nums[i] % nums[j] == 0 { f[i] = f[i].max(f[j] + 1); } } if f[k] < f[i] { k = i; } } let mut m = f[k]; let mut ans = Vec::new(); for i in (0..=k).rev() { if nums[k] % nums[i] == 0 && f[i] == m { ans.push(nums[i]); k = i; m -= 1; } } ans } }
368
Largest Divisible Subset
Medium
<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p> <ul> <li><code>answer[i] % answer[j] == 0</code>, or</li> <li><code>answer[j] % answer[i] == 0</code></li> </ul> <p>If there are multiple solutions, return any of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> [1,3] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,8] <strong>Output:</strong> [1,2,4,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li>All the integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array; Math; Dynamic Programming; Sorting
TypeScript
function largestDivisibleSubset(nums: number[]): number[] { nums.sort((a, b) => a - b); const n = nums.length; const f: number[] = Array(n).fill(1); let k = 0; for (let i = 0; i < n; ++i) { for (let j = 0; j < i; ++j) { if (nums[i] % nums[j] === 0) { f[i] = Math.max(f[i], f[j] + 1); } } if (f[k] < f[i]) { k = i; } } let m = f[k]; const ans: number[] = []; for (let i = k; m > 0; --i) { if (nums[k] % nums[i] === 0 && f[i] === m) { ans.push(nums[i]); k = i; --m; } } return ans; }
369
Plus One Linked List
Medium
<p>Given a non-negative integer represented as a linked list of digits, <em>plus one to the integer</em>.</p> <p>The digits are stored such that the most significant digit is at the <code>head</code> of the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> head = [1,2,3] <strong>Output:</strong> [1,2,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> head = [0] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>The number represented by the linked list does not contain leading zeros except for the zero itself.&nbsp;</li> </ul>
Linked List; Math
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* plusOne(ListNode* head) { ListNode* dummy = new ListNode(0, head); ListNode* target = dummy; for (; head; head = head->next) { if (head->val != 9) { target = head; } } target->val++; for (target = target->next; target; target = target->next) { target->val = 0; } return dummy->val ? dummy : dummy->next; } };
369
Plus One Linked List
Medium
<p>Given a non-negative integer represented as a linked list of digits, <em>plus one to the integer</em>.</p> <p>The digits are stored such that the most significant digit is at the <code>head</code> of the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> head = [1,2,3] <strong>Output:</strong> [1,2,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> head = [0] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>The number represented by the linked list does not contain leading zeros except for the zero itself.&nbsp;</li> </ul>
Linked List; Math
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func plusOne(head *ListNode) *ListNode { dummy := &ListNode{0, head} target := dummy for head != nil { if head.Val != 9 { target = head } head = head.Next } target.Val++ for target = target.Next; target != nil; target = target.Next { target.Val = 0 } if dummy.Val == 1 { return dummy } return dummy.Next }
369
Plus One Linked List
Medium
<p>Given a non-negative integer represented as a linked list of digits, <em>plus one to the integer</em>.</p> <p>The digits are stored such that the most significant digit is at the <code>head</code> of the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> head = [1,2,3] <strong>Output:</strong> [1,2,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> head = [0] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>The number represented by the linked list does not contain leading zeros except for the zero itself.&nbsp;</li> </ul>
Linked List; Math
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode plusOne(ListNode head) { ListNode dummy = new ListNode(0, head); ListNode target = dummy; while (head != null) { if (head.val != 9) { target = head; } head = head.next; } ++target.val; target = target.next; while (target != null) { target.val = 0; target = target.next; } return dummy.val == 1 ? dummy : dummy.next; } }
369
Plus One Linked List
Medium
<p>Given a non-negative integer represented as a linked list of digits, <em>plus one to the integer</em>.</p> <p>The digits are stored such that the most significant digit is at the <code>head</code> of the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> head = [1,2,3] <strong>Output:</strong> [1,2,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> head = [0] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>The number represented by the linked list does not contain leading zeros except for the zero itself.&nbsp;</li> </ul>
Linked List; Math
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def plusOne(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0, head) target = dummy while head: if head.val != 9: target = head head = head.next target.val += 1 target = target.next while target: target.val = 0 target = target.next return dummy if dummy.val else dummy.next
369
Plus One Linked List
Medium
<p>Given a non-negative integer represented as a linked list of digits, <em>plus one to the integer</em>.</p> <p>The digits are stored such that the most significant digit is at the <code>head</code> of the list.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> head = [1,2,3] <strong>Output:</strong> [1,2,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> head = [0] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>The number represented by the linked list does not contain leading zeros except for the zero itself.&nbsp;</li> </ul>
Linked List; Math
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function plusOne(head: ListNode | null): ListNode | null { const dummy = new ListNode(0, head); let target = dummy; while (head) { if (head.val !== 9) { target = head; } head = head.next; } target.val++; for (target = target.next; target; target = target.next) { target.val = 0; } return dummy.val ? dummy : dummy.next; }
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
C++
class Solution { public: vector<int> getModifiedArray(int length, vector<vector<int>>& updates) { vector<int> d(length); for (const auto& e : updates) { int l = e[0], r = e[1], c = e[2]; d[l] += c; if (r + 1 < length) { d[r + 1] -= c; } } for (int i = 1; i < length; ++i) { d[i] += d[i - 1]; } return d; } };
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Go
func getModifiedArray(length int, updates [][]int) []int { d := make([]int, length) for _, e := range updates { l, r, c := e[0], e[1], e[2] d[l] += c if r+1 < length { d[r+1] -= c } } for i := 1; i < length; i++ { d[i] += d[i-1] } return d }
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Java
class Solution { public int[] getModifiedArray(int length, int[][] updates) { int[] d = new int[length]; for (var e : updates) { int l = e[0], r = e[1], c = e[2]; d[l] += c; if (r + 1 < length) { d[r + 1] -= c; } } for (int i = 1; i < length; ++i) { d[i] += d[i - 1]; } return d; } }
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
JavaScript
/** * @param {number} length * @param {number[][]} updates * @return {number[]} */ var getModifiedArray = function (length, updates) { const d = Array(length).fill(0); for (const [l, r, c] of updates) { d[l] += c; if (r + 1 < length) { d[r + 1] -= c; } } for (let i = 1; i < length; ++i) { d[i] += d[i - 1]; } return d; };
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Python
class Solution: def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: d = [0] * length for l, r, c in updates: d[l] += c if r + 1 < length: d[r + 1] -= c return list(accumulate(d))
370
Range Addition
Medium
<p>You are given an integer <code>length</code> and an array <code>updates</code> where <code>updates[i] = [startIdx<sub>i</sub>, endIdx<sub>i</sub>, inc<sub>i</sub>]</code>.</p> <p>You have an array <code>arr</code> of length <code>length</code> with all zeros, and you have some operation to apply on <code>arr</code>. In the <code>i<sup>th</sup></code> operation, you should increment all the elements <code>arr[startIdx<sub>i</sub>], arr[startIdx<sub>i</sub> + 1], ..., arr[endIdx<sub>i</sub>]</code> by <code>inc<sub>i</sub></code>.</p> <p>Return <code>arr</code> <em>after applying all the</em> <code>updates</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0370.Range%20Addition/images/rangeadd-grid.jpg" style="width: 413px; height: 573px;" /> <pre> <strong>Input:</strong> length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]] <strong>Output:</strong> [-2,0,3,5,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]] <strong>Output:</strong> [0,-4,2,2,2,4,4,-4,-4,-4] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= updates.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIdx<sub>i</sub> &lt;= endIdx<sub>i</sub> &lt; length</code></li> <li><code>-1000 &lt;= inc<sub>i</sub> &lt;= 1000</code></li> </ul>
Array; Prefix Sum
TypeScript
function getModifiedArray(length: number, updates: number[][]): number[] { const d: number[] = Array(length).fill(0); for (const [l, r, c] of updates) { d[l] += c; if (r + 1 < length) { d[r + 1] -= c; } } for (let i = 1; i < length; ++i) { d[i] += d[i - 1]; } return d; }
371
Sum of Two Integers
Medium
<p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> a = 1, b = 2 <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> a = 2, b = 3 <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000 &lt;= a, b &lt;= 1000</code></li> </ul>
Bit Manipulation; Math
C++
class Solution { public: int getSum(int a, int b) { while (b) { unsigned int carry = (unsigned int) (a & b) << 1; a = a ^ b; b = carry; } return a; } };
371
Sum of Two Integers
Medium
<p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> a = 1, b = 2 <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> a = 2, b = 3 <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000 &lt;= a, b &lt;= 1000</code></li> </ul>
Bit Manipulation; Math
Go
func getSum(a int, b int) int { for b != 0 { s := a ^ b b = (a & b) << 1 a = s } return a }
371
Sum of Two Integers
Medium
<p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> a = 1, b = 2 <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> a = 2, b = 3 <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000 &lt;= a, b &lt;= 1000</code></li> </ul>
Bit Manipulation; Math
Java
class Solution { public int getSum(int a, int b) { return b == 0 ? a : getSum(a ^ b, (a & b) << 1); } }
371
Sum of Two Integers
Medium
<p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> a = 1, b = 2 <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> a = 2, b = 3 <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000 &lt;= a, b &lt;= 1000</code></li> </ul>
Bit Manipulation; Math
Python
class Solution: def getSum(self, a: int, b: int) -> int: a, b = a & 0xFFFFFFFF, b & 0xFFFFFFFF while b: carry = ((a & b) << 1) & 0xFFFFFFFF a, b = a ^ b, carry return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
372
Super Pow
Medium
<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [3] <strong>Output:</strong> 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [1,0] <strong>Output:</strong> 1024 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 1, b = [4,3,3,8,5,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= b.length &lt;= 2000</code></li> <li><code>0 &lt;= b[i] &lt;= 9</code></li> <li><code>b</code> does not contain leading zeros.</li> </ul>
Math; Divide and Conquer
C++
class Solution { public: int superPow(int a, vector<int>& b) { using ll = long long; const int mod = 1337; ll ans = 1; auto qpow = [&](ll a, int n) { ll ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; }; for (int i = b.size() - 1; ~i; --i) { ans = ans * qpow(a, b[i]) % mod; a = qpow(a, 10); } return ans; } };
372
Super Pow
Medium
<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [3] <strong>Output:</strong> 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [1,0] <strong>Output:</strong> 1024 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 1, b = [4,3,3,8,5,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= b.length &lt;= 2000</code></li> <li><code>0 &lt;= b[i] &lt;= 9</code></li> <li><code>b</code> does not contain leading zeros.</li> </ul>
Math; Divide and Conquer
Go
func superPow(a int, b []int) int { const mod int = 1337 ans := 1 qpow := func(a, n int) int { ans := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { ans = ans * a % mod } a = a * a % mod } return ans } for i := len(b) - 1; i >= 0; i-- { ans = ans * qpow(a, b[i]) % mod a = qpow(a, 10) } return ans }
372
Super Pow
Medium
<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [3] <strong>Output:</strong> 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [1,0] <strong>Output:</strong> 1024 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 1, b = [4,3,3,8,5,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= b.length &lt;= 2000</code></li> <li><code>0 &lt;= b[i] &lt;= 9</code></li> <li><code>b</code> does not contain leading zeros.</li> </ul>
Math; Divide and Conquer
Java
class Solution { private final int mod = 1337; public int superPow(int a, int[] b) { long ans = 1; for (int i = b.length - 1; i >= 0; --i) { ans = ans * qpow(a, b[i]) % mod; a = qpow(a, 10); } return (int) ans; } private long qpow(long a, int n) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return ans; } }
372
Super Pow
Medium
<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [3] <strong>Output:</strong> 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [1,0] <strong>Output:</strong> 1024 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 1, b = [4,3,3,8,5,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= b.length &lt;= 2000</code></li> <li><code>0 &lt;= b[i] &lt;= 9</code></li> <li><code>b</code> does not contain leading zeros.</li> </ul>
Math; Divide and Conquer
Python
class Solution: def superPow(self, a: int, b: List[int]) -> int: mod = 1337 ans = 1 for e in b[::-1]: ans = ans * pow(a, e, mod) % mod a = pow(a, 10, mod) return ans
372
Super Pow
Medium
<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [3] <strong>Output:</strong> 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 2, b = [1,0] <strong>Output:</strong> 1024 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 1, b = [4,3,3,8,5,2] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= b.length &lt;= 2000</code></li> <li><code>0 &lt;= b[i] &lt;= 9</code></li> <li><code>b</code> does not contain leading zeros.</li> </ul>
Math; Divide and Conquer
TypeScript
function superPow(a: number, b: number[]): number { let ans = 1; const mod = 1337; const qpow = (a: number, n: number): number => { let ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = Number((BigInt(ans) * BigInt(a)) % BigInt(mod)); } a = Number((BigInt(a) * BigInt(a)) % BigInt(mod)); } return ans; }; for (let i = b.length - 1; ~i; --i) { ans = Number((BigInt(ans) * BigInt(qpow(a, b[i]))) % BigInt(mod)); a = qpow(a, 10); } return ans; }
373
Find K Pairs with Smallest Sums
Medium
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> sorted in <strong>non-decreasing&nbsp;order</strong> and an integer <code>k</code>.</p> <p>Define a pair <code>(u, v)</code> which consists of one element from the first array and one element from the second array.</p> <p>Return <em>the</em> <code>k</code> <em>pairs</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>with the smallest sums</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3 <strong>Output:</strong> [[1,2],[1,4],[1,6]] <strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2 <strong>Output:</strong> [[1,1],[1,1]] <strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums1</code> and <code>nums2</code> both are sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li> </ul>
Array; Heap (Priority Queue)
C++
class Solution { public: vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { auto cmp = [&nums1, &nums2](const pair<int, int>& a, const pair<int, int>& b) { return nums1[a.first] + nums2[a.second] > nums1[b.first] + nums2[b.second]; }; int m = nums1.size(); int n = nums2.size(); vector<vector<int>> ans; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp); for (int i = 0; i < min(k, m); i++) pq.emplace(i, 0); while (k-- && !pq.empty()) { auto [x, y] = pq.top(); pq.pop(); ans.emplace_back(initializer_list<int>{nums1[x], nums2[y]}); if (y + 1 < n) pq.emplace(x, y + 1); } return ans; } };
373
Find K Pairs with Smallest Sums
Medium
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> sorted in <strong>non-decreasing&nbsp;order</strong> and an integer <code>k</code>.</p> <p>Define a pair <code>(u, v)</code> which consists of one element from the first array and one element from the second array.</p> <p>Return <em>the</em> <code>k</code> <em>pairs</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>with the smallest sums</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3 <strong>Output:</strong> [[1,2],[1,4],[1,6]] <strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2 <strong>Output:</strong> [[1,1],[1,1]] <strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums1</code> and <code>nums2</code> both are sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li> </ul>
Array; Heap (Priority Queue)
Go
func kSmallestPairs(nums1, nums2 []int, k int) (ans [][]int) { m, n := len(nums1), len(nums2) h := hp{nil, nums1, nums2} for i := 0; i < k && i < m; i++ { h.data = append(h.data, pair{i, 0}) } for h.Len() > 0 && len(ans) < k { p := heap.Pop(&h).(pair) i, j := p.i, p.j ans = append(ans, []int{nums1[i], nums2[j]}) if j+1 < n { heap.Push(&h, pair{i, j + 1}) } } return } type pair struct{ i, j int } type hp struct { data []pair nums1, nums2 []int } func (h hp) Len() int { return len(h.data) } func (h hp) Less(i, j int) bool { a, b := h.data[i], h.data[j] return h.nums1[a.i]+h.nums2[a.j] < h.nums1[b.i]+h.nums2[b.j] } func (h hp) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } func (h *hp) Push(v any) { h.data = append(h.data, v.(pair)) } func (h *hp) Pop() any { a := h.data; v := a[len(a)-1]; h.data = a[:len(a)-1]; return v }
373
Find K Pairs with Smallest Sums
Medium
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> sorted in <strong>non-decreasing&nbsp;order</strong> and an integer <code>k</code>.</p> <p>Define a pair <code>(u, v)</code> which consists of one element from the first array and one element from the second array.</p> <p>Return <em>the</em> <code>k</code> <em>pairs</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>with the smallest sums</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3 <strong>Output:</strong> [[1,2],[1,4],[1,6]] <strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2 <strong>Output:</strong> [[1,1],[1,1]] <strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums1</code> and <code>nums2</code> both are sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li> </ul>
Array; Heap (Priority Queue)
Java
class Solution { public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) { PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); for (int i = 0; i < Math.min(nums1.length, k); ++i) { q.offer(new int[] {nums1[i] + nums2[0], i, 0}); } List<List<Integer>> ans = new ArrayList<>(); while (!q.isEmpty() && k > 0) { int[] e = q.poll(); ans.add(Arrays.asList(nums1[e[1]], nums2[e[2]])); --k; if (e[2] + 1 < nums2.length) { q.offer(new int[] {nums1[e[1]] + nums2[e[2] + 1], e[1], e[2] + 1}); } } return ans; } }
373
Find K Pairs with Smallest Sums
Medium
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> sorted in <strong>non-decreasing&nbsp;order</strong> and an integer <code>k</code>.</p> <p>Define a pair <code>(u, v)</code> which consists of one element from the first array and one element from the second array.</p> <p>Return <em>the</em> <code>k</code> <em>pairs</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>with the smallest sums</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3 <strong>Output:</strong> [[1,2],[1,4],[1,6]] <strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2 <strong>Output:</strong> [[1,1],[1,1]] <strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums1</code> and <code>nums2</code> both are sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li> </ul>
Array; Heap (Priority Queue)
Python
class Solution: def kSmallestPairs( self, nums1: List[int], nums2: List[int], k: int ) -> List[List[int]]: q = [[u + nums2[0], i, 0] for i, u in enumerate(nums1[:k])] heapify(q) ans = [] while q and k > 0: _, i, j = heappop(q) ans.append([nums1[i], nums2[j]]) k -= 1 if j + 1 < len(nums2): heappush(q, [nums1[i] + nums2[j + 1], i, j + 1]) return ans
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
C++
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */ class Solution { public: int guessNumber(int n) { int left = 1, right = n; while (left < right) { int mid = left + ((right - left) >> 1); if (guess(mid) <= 0) { right = mid; } else { left = mid + 1; } } return left; } };
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
C#
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ public class Solution : GuessGame { public int GuessNumber(int n) { int left = 1, right = n; while (left < right) { int mid = left + ((right - left) >> 1); if (guess(mid) <= 0) { right = mid; } else { left = mid + 1; } } return left; } }
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
Go
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * func guess(num int) int; */ func guessNumber(n int) int { return sort.Search(n, func(i int) bool { i++ return guess(i) <= 0 }) + 1 }
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
Java
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { int left = 1, right = n; while (left < right) { int mid = (left + right) >>> 1; if (guess(mid) <= 0) { right = mid; } else { left = mid + 1; } } return left; } }
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
Python
# The guess API is already defined for you. # @param num, your guess # @return -1 if num is higher than the picked number # 1 if num is lower than the picked number # otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x))
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
Rust
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * unsafe fn guess(num: i32) -> i32 {} */ impl Solution { unsafe fn guessNumber(n: i32) -> i32 { let mut l = 1; let mut r = n; loop { let mid = l + (r - l) / 2; match guess(mid) { -1 => { r = mid - 1; } 1 => { l = mid + 1; } _ => { break mid; } } } } }
374
Guess Number Higher or Lower
Easy
<p>We are playing the Guess Game. The game is as follows:</p> <p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked (the number I picked stays the same throughout the game).</p> <p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p> <p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p> <ul> <li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li> <li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li> <li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li> </ul> <p>Return <em>the number that I picked</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, pick = 6 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, pick = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, pick = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= pick &lt;= n</code></li> </ul>
Binary Search; Interactive
TypeScript
/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * var guess = function(num) {} */ function guessNumber(n: number): number { let l = 1; let r = n; while (l < r) { const mid = (l + r) >>> 1; if (guess(mid) <= 0) { r = mid; } else { l = mid + 1; } } return l; }
375
Guess Number Higher or Lower II
Medium
<p>We are playing the Guessing Game. The game will work as follows:</p> <ol> <li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li> <li>You guess a number.</li> <li>If you guess the right number, <strong>you win the game</strong>.</li> <li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li> <li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li> </ol> <p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/images/graph.png" style="width: 505px; height: 388px;" /> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 16 <strong>Explanation:</strong> The winning strategy is as follows: - The range is [1,10]. Guess 7. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $7. &nbsp; - If my number is higher, the range is [8,10]. Guess 9. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $9. &nbsp; - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, the range is [1,6]. Guess 3. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $3. &nbsp; - If my number is higher, the range is [4,6]. Guess 5. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. &nbsp; - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, the range is [1,2]. Guess 1. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2. - Guess 1. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> </ul>
Math; Dynamic Programming; Game Theory
C++
class Solution { public: int getMoneyAmount(int n) { int f[n + 1][n + 1]; memset(f, 0, sizeof(f)); for (int i = n - 1; i; --i) { for (int j = i + 1; j <= n; ++j) { f[i][j] = j + f[i][j - 1]; for (int k = i; k < j; ++k) { f[i][j] = min(f[i][j], max(f[i][k - 1], f[k + 1][j]) + k); } } } return f[1][n]; } };
375
Guess Number Higher or Lower II
Medium
<p>We are playing the Guessing Game. The game will work as follows:</p> <ol> <li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li> <li>You guess a number.</li> <li>If you guess the right number, <strong>you win the game</strong>.</li> <li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li> <li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li> </ol> <p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/images/graph.png" style="width: 505px; height: 388px;" /> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 16 <strong>Explanation:</strong> The winning strategy is as follows: - The range is [1,10]. Guess 7. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $7. &nbsp; - If my number is higher, the range is [8,10]. Guess 9. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $9. &nbsp; - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, the range is [1,6]. Guess 3. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $3. &nbsp; - If my number is higher, the range is [4,6]. Guess 5. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. &nbsp; - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, the range is [1,2]. Guess 1. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2. - Guess 1. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> </ul>
Math; Dynamic Programming; Game Theory
Go
func getMoneyAmount(n int) int { f := make([][]int, n+1) for i := range f { f[i] = make([]int, n+1) } for i := n - 1; i > 0; i-- { for j := i + 1; j <= n; j++ { f[i][j] = j + f[i][j-1] for k := i; k < j; k++ { f[i][j] = min(f[i][j], k+max(f[i][k-1], f[k+1][j])) } } } return f[1][n] }
375
Guess Number Higher or Lower II
Medium
<p>We are playing the Guessing Game. The game will work as follows:</p> <ol> <li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li> <li>You guess a number.</li> <li>If you guess the right number, <strong>you win the game</strong>.</li> <li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li> <li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li> </ol> <p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/images/graph.png" style="width: 505px; height: 388px;" /> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 16 <strong>Explanation:</strong> The winning strategy is as follows: - The range is [1,10]. Guess 7. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $7. &nbsp; - If my number is higher, the range is [8,10]. Guess 9. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $9. &nbsp; - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, the range is [1,6]. Guess 3. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $3. &nbsp; - If my number is higher, the range is [4,6]. Guess 5. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. &nbsp; - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, the range is [1,2]. Guess 1. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2. - Guess 1. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> </ul>
Math; Dynamic Programming; Game Theory
Java
class Solution { public int getMoneyAmount(int n) { int[][] f = new int[n + 1][n + 1]; for (int i = n - 1; i > 0; --i) { for (int j = i + 1; j <= n; ++j) { f[i][j] = j + f[i][j - 1]; for (int k = i; k < j; ++k) { f[i][j] = Math.min(f[i][j], Math.max(f[i][k - 1], f[k + 1][j]) + k); } } } return f[1][n]; } }
375
Guess Number Higher or Lower II
Medium
<p>We are playing the Guessing Game. The game will work as follows:</p> <ol> <li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li> <li>You guess a number.</li> <li>If you guess the right number, <strong>you win the game</strong>.</li> <li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li> <li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li> </ol> <p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/images/graph.png" style="width: 505px; height: 388px;" /> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 16 <strong>Explanation:</strong> The winning strategy is as follows: - The range is [1,10]. Guess 7. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $7. &nbsp; - If my number is higher, the range is [8,10]. Guess 9. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $9. &nbsp; - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, the range is [1,6]. Guess 3. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $3. &nbsp; - If my number is higher, the range is [4,6]. Guess 5. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. &nbsp; - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, the range is [1,2]. Guess 1. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2. - Guess 1. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> </ul>
Math; Dynamic Programming; Game Theory
Python
class Solution: def getMoneyAmount(self, n: int) -> int: f = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n - 1, 0, -1): for j in range(i + 1, n + 1): f[i][j] = j + f[i][j - 1] for k in range(i, j): f[i][j] = min(f[i][j], max(f[i][k - 1], f[k + 1][j]) + k) return f[1][n]
375
Guess Number Higher or Lower II
Medium
<p>We are playing the Guessing Game. The game will work as follows:</p> <ol> <li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li> <li>You guess a number.</li> <li>If you guess the right number, <strong>you win the game</strong>.</li> <li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li> <li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li> </ol> <p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/images/graph.png" style="width: 505px; height: 388px;" /> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 16 <strong>Explanation:</strong> The winning strategy is as follows: - The range is [1,10]. Guess 7. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $7. &nbsp; - If my number is higher, the range is [8,10]. Guess 9. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $9. &nbsp; - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. &nbsp; - If my number is lower, the range is [1,6]. Guess 3. &nbsp; - If this is my number, your total is $7. Otherwise, you pay $3. &nbsp; - If my number is higher, the range is [4,6]. Guess 5. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. &nbsp; - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. &nbsp; - If my number is lower, the range is [1,2]. Guess 1. &nbsp; - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2. - Guess 1. &nbsp; - If this is my number, your total is $0. Otherwise, you pay $1. &nbsp; - If my number is higher, it must be 2. Guess 2. Your total is $1. The worst case is that you pay $1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> </ul>
Math; Dynamic Programming; Game Theory
TypeScript
function getMoneyAmount(n: number): number { const f: number[][] = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0)); for (let i = n - 1; i; --i) { for (let j = i + 1; j <= n; ++j) { f[i][j] = j + f[i][j - 1]; for (let k = i; k < j; ++k) { f[i][j] = Math.min(f[i][j], k + Math.max(f[i][k - 1], f[k + 1][j])); } } } return f[1][n]; }
376
Wiggle Subsequence
Medium
<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p> <ul> <li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li> <li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li> </ul> <p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p> <p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,4,9,2,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>
Greedy; Array; Dynamic Programming
C++
class Solution { public: int wiggleMaxLength(vector<int>& nums) { int n = nums.size(); int ans = 1; vector<int> f(n, 1); vector<int> g(n, 1); for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) { f[i] = max(f[i], g[j] + 1); } else if (nums[j] > nums[i]) { g[i] = max(g[i], f[j] + 1); } } ans = max({ans, f[i], g[i]}); } return ans; } };
376
Wiggle Subsequence
Medium
<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p> <ul> <li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li> <li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li> </ul> <p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p> <p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,4,9,2,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>
Greedy; Array; Dynamic Programming
Go
func wiggleMaxLength(nums []int) int { n := len(nums) f := make([]int, n) g := make([]int, n) f[0], g[0] = 1, 1 ans := 1 for i := 1; i < n; i++ { for j := 0; j < i; j++ { if nums[j] < nums[i] { f[i] = max(f[i], g[j]+1) } else if nums[j] > nums[i] { g[i] = max(g[i], f[j]+1) } } ans = max(ans, max(f[i], g[i])) } return ans }
376
Wiggle Subsequence
Medium
<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p> <ul> <li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li> <li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li> </ul> <p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p> <p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,4,9,2,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>
Greedy; Array; Dynamic Programming
Java
class Solution { public int wiggleMaxLength(int[] nums) { int n = nums.length; int ans = 1; int[] f = new int[n]; int[] g = new int[n]; f[0] = 1; g[0] = 1; for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) { f[i] = Math.max(f[i], g[j] + 1); } else if (nums[j] > nums[i]) { g[i] = Math.max(g[i], f[j] + 1); } } ans = Math.max(ans, Math.max(f[i], g[i])); } return ans; } }
376
Wiggle Subsequence
Medium
<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p> <ul> <li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li> <li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li> </ul> <p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p> <p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,4,9,2,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>
Greedy; Array; Dynamic Programming
Python
class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: n = len(nums) ans = 1 f = [1] * n g = [1] * n for i in range(1, n): for j in range(i): if nums[j] < nums[i]: f[i] = max(f[i], g[j] + 1) elif nums[j] > nums[i]: g[i] = max(g[i], f[j] + 1) ans = max(ans, f[i], g[i]) return ans
376
Wiggle Subsequence
Medium
<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p> <ul> <li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li> <li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li> </ul> <p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p> <p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,4,9,2,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> There are several subsequences that achieve this length. One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>
Greedy; Array; Dynamic Programming
TypeScript
function wiggleMaxLength(nums: number[]): number { const n = nums.length; const f: number[] = Array(n).fill(1); const g: number[] = Array(n).fill(1); let ans = 1; for (let i = 1; i < n; ++i) { for (let j = 0; j < i; ++j) { if (nums[i] > nums[j]) { f[i] = Math.max(f[i], g[j] + 1); } else if (nums[i] < nums[j]) { g[i] = Math.max(g[i], f[j] + 1); } } ans = Math.max(ans, f[i], g[i]); } return ans; }
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
C++
class Solution { public: int combinationSum4(vector<int>& nums, int target) { int f[target + 1]; memset(f, 0, sizeof(f)); f[0] = 1; for (int i = 1; i <= target; ++i) { for (int x : nums) { if (i >= x && f[i - x] < INT_MAX - f[i]) { f[i] += f[i - x]; } } } return f[target]; } };
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
C#
public class Solution { public int CombinationSum4(int[] nums, int target) { int[] f = new int[target + 1]; f[0] = 1; for (int i = 1; i <= target; ++i) { foreach (int x in nums) { if (i >= x) { f[i] += f[i - x]; } } } return f[target]; } }
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
Go
func combinationSum4(nums []int, target int) int { f := make([]int, target+1) f[0] = 1 for i := 1; i <= target; i++ { for _, x := range nums { if i >= x { f[i] += f[i-x] } } } return f[target] }
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
Java
class Solution { public int combinationSum4(int[] nums, int target) { int[] f = new int[target + 1]; f[0] = 1; for (int i = 1; i <= target; ++i) { for (int x : nums) { if (i >= x) { f[i] += f[i - x]; } } } return f[target]; } }
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var combinationSum4 = function (nums, target) { const f = Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { if (i >= x) { f[i] += f[i - x]; } } } return f[target]; };
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
Python
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: f = [1] + [0] * target for i in range(1, target + 1): for x in nums: if i >= x: f[i] += f[i - x] return f[target]
377
Combination Sum IV
Medium
<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p> <p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 4 <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9], target = 3 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li><code>1 &lt;= target &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
Array; Dynamic Programming
TypeScript
function combinationSum4(nums: number[], target: number): number { const f: number[] = Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { if (i >= x) { f[i] += f[i - x]; } } } return f[target]; }
378
Kth Smallest Element in a Sorted Matrix
Medium
<p>Given an <code>n x n</code> <code>matrix</code> where each of the rows and columns is sorted in ascending order, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest element in the matrix</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> smallest element <strong>in the sorted order</strong>, not the <code>k<sup>th</sup></code> <strong>distinct</strong> element.</p> <p>You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 <strong>Output:</strong> 13 <strong>Explanation:</strong> The elements in the matrix are [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], and the 8<sup>th</sup> smallest number is 13 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[-5]], k = 1 <strong>Output:</strong> -5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the rows and columns of <code>matrix</code> are <strong>guaranteed</strong> to be sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve the problem with a constant memory (i.e., <code>O(1)</code> memory complexity)?</li> <li>Could you solve the problem in <code>O(n)</code> time complexity? The solution may be too advanced for an interview but you may find reading <a href="http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf" target="_blank">this paper</a> fun.</li> </ul>
Array; Binary Search; Matrix; Sorting; Heap (Priority Queue)
C++
class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int n = matrix.size(); int left = matrix[0][0], right = matrix[n - 1][n - 1]; while (left < right) { int mid = left + right >> 1; if (check(matrix, mid, k, n)) { right = mid; } else { left = mid + 1; } } return left; } private: bool check(vector<vector<int>>& matrix, int mid, int k, int n) { int count = 0; int i = n - 1, j = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= mid) { count += (i + 1); ++j; } else { --i; } } return count >= k; } };
378
Kth Smallest Element in a Sorted Matrix
Medium
<p>Given an <code>n x n</code> <code>matrix</code> where each of the rows and columns is sorted in ascending order, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest element in the matrix</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> smallest element <strong>in the sorted order</strong>, not the <code>k<sup>th</sup></code> <strong>distinct</strong> element.</p> <p>You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 <strong>Output:</strong> 13 <strong>Explanation:</strong> The elements in the matrix are [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], and the 8<sup>th</sup> smallest number is 13 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[-5]], k = 1 <strong>Output:</strong> -5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the rows and columns of <code>matrix</code> are <strong>guaranteed</strong> to be sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve the problem with a constant memory (i.e., <code>O(1)</code> memory complexity)?</li> <li>Could you solve the problem in <code>O(n)</code> time complexity? The solution may be too advanced for an interview but you may find reading <a href="http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf" target="_blank">this paper</a> fun.</li> </ul>
Array; Binary Search; Matrix; Sorting; Heap (Priority Queue)
Go
func kthSmallest(matrix [][]int, k int) int { n := len(matrix) left, right := matrix[0][0], matrix[n-1][n-1] for left < right { mid := (left + right) >> 1 if check(matrix, mid, k, n) { right = mid } else { left = mid + 1 } } return left } func check(matrix [][]int, mid, k, n int) bool { count := 0 i, j := n-1, 0 for i >= 0 && j < n { if matrix[i][j] <= mid { count += (i + 1) j++ } else { i-- } } return count >= k }
378
Kth Smallest Element in a Sorted Matrix
Medium
<p>Given an <code>n x n</code> <code>matrix</code> where each of the rows and columns is sorted in ascending order, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest element in the matrix</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> smallest element <strong>in the sorted order</strong>, not the <code>k<sup>th</sup></code> <strong>distinct</strong> element.</p> <p>You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 <strong>Output:</strong> 13 <strong>Explanation:</strong> The elements in the matrix are [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], and the 8<sup>th</sup> smallest number is 13 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[-5]], k = 1 <strong>Output:</strong> -5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the rows and columns of <code>matrix</code> are <strong>guaranteed</strong> to be sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve the problem with a constant memory (i.e., <code>O(1)</code> memory complexity)?</li> <li>Could you solve the problem in <code>O(n)</code> time complexity? The solution may be too advanced for an interview but you may find reading <a href="http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf" target="_blank">this paper</a> fun.</li> </ul>
Array; Binary Search; Matrix; Sorting; Heap (Priority Queue)
Java
class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int left = matrix[0][0], right = matrix[n - 1][n - 1]; while (left < right) { int mid = (left + right) >>> 1; if (check(matrix, mid, k, n)) { right = mid; } else { left = mid + 1; } } return left; } private boolean check(int[][] matrix, int mid, int k, int n) { int count = 0; int i = n - 1, j = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= mid) { count += (i + 1); ++j; } else { --i; } } return count >= k; } }
378
Kth Smallest Element in a Sorted Matrix
Medium
<p>Given an <code>n x n</code> <code>matrix</code> where each of the rows and columns is sorted in ascending order, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest element in the matrix</em>.</p> <p>Note that it is the <code>k<sup>th</sup></code> smallest element <strong>in the sorted order</strong>, not the <code>k<sup>th</sup></code> <strong>distinct</strong> element.</p> <p>You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 <strong>Output:</strong> 13 <strong>Explanation:</strong> The elements in the matrix are [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], and the 8<sup>th</sup> smallest number is 13 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> matrix = [[-5]], k = 1 <strong>Output:</strong> -5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == matrix.length == matrix[i].length</code></li> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li> <li>All the rows and columns of <code>matrix</code> are <strong>guaranteed</strong> to be sorted in <strong>non-decreasing order</strong>.</li> <li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve the problem with a constant memory (i.e., <code>O(1)</code> memory complexity)?</li> <li>Could you solve the problem in <code>O(n)</code> time complexity? The solution may be too advanced for an interview but you may find reading <a href="http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf" target="_blank">this paper</a> fun.</li> </ul>
Array; Binary Search; Matrix; Sorting; Heap (Priority Queue)
Python
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: def check(matrix, mid, k, n): count = 0 i, j = n - 1, 0 while i >= 0 and j < n: if matrix[i][j] <= mid: count += i + 1 j += 1 else: i -= 1 return count >= k n = len(matrix) left, right = matrix[0][0], matrix[n - 1][n - 1] while left < right: mid = (left + right) >> 1 if check(matrix, mid, k, n): right = mid else: left = mid + 1 return left
379
Design Phone Directory
Medium
<p>Design a phone directory that initially has <code>maxNumbers</code> empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.</p> <p>Implement the <code>PhoneDirectory</code> class:</p> <ul> <li><code>PhoneDirectory(int maxNumbers)</code> Initializes the phone directory with the number of available slots <code>maxNumbers</code>.</li> <li><code>int get()</code> Provides a number that is not assigned to anyone. Returns <code>-1</code> if no number is available.</li> <li><code>bool check(int number)</code> Returns <code>true</code> if the slot <code>number</code> is available and <code>false</code> otherwise.</li> <li><code>void release(int number)</code> Recycles or releases the slot <code>number</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PhoneDirectory&quot;, &quot;get&quot;, &quot;get&quot;, &quot;check&quot;, &quot;get&quot;, &quot;check&quot;, &quot;release&quot;, &quot;check&quot;] [[3], [], [], [2], [], [2], [2], [2]] <strong>Output</strong> [null, 0, 1, true, 2, false, null, true] <strong>Explanation</strong> PhoneDirectory phoneDirectory = new PhoneDirectory(3); phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0. phoneDirectory.get(); // Assume it returns 1. phoneDirectory.check(2); // The number 2 is available, so return true. phoneDirectory.get(); // It returns 2, the only number that is left. phoneDirectory.check(2); // The number 2 is no longer available, so return false. phoneDirectory.release(2); // Release number 2 back to the pool. phoneDirectory.check(2); // Number 2 is available again, return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= maxNumbers &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= number &lt; maxNumbers</code></li> <li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>get</code>, <code>check</code>, and <code>release</code>.</li> </ul>
Design; Queue; Array; Hash Table; Linked List
C++
class PhoneDirectory { public: PhoneDirectory(int maxNumbers) { for (int i = 0; i < maxNumbers; ++i) { available.insert(i); } } int get() { if (available.empty()) { return -1; } int x = *available.begin(); available.erase(x); return x; } bool check(int number) { return available.contains(number); } void release(int number) { available.insert(number); } private: unordered_set<int> available; }; /** * Your PhoneDirectory object will be instantiated and called as such: * PhoneDirectory* obj = new PhoneDirectory(maxNumbers); * int param_1 = obj->get(); * bool param_2 = obj->check(number); * obj->release(number); */
379
Design Phone Directory
Medium
<p>Design a phone directory that initially has <code>maxNumbers</code> empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.</p> <p>Implement the <code>PhoneDirectory</code> class:</p> <ul> <li><code>PhoneDirectory(int maxNumbers)</code> Initializes the phone directory with the number of available slots <code>maxNumbers</code>.</li> <li><code>int get()</code> Provides a number that is not assigned to anyone. Returns <code>-1</code> if no number is available.</li> <li><code>bool check(int number)</code> Returns <code>true</code> if the slot <code>number</code> is available and <code>false</code> otherwise.</li> <li><code>void release(int number)</code> Recycles or releases the slot <code>number</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PhoneDirectory&quot;, &quot;get&quot;, &quot;get&quot;, &quot;check&quot;, &quot;get&quot;, &quot;check&quot;, &quot;release&quot;, &quot;check&quot;] [[3], [], [], [2], [], [2], [2], [2]] <strong>Output</strong> [null, 0, 1, true, 2, false, null, true] <strong>Explanation</strong> PhoneDirectory phoneDirectory = new PhoneDirectory(3); phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0. phoneDirectory.get(); // Assume it returns 1. phoneDirectory.check(2); // The number 2 is available, so return true. phoneDirectory.get(); // It returns 2, the only number that is left. phoneDirectory.check(2); // The number 2 is no longer available, so return false. phoneDirectory.release(2); // Release number 2 back to the pool. phoneDirectory.check(2); // Number 2 is available again, return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= maxNumbers &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= number &lt; maxNumbers</code></li> <li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>get</code>, <code>check</code>, and <code>release</code>.</li> </ul>
Design; Queue; Array; Hash Table; Linked List
Go
type PhoneDirectory struct { available map[int]bool } func Constructor(maxNumbers int) PhoneDirectory { available := make(map[int]bool) for i := 0; i < maxNumbers; i++ { available[i] = true } return PhoneDirectory{available} } func (this *PhoneDirectory) Get() int { for k := range this.available { delete(this.available, k) return k } return -1 } func (this *PhoneDirectory) Check(number int) bool { _, ok := this.available[number] return ok } func (this *PhoneDirectory) Release(number int) { this.available[number] = true } /** * Your PhoneDirectory object will be instantiated and called as such: * obj := Constructor(maxNumbers); * param_1 := obj.Get(); * param_2 := obj.Check(number); * obj.Release(number); */
379
Design Phone Directory
Medium
<p>Design a phone directory that initially has <code>maxNumbers</code> empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.</p> <p>Implement the <code>PhoneDirectory</code> class:</p> <ul> <li><code>PhoneDirectory(int maxNumbers)</code> Initializes the phone directory with the number of available slots <code>maxNumbers</code>.</li> <li><code>int get()</code> Provides a number that is not assigned to anyone. Returns <code>-1</code> if no number is available.</li> <li><code>bool check(int number)</code> Returns <code>true</code> if the slot <code>number</code> is available and <code>false</code> otherwise.</li> <li><code>void release(int number)</code> Recycles or releases the slot <code>number</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PhoneDirectory&quot;, &quot;get&quot;, &quot;get&quot;, &quot;check&quot;, &quot;get&quot;, &quot;check&quot;, &quot;release&quot;, &quot;check&quot;] [[3], [], [], [2], [], [2], [2], [2]] <strong>Output</strong> [null, 0, 1, true, 2, false, null, true] <strong>Explanation</strong> PhoneDirectory phoneDirectory = new PhoneDirectory(3); phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0. phoneDirectory.get(); // Assume it returns 1. phoneDirectory.check(2); // The number 2 is available, so return true. phoneDirectory.get(); // It returns 2, the only number that is left. phoneDirectory.check(2); // The number 2 is no longer available, so return false. phoneDirectory.release(2); // Release number 2 back to the pool. phoneDirectory.check(2); // Number 2 is available again, return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= maxNumbers &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= number &lt; maxNumbers</code></li> <li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>get</code>, <code>check</code>, and <code>release</code>.</li> </ul>
Design; Queue; Array; Hash Table; Linked List
Java
class PhoneDirectory { private Set<Integer> available = new HashSet<>(); public PhoneDirectory(int maxNumbers) { for (int i = 0; i < maxNumbers; ++i) { available.add(i); } } public int get() { if (available.isEmpty()) { return -1; } int x = available.iterator().next(); available.remove(x); return x; } public boolean check(int number) { return available.contains(number); } public void release(int number) { available.add(number); } } /** * Your PhoneDirectory object will be instantiated and called as such: * PhoneDirectory obj = new PhoneDirectory(maxNumbers); * int param_1 = obj.get(); * boolean param_2 = obj.check(number); * obj.release(number); */
379
Design Phone Directory
Medium
<p>Design a phone directory that initially has <code>maxNumbers</code> empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.</p> <p>Implement the <code>PhoneDirectory</code> class:</p> <ul> <li><code>PhoneDirectory(int maxNumbers)</code> Initializes the phone directory with the number of available slots <code>maxNumbers</code>.</li> <li><code>int get()</code> Provides a number that is not assigned to anyone. Returns <code>-1</code> if no number is available.</li> <li><code>bool check(int number)</code> Returns <code>true</code> if the slot <code>number</code> is available and <code>false</code> otherwise.</li> <li><code>void release(int number)</code> Recycles or releases the slot <code>number</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PhoneDirectory&quot;, &quot;get&quot;, &quot;get&quot;, &quot;check&quot;, &quot;get&quot;, &quot;check&quot;, &quot;release&quot;, &quot;check&quot;] [[3], [], [], [2], [], [2], [2], [2]] <strong>Output</strong> [null, 0, 1, true, 2, false, null, true] <strong>Explanation</strong> PhoneDirectory phoneDirectory = new PhoneDirectory(3); phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0. phoneDirectory.get(); // Assume it returns 1. phoneDirectory.check(2); // The number 2 is available, so return true. phoneDirectory.get(); // It returns 2, the only number that is left. phoneDirectory.check(2); // The number 2 is no longer available, so return false. phoneDirectory.release(2); // Release number 2 back to the pool. phoneDirectory.check(2); // Number 2 is available again, return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= maxNumbers &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= number &lt; maxNumbers</code></li> <li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>get</code>, <code>check</code>, and <code>release</code>.</li> </ul>
Design; Queue; Array; Hash Table; Linked List
Python
class PhoneDirectory: def __init__(self, maxNumbers: int): self.available = set(range(maxNumbers)) def get(self) -> int: if not self.available: return -1 return self.available.pop() def check(self, number: int) -> bool: return number in self.available def release(self, number: int) -> None: self.available.add(number) # Your PhoneDirectory object will be instantiated and called as such: # obj = PhoneDirectory(maxNumbers) # param_1 = obj.get() # param_2 = obj.check(number) # obj.release(number)
379
Design Phone Directory
Medium
<p>Design a phone directory that initially has <code>maxNumbers</code> empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.</p> <p>Implement the <code>PhoneDirectory</code> class:</p> <ul> <li><code>PhoneDirectory(int maxNumbers)</code> Initializes the phone directory with the number of available slots <code>maxNumbers</code>.</li> <li><code>int get()</code> Provides a number that is not assigned to anyone. Returns <code>-1</code> if no number is available.</li> <li><code>bool check(int number)</code> Returns <code>true</code> if the slot <code>number</code> is available and <code>false</code> otherwise.</li> <li><code>void release(int number)</code> Recycles or releases the slot <code>number</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PhoneDirectory&quot;, &quot;get&quot;, &quot;get&quot;, &quot;check&quot;, &quot;get&quot;, &quot;check&quot;, &quot;release&quot;, &quot;check&quot;] [[3], [], [], [2], [], [2], [2], [2]] <strong>Output</strong> [null, 0, 1, true, 2, false, null, true] <strong>Explanation</strong> PhoneDirectory phoneDirectory = new PhoneDirectory(3); phoneDirectory.get(); // It can return any available phone number. Here we assume it returns 0. phoneDirectory.get(); // Assume it returns 1. phoneDirectory.check(2); // The number 2 is available, so return true. phoneDirectory.get(); // It returns 2, the only number that is left. phoneDirectory.check(2); // The number 2 is no longer available, so return false. phoneDirectory.release(2); // Release number 2 back to the pool. phoneDirectory.check(2); // Number 2 is available again, return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= maxNumbers &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= number &lt; maxNumbers</code></li> <li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>get</code>, <code>check</code>, and <code>release</code>.</li> </ul>
Design; Queue; Array; Hash Table; Linked List
TypeScript
class PhoneDirectory { private available: Set<number> = new Set(); constructor(maxNumbers: number) { for (let i = 0; i < maxNumbers; ++i) { this.available.add(i); } } get(): number { const [x] = this.available; if (x === undefined) { return -1; } this.available.delete(x); return x; } check(number: number): boolean { return this.available.has(number); } release(number: number): void { this.available.add(number); } } /** * Your PhoneDirectory object will be instantiated and called as such: * var obj = new PhoneDirectory(maxNumbers) * var param_1 = obj.get() * var param_2 = obj.check(number) * obj.release(number) */