id
int64 1
3.65k
| 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
|
---|---|---|---|---|---|---|
3,155 |
Maximum Number of Upgradable Servers
|
Medium
|
<p>You have <code>n</code> data centers and need to upgrade their servers.</p>
<p>You are given four arrays <code>count</code>, <code>upgrade</code>, <code>sell</code>, and <code>money</code> of length <code>n</code>, which show:</p>
<ul>
<li>The number of servers</li>
<li>The cost of upgrading a single server</li>
<li>The money you get by selling a server</li>
<li>The money you initially have</li>
</ul>
<p>for each data center respectively.</p>
<p>Return an array <code>answer</code>, where for each data center, the corresponding element in <code>answer</code> represents the <strong>maximum</strong> number of servers that can be upgraded.</p>
<p>Note that the money from one data center <strong>cannot</strong> be used for another data center.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the first data center, if we sell one server, we'll have <code>8 + 4 = 12</code> units of money and we can upgrade the remaining 3 servers.</p>
<p>For the second data center, if we sell one server, we'll have <code>9 + 2 = 11</code> units of money and we can upgrade the remaining 2 servers.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [1], upgrade = [2], sell = [1], money = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= count.length == upgrade.length == sell.length == money.length <= 10<sup>5</sup></code></li>
<li><code>1 <= count[i], upgrade[i], sell[i], money[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Math; Binary Search
|
C++
|
class Solution {
public:
vector<int> maxUpgrades(vector<int>& count, vector<int>& upgrade, vector<int>& sell, vector<int>& money) {
int n = count.size();
vector<int> ans;
for (int i = 0; i < n; ++i) {
ans.push_back(min(count[i], (int) ((1LL * count[i] * sell[i] + money[i]) / (upgrade[i] + sell[i]))));
}
return ans;
}
};
|
3,155 |
Maximum Number of Upgradable Servers
|
Medium
|
<p>You have <code>n</code> data centers and need to upgrade their servers.</p>
<p>You are given four arrays <code>count</code>, <code>upgrade</code>, <code>sell</code>, and <code>money</code> of length <code>n</code>, which show:</p>
<ul>
<li>The number of servers</li>
<li>The cost of upgrading a single server</li>
<li>The money you get by selling a server</li>
<li>The money you initially have</li>
</ul>
<p>for each data center respectively.</p>
<p>Return an array <code>answer</code>, where for each data center, the corresponding element in <code>answer</code> represents the <strong>maximum</strong> number of servers that can be upgraded.</p>
<p>Note that the money from one data center <strong>cannot</strong> be used for another data center.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the first data center, if we sell one server, we'll have <code>8 + 4 = 12</code> units of money and we can upgrade the remaining 3 servers.</p>
<p>For the second data center, if we sell one server, we'll have <code>9 + 2 = 11</code> units of money and we can upgrade the remaining 2 servers.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [1], upgrade = [2], sell = [1], money = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= count.length == upgrade.length == sell.length == money.length <= 10<sup>5</sup></code></li>
<li><code>1 <= count[i], upgrade[i], sell[i], money[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Math; Binary Search
|
Go
|
func maxUpgrades(count []int, upgrade []int, sell []int, money []int) (ans []int) {
for i, cnt := range count {
ans = append(ans, min(cnt, (cnt*sell[i]+money[i])/(upgrade[i]+sell[i])))
}
return
}
|
3,155 |
Maximum Number of Upgradable Servers
|
Medium
|
<p>You have <code>n</code> data centers and need to upgrade their servers.</p>
<p>You are given four arrays <code>count</code>, <code>upgrade</code>, <code>sell</code>, and <code>money</code> of length <code>n</code>, which show:</p>
<ul>
<li>The number of servers</li>
<li>The cost of upgrading a single server</li>
<li>The money you get by selling a server</li>
<li>The money you initially have</li>
</ul>
<p>for each data center respectively.</p>
<p>Return an array <code>answer</code>, where for each data center, the corresponding element in <code>answer</code> represents the <strong>maximum</strong> number of servers that can be upgraded.</p>
<p>Note that the money from one data center <strong>cannot</strong> be used for another data center.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the first data center, if we sell one server, we'll have <code>8 + 4 = 12</code> units of money and we can upgrade the remaining 3 servers.</p>
<p>For the second data center, if we sell one server, we'll have <code>9 + 2 = 11</code> units of money and we can upgrade the remaining 2 servers.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [1], upgrade = [2], sell = [1], money = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= count.length == upgrade.length == sell.length == money.length <= 10<sup>5</sup></code></li>
<li><code>1 <= count[i], upgrade[i], sell[i], money[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Math; Binary Search
|
Java
|
class Solution {
public int[] maxUpgrades(int[] count, int[] upgrade, int[] sell, int[] money) {
int n = count.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = Math.min(
count[i], (int) ((1L * count[i] * sell[i] + money[i]) / (upgrade[i] + sell[i])));
}
return ans;
}
}
|
3,155 |
Maximum Number of Upgradable Servers
|
Medium
|
<p>You have <code>n</code> data centers and need to upgrade their servers.</p>
<p>You are given four arrays <code>count</code>, <code>upgrade</code>, <code>sell</code>, and <code>money</code> of length <code>n</code>, which show:</p>
<ul>
<li>The number of servers</li>
<li>The cost of upgrading a single server</li>
<li>The money you get by selling a server</li>
<li>The money you initially have</li>
</ul>
<p>for each data center respectively.</p>
<p>Return an array <code>answer</code>, where for each data center, the corresponding element in <code>answer</code> represents the <strong>maximum</strong> number of servers that can be upgraded.</p>
<p>Note that the money from one data center <strong>cannot</strong> be used for another data center.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the first data center, if we sell one server, we'll have <code>8 + 4 = 12</code> units of money and we can upgrade the remaining 3 servers.</p>
<p>For the second data center, if we sell one server, we'll have <code>9 + 2 = 11</code> units of money and we can upgrade the remaining 2 servers.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [1], upgrade = [2], sell = [1], money = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= count.length == upgrade.length == sell.length == money.length <= 10<sup>5</sup></code></li>
<li><code>1 <= count[i], upgrade[i], sell[i], money[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Math; Binary Search
|
Python
|
class Solution:
def maxUpgrades(
self, count: List[int], upgrade: List[int], sell: List[int], money: List[int]
) -> List[int]:
ans = []
for cnt, cost, income, cash in zip(count, upgrade, sell, money):
ans.append(min(cnt, (cnt * income + cash) // (cost + income)))
return ans
|
3,155 |
Maximum Number of Upgradable Servers
|
Medium
|
<p>You have <code>n</code> data centers and need to upgrade their servers.</p>
<p>You are given four arrays <code>count</code>, <code>upgrade</code>, <code>sell</code>, and <code>money</code> of length <code>n</code>, which show:</p>
<ul>
<li>The number of servers</li>
<li>The cost of upgrading a single server</li>
<li>The money you get by selling a server</li>
<li>The money you initially have</li>
</ul>
<p>for each data center respectively.</p>
<p>Return an array <code>answer</code>, where for each data center, the corresponding element in <code>answer</code> represents the <strong>maximum</strong> number of servers that can be upgraded.</p>
<p>Note that the money from one data center <strong>cannot</strong> be used for another data center.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [4,3], upgrade = [3,5], sell = [4,2], money = [8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the first data center, if we sell one server, we'll have <code>8 + 4 = 12</code> units of money and we can upgrade the remaining 3 servers.</p>
<p>For the second data center, if we sell one server, we'll have <code>9 + 2 = 11</code> units of money and we can upgrade the remaining 2 servers.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">count = [1], upgrade = [2], sell = [1], money = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= count.length == upgrade.length == sell.length == money.length <= 10<sup>5</sup></code></li>
<li><code>1 <= count[i], upgrade[i], sell[i], money[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Math; Binary Search
|
TypeScript
|
function maxUpgrades(
count: number[],
upgrade: number[],
sell: number[],
money: number[],
): number[] {
const n = count.length;
const ans: number[] = [];
for (let i = 0; i < n; ++i) {
const x = ((count[i] * sell[i] + money[i]) / (upgrade[i] + sell[i])) | 0;
ans.push(Math.min(x, count[i]));
}
return ans;
}
|
3,156 |
Employee Task Duration and Concurrent Tasks
|
Hard
|
<p>Table: <code>Tasks</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| task_id | int |
| employee_id | int |
| start_time | datetime |
| end_time | datetime |
+---------------+----------+
(task_id, employee_id) is the primary key for this table.
Each row in this table contains the task identifier, the employee identifier, and the start and end times of each task.
</pre>
<p>Write a solution to find the <strong>total duration</strong> of tasks for <strong>each</strong> employee and the <strong>maximum number of concurrent tasks</strong> an employee handled at <strong>any point in time</strong>. The total duration should be <strong>rounded down</strong> to the nearest number of <strong>full hours</strong>.</p>
<p>Return <em>the result table ordered by</em> <code>employee_id</code><strong> <em>ascending</em></strong><em> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tasks table:</p>
<pre class="example-io">
+---------+-------------+---------------------+---------------------+
| task_id | employee_id | start_time | end_time |
+---------+-------------+---------------------+---------------------+
| 1 | 1001 | 2023-05-01 08:00:00 | 2023-05-01 09:00:00 |
| 2 | 1001 | 2023-05-01 08:30:00 | 2023-05-01 10:30:00 |
| 3 | 1001 | 2023-05-01 11:00:00 | 2023-05-01 12:00:00 |
| 7 | 1001 | 2023-05-01 13:00:00 | 2023-05-01 15:30:00 |
| 4 | 1002 | 2023-05-01 09:00:00 | 2023-05-01 10:00:00 |
| 5 | 1002 | 2023-05-01 09:30:00 | 2023-05-01 11:30:00 |
| 6 | 1003 | 2023-05-01 14:00:00 | 2023-05-01 16:00:00 |
+---------+-------------+---------------------+---------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------+------------------+----------------------+
| employee_id | total_task_hours | max_concurrent_tasks |
+-------------+------------------+----------------------+
| 1001 | 6 | 2 |
| 1002 | 2 | 2 |
| 1003 | 2 | 1 |
+-------------+------------------+----------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For employee ID 1001:
<ul>
<li>Task 1 and Task 2 overlap from 08:30 to 09:00 (30 minutes).</li>
<li>Task 7 has a duration of 150 minutes (2 hours and 30 minutes).</li>
<li>Total task time: 60 (Task 1) + 120 (Task 2) + 60 (Task 3) + 150 (Task 7) - 30 (overlap) = 360 minutes = 6 hours.</li>
<li>Maximum concurrent tasks: 2 (during the overlap period).</li>
</ul>
</li>
<li>For employee ID 1002:
<ul>
<li>Task 4 and Task 5 overlap from 09:30 to 10:00 (30 minutes).</li>
<li>Total task time: 60 (Task 4) + 120 (Task 5) - 30 (overlap) = 150 minutes = 2 hours and 30 minutes.</li>
<li>Total task hours (rounded down): 2 hours.</li>
<li>Maximum concurrent tasks: 2 (during the overlap period).</li>
</ul>
</li>
<li>For employee ID 1003:
<ul>
<li>No overlapping tasks.</li>
<li>Total task time: 120 minutes = 2 hours.</li>
<li>Maximum concurrent tasks: 1.</li>
</ul>
</li>
</ul>
<p><b>Note:</b> Output table is ordered by employee_id in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT DISTINCT employee_id, start_time AS st
FROM Tasks
UNION DISTINCT
SELECT DISTINCT employee_id, end_time AS st
FROM Tasks
),
P AS (
SELECT
*,
LEAD(st) OVER (
PARTITION BY employee_id
ORDER BY st
) AS ed
FROM T
),
S AS (
SELECT
P.*,
COUNT(1) AS concurrent_count
FROM
P
INNER JOIN Tasks USING (employee_id)
WHERE P.st >= Tasks.start_time AND P.ed <= Tasks.end_time
GROUP BY 1, 2, 3
)
SELECT
employee_id,
FLOOR(SUM(TIME_TO_SEC(TIMEDIFF(ed, st)) / 3600)) AS total_task_hours,
MAX(concurrent_count) AS max_concurrent_tasks
FROM S
GROUP BY 1
ORDER BY 1;
|
3,157 |
Find the Level of Tree with Minimum Sum
|
Medium
|
<p>Given the root of a binary tree <code>root</code> where each node has a value, return the level of the tree that has the <strong>minimum</strong> sum of values among all the levels (in case of a tie, return the <strong>lowest</strong> level).</p>
<p><strong>Note</strong> that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [50,6,2,30,80,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-15-46.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 265px; height: 129px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [36,17,10,null,null,24]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-14-18.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,null,5,null,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-19_19-07-20.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>9</sup></code></li>
</ul>
|
Tree; Depth-First Search; Breadth-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:
int minimumLevel(TreeNode* root) {
queue<TreeNode*> q{{root}};
int ans = 0;
long long s = 1LL << 60;
for (int level = 1; q.size(); ++level) {
long long t = 0;
for (int m = q.size(); m; --m) {
TreeNode* node = q.front();
q.pop();
t += node->val;
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
if (s > t) {
s = t;
ans = level;
}
}
return ans;
}
};
|
3,157 |
Find the Level of Tree with Minimum Sum
|
Medium
|
<p>Given the root of a binary tree <code>root</code> where each node has a value, return the level of the tree that has the <strong>minimum</strong> sum of values among all the levels (in case of a tie, return the <strong>lowest</strong> level).</p>
<p><strong>Note</strong> that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [50,6,2,30,80,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-15-46.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 265px; height: 129px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [36,17,10,null,null,24]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-14-18.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,null,5,null,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-19_19-07-20.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>9</sup></code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minimumLevel(root *TreeNode) (ans int) {
q := []*TreeNode{root}
s := math.MaxInt64
for level := 1; len(q) > 0; level++ {
t := 0
for m := len(q); m > 0; m-- {
node := q[0]
q = q[1:]
t += node.Val
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
if s > t {
s = t
ans = level
}
}
return
}
|
3,157 |
Find the Level of Tree with Minimum Sum
|
Medium
|
<p>Given the root of a binary tree <code>root</code> where each node has a value, return the level of the tree that has the <strong>minimum</strong> sum of values among all the levels (in case of a tie, return the <strong>lowest</strong> level).</p>
<p><strong>Note</strong> that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [50,6,2,30,80,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-15-46.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 265px; height: 129px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [36,17,10,null,null,24]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-14-18.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,null,5,null,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-19_19-07-20.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>9</sup></code></li>
</ul>
|
Tree; Depth-First Search; Breadth-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 {
public int minimumLevel(TreeNode root) {
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
int ans = 0;
long s = Long.MAX_VALUE;
for (int level = 1; !q.isEmpty(); ++level) {
long t = 0;
for (int m = q.size(); m > 0; --m) {
TreeNode node = q.poll();
t += node.val;
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
if (s > t) {
s = t;
ans = level;
}
}
return ans;
}
}
|
3,157 |
Find the Level of Tree with Minimum Sum
|
Medium
|
<p>Given the root of a binary tree <code>root</code> where each node has a value, return the level of the tree that has the <strong>minimum</strong> sum of values among all the levels (in case of a tie, return the <strong>lowest</strong> level).</p>
<p><strong>Note</strong> that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [50,6,2,30,80,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-15-46.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 265px; height: 129px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [36,17,10,null,null,24]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-14-18.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,null,5,null,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-19_19-07-20.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>9</sup></code></li>
</ul>
|
Tree; Depth-First Search; Breadth-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 minimumLevel(self, root: Optional[TreeNode]) -> int:
q = deque([root])
ans = 0
level, s = 1, inf
while q:
t = 0
for _ in range(len(q)):
node = q.popleft()
t += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if s > t:
s = t
ans = level
level += 1
return ans
|
3,157 |
Find the Level of Tree with Minimum Sum
|
Medium
|
<p>Given the root of a binary tree <code>root</code> where each node has a value, return the level of the tree that has the <strong>minimum</strong> sum of values among all the levels (in case of a tie, return the <strong>lowest</strong> level).</p>
<p><strong>Note</strong> that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [50,6,2,30,80,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-15-46.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 265px; height: 129px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [36,17,10,null,null,24]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-17_16-14-18.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,null,5,null,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3157.Find%20the%20Level%20of%20Tree%20with%20Minimum%20Sum/images/image_2024-05-19_19-07-20.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 170px; height: 135px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>9</sup></code></li>
</ul>
|
Tree; Depth-First Search; Breadth-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 minimumLevel(root: TreeNode | null): number {
const q: TreeNode[] = [root];
let s = Infinity;
let ans = 0;
for (let level = 1; q.length; ++level) {
const qq: TreeNode[] = [];
let t = 0;
for (const { val, left, right } of q) {
t += val;
left && qq.push(left);
right && qq.push(right);
}
if (s > t) {
s = t;
ans = level;
}
q.splice(0, q.length, ...qq);
}
return ans;
}
|
3,158 |
Find the XOR of Numbers Which Appear Twice
|
Easy
|
<p>You are given an array <code>nums</code>, where each number in the array appears <strong>either</strong><em> </em>once<em> </em>or<em> </em>twice.</p>
<p>Return the bitwise<em> </em><code>XOR</code> of all the numbers that appear twice in the array, or 0 if no number appears twice.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only number that appears twice in <code>nums</code> is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No number appears twice in <code>nums</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Numbers 1 and 2 appeared twice. <code>1 XOR 2 == 3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li>Each number in <code>nums</code> appears either once or twice.</li>
</ul>
|
Bit Manipulation; Array; Hash Table
|
C++
|
class Solution {
public:
int duplicateNumbersXOR(vector<int>& nums) {
int cnt[51]{};
int ans = 0;
for (int x : nums) {
if (++cnt[x] == 2) {
ans ^= x;
}
}
return ans;
}
};
|
3,158 |
Find the XOR of Numbers Which Appear Twice
|
Easy
|
<p>You are given an array <code>nums</code>, where each number in the array appears <strong>either</strong><em> </em>once<em> </em>or<em> </em>twice.</p>
<p>Return the bitwise<em> </em><code>XOR</code> of all the numbers that appear twice in the array, or 0 if no number appears twice.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only number that appears twice in <code>nums</code> is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No number appears twice in <code>nums</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Numbers 1 and 2 appeared twice. <code>1 XOR 2 == 3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li>Each number in <code>nums</code> appears either once or twice.</li>
</ul>
|
Bit Manipulation; Array; Hash Table
|
Go
|
func duplicateNumbersXOR(nums []int) (ans int) {
cnt := [51]int{}
for _, x := range nums {
cnt[x]++
if cnt[x] == 2 {
ans ^= x
}
}
return
}
|
3,158 |
Find the XOR of Numbers Which Appear Twice
|
Easy
|
<p>You are given an array <code>nums</code>, where each number in the array appears <strong>either</strong><em> </em>once<em> </em>or<em> </em>twice.</p>
<p>Return the bitwise<em> </em><code>XOR</code> of all the numbers that appear twice in the array, or 0 if no number appears twice.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only number that appears twice in <code>nums</code> is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No number appears twice in <code>nums</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Numbers 1 and 2 appeared twice. <code>1 XOR 2 == 3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li>Each number in <code>nums</code> appears either once or twice.</li>
</ul>
|
Bit Manipulation; Array; Hash Table
|
Java
|
class Solution {
public int duplicateNumbersXOR(int[] nums) {
int[] cnt = new int[51];
int ans = 0;
for (int x : nums) {
if (++cnt[x] == 2) {
ans ^= x;
}
}
return ans;
}
}
|
3,158 |
Find the XOR of Numbers Which Appear Twice
|
Easy
|
<p>You are given an array <code>nums</code>, where each number in the array appears <strong>either</strong><em> </em>once<em> </em>or<em> </em>twice.</p>
<p>Return the bitwise<em> </em><code>XOR</code> of all the numbers that appear twice in the array, or 0 if no number appears twice.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only number that appears twice in <code>nums</code> is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No number appears twice in <code>nums</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Numbers 1 and 2 appeared twice. <code>1 XOR 2 == 3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li>Each number in <code>nums</code> appears either once or twice.</li>
</ul>
|
Bit Manipulation; Array; Hash Table
|
Python
|
class Solution:
def duplicateNumbersXOR(self, nums: List[int]) -> int:
cnt = Counter(nums)
return reduce(xor, [x for x, v in cnt.items() if v == 2], 0)
|
3,158 |
Find the XOR of Numbers Which Appear Twice
|
Easy
|
<p>You are given an array <code>nums</code>, where each number in the array appears <strong>either</strong><em> </em>once<em> </em>or<em> </em>twice.</p>
<p>Return the bitwise<em> </em><code>XOR</code> of all the numbers that appear twice in the array, or 0 if no number appears twice.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only number that appears twice in <code>nums</code> is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No number appears twice in <code>nums</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Numbers 1 and 2 appeared twice. <code>1 XOR 2 == 3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li>Each number in <code>nums</code> appears either once or twice.</li>
</ul>
|
Bit Manipulation; Array; Hash Table
|
TypeScript
|
function duplicateNumbersXOR(nums: number[]): number {
const cnt: number[] = Array(51).fill(0);
let ans: number = 0;
for (const x of nums) {
if (++cnt[x] === 2) {
ans ^= x;
}
}
return ans;
}
|
3,159 |
Find Occurrences of an Element in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>, an integer array <code>queries</code>, and an integer <code>x</code>.</p>
<p>For each <code>queries[i]</code>, you need to find the index of the <code>queries[i]<sup>th</sup></code> occurrence of <code>x</code> in the <code>nums</code> array. If there are fewer than <code>queries[i]</code> occurrences of <code>x</code>, the answer should be -1 for that query.</p>
<p>Return an integer array <code>answer</code> containing the answers to all queries.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,7], queries = [1,3,2,4], x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,2,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, the first occurrence of 1 is at index 0.</li>
<li>For the 2<sup>nd</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
<li>For the 3<sup>rd</sup> query, the second occurrence of 1 is at index 2.</li>
<li>For the 4<sup>th</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], queries = [10], x = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, 5 doesn't exist in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, queries.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
vector<int> occurrencesOfElement(vector<int>& nums, vector<int>& queries, int x) {
vector<int> ids;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == x) {
ids.push_back(i);
}
}
vector<int> ans;
for (int& i : queries) {
ans.push_back(i - 1 < ids.size() ? ids[i - 1] : -1);
}
return ans;
}
};
|
3,159 |
Find Occurrences of an Element in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>, an integer array <code>queries</code>, and an integer <code>x</code>.</p>
<p>For each <code>queries[i]</code>, you need to find the index of the <code>queries[i]<sup>th</sup></code> occurrence of <code>x</code> in the <code>nums</code> array. If there are fewer than <code>queries[i]</code> occurrences of <code>x</code>, the answer should be -1 for that query.</p>
<p>Return an integer array <code>answer</code> containing the answers to all queries.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,7], queries = [1,3,2,4], x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,2,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, the first occurrence of 1 is at index 0.</li>
<li>For the 2<sup>nd</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
<li>For the 3<sup>rd</sup> query, the second occurrence of 1 is at index 2.</li>
<li>For the 4<sup>th</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], queries = [10], x = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, 5 doesn't exist in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, queries.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func occurrencesOfElement(nums []int, queries []int, x int) (ans []int) {
ids := []int{}
for i, v := range nums {
if v == x {
ids = append(ids, i)
}
}
for _, i := range queries {
if i-1 < len(ids) {
ans = append(ans, ids[i-1])
} else {
ans = append(ans, -1)
}
}
return
}
|
3,159 |
Find Occurrences of an Element in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>, an integer array <code>queries</code>, and an integer <code>x</code>.</p>
<p>For each <code>queries[i]</code>, you need to find the index of the <code>queries[i]<sup>th</sup></code> occurrence of <code>x</code> in the <code>nums</code> array. If there are fewer than <code>queries[i]</code> occurrences of <code>x</code>, the answer should be -1 for that query.</p>
<p>Return an integer array <code>answer</code> containing the answers to all queries.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,7], queries = [1,3,2,4], x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,2,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, the first occurrence of 1 is at index 0.</li>
<li>For the 2<sup>nd</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
<li>For the 3<sup>rd</sup> query, the second occurrence of 1 is at index 2.</li>
<li>For the 4<sup>th</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], queries = [10], x = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, 5 doesn't exist in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, queries.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int[] occurrencesOfElement(int[] nums, int[] queries, int x) {
List<Integer> ids = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == x) {
ids.add(i);
}
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int j = queries[i] - 1;
ans[i] = j < ids.size() ? ids.get(j) : -1;
}
return ans;
}
}
|
3,159 |
Find Occurrences of an Element in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>, an integer array <code>queries</code>, and an integer <code>x</code>.</p>
<p>For each <code>queries[i]</code>, you need to find the index of the <code>queries[i]<sup>th</sup></code> occurrence of <code>x</code> in the <code>nums</code> array. If there are fewer than <code>queries[i]</code> occurrences of <code>x</code>, the answer should be -1 for that query.</p>
<p>Return an integer array <code>answer</code> containing the answers to all queries.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,7], queries = [1,3,2,4], x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,2,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, the first occurrence of 1 is at index 0.</li>
<li>For the 2<sup>nd</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
<li>For the 3<sup>rd</sup> query, the second occurrence of 1 is at index 2.</li>
<li>For the 4<sup>th</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], queries = [10], x = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, 5 doesn't exist in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, queries.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def occurrencesOfElement(
self, nums: List[int], queries: List[int], x: int
) -> List[int]:
ids = [i for i, v in enumerate(nums) if v == x]
return [ids[i - 1] if i - 1 < len(ids) else -1 for i in queries]
|
3,159 |
Find Occurrences of an Element in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>, an integer array <code>queries</code>, and an integer <code>x</code>.</p>
<p>For each <code>queries[i]</code>, you need to find the index of the <code>queries[i]<sup>th</sup></code> occurrence of <code>x</code> in the <code>nums</code> array. If there are fewer than <code>queries[i]</code> occurrences of <code>x</code>, the answer should be -1 for that query.</p>
<p>Return an integer array <code>answer</code> containing the answers to all queries.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,7], queries = [1,3,2,4], x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,2,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, the first occurrence of 1 is at index 0.</li>
<li>For the 2<sup>nd</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
<li>For the 3<sup>rd</sup> query, the second occurrence of 1 is at index 2.</li>
<li>For the 4<sup>th</sup> query, there are only two occurrences of 1 in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], queries = [10], x = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 1<sup>st</sup> query, 5 doesn't exist in <code>nums</code>, so the answer is -1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, queries.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function occurrencesOfElement(nums: number[], queries: number[], x: number): number[] {
const ids: number[] = nums.map((v, i) => (v === x ? i : -1)).filter(v => v !== -1);
return queries.map(i => ids[i - 1] ?? -1);
}
|
3,160 |
Find the Number of Distinct Colors Among the Balls
|
Medium
|
<p>You are given an integer <code>limit</code> and a 2D array <code>queries</code> of size <code>n x 2</code>.</p>
<p>There are <code>limit + 1</code> balls with <strong>distinct</strong> labels in the range <code>[0, limit]</code>. Initially, all balls are uncolored. For every query in <code>queries</code> that is of the form <code>[x, y]</code>, you mark ball <code>x</code> with the color <code>y</code>. After each query, you need to find the number of colors among the balls.</p>
<p>Return an array <code>result</code> of length <code>n</code>, where <code>result[i]</code> denotes the number of colors <em>after</em> <code>i<sup>th</sup></code> query.</p>
<p><strong>Note</strong> that when answering a query, lack of a color <em>will not</em> be considered as a color.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop.gif" style="width: 455px; height: 145px;" /></p>
<ul>
<li>After query 0, ball 1 has color 4.</li>
<li>After query 1, ball 1 has color 4, and ball 2 has color 5.</li>
<li>After query 2, ball 1 has color 3, and ball 2 has color 5.</li>
<li>After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop2.gif" style="width: 457px; height: 144px;" /></strong></p>
<ul>
<li>After query 0, ball 0 has color 1.</li>
<li>After query 1, ball 0 has color 1, and ball 1 has color 2.</li>
<li>After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.</li>
<li>After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.</li>
<li>After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= limit <= 10<sup>9</sup></code></li>
<li><code>1 <= n == queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= limit</code></li>
<li><code>1 <= queries[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Simulation
|
C++
|
class Solution {
public:
vector<int> queryResults(int limit, vector<vector<int>>& queries) {
unordered_map<int, int> g;
unordered_map<int, int> cnt;
vector<int> ans;
for (auto& q : queries) {
int x = q[0], y = q[1];
cnt[y]++;
if (g.contains(x) && --cnt[g[x]] == 0) {
cnt.erase(g[x]);
}
g[x] = y;
ans.push_back(cnt.size());
}
return ans;
}
};
|
3,160 |
Find the Number of Distinct Colors Among the Balls
|
Medium
|
<p>You are given an integer <code>limit</code> and a 2D array <code>queries</code> of size <code>n x 2</code>.</p>
<p>There are <code>limit + 1</code> balls with <strong>distinct</strong> labels in the range <code>[0, limit]</code>. Initially, all balls are uncolored. For every query in <code>queries</code> that is of the form <code>[x, y]</code>, you mark ball <code>x</code> with the color <code>y</code>. After each query, you need to find the number of colors among the balls.</p>
<p>Return an array <code>result</code> of length <code>n</code>, where <code>result[i]</code> denotes the number of colors <em>after</em> <code>i<sup>th</sup></code> query.</p>
<p><strong>Note</strong> that when answering a query, lack of a color <em>will not</em> be considered as a color.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop.gif" style="width: 455px; height: 145px;" /></p>
<ul>
<li>After query 0, ball 1 has color 4.</li>
<li>After query 1, ball 1 has color 4, and ball 2 has color 5.</li>
<li>After query 2, ball 1 has color 3, and ball 2 has color 5.</li>
<li>After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop2.gif" style="width: 457px; height: 144px;" /></strong></p>
<ul>
<li>After query 0, ball 0 has color 1.</li>
<li>After query 1, ball 0 has color 1, and ball 1 has color 2.</li>
<li>After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.</li>
<li>After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.</li>
<li>After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= limit <= 10<sup>9</sup></code></li>
<li><code>1 <= n == queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= limit</code></li>
<li><code>1 <= queries[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Simulation
|
Go
|
func queryResults(limit int, queries [][]int) (ans []int) {
g := map[int]int{}
cnt := map[int]int{}
for _, q := range queries {
x, y := q[0], q[1]
cnt[y]++
if v, ok := g[x]; ok {
cnt[v]--
if cnt[v] == 0 {
delete(cnt, v)
}
}
g[x] = y
ans = append(ans, len(cnt))
}
return
}
|
3,160 |
Find the Number of Distinct Colors Among the Balls
|
Medium
|
<p>You are given an integer <code>limit</code> and a 2D array <code>queries</code> of size <code>n x 2</code>.</p>
<p>There are <code>limit + 1</code> balls with <strong>distinct</strong> labels in the range <code>[0, limit]</code>. Initially, all balls are uncolored. For every query in <code>queries</code> that is of the form <code>[x, y]</code>, you mark ball <code>x</code> with the color <code>y</code>. After each query, you need to find the number of colors among the balls.</p>
<p>Return an array <code>result</code> of length <code>n</code>, where <code>result[i]</code> denotes the number of colors <em>after</em> <code>i<sup>th</sup></code> query.</p>
<p><strong>Note</strong> that when answering a query, lack of a color <em>will not</em> be considered as a color.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop.gif" style="width: 455px; height: 145px;" /></p>
<ul>
<li>After query 0, ball 1 has color 4.</li>
<li>After query 1, ball 1 has color 4, and ball 2 has color 5.</li>
<li>After query 2, ball 1 has color 3, and ball 2 has color 5.</li>
<li>After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop2.gif" style="width: 457px; height: 144px;" /></strong></p>
<ul>
<li>After query 0, ball 0 has color 1.</li>
<li>After query 1, ball 0 has color 1, and ball 1 has color 2.</li>
<li>After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.</li>
<li>After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.</li>
<li>After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= limit <= 10<sup>9</sup></code></li>
<li><code>1 <= n == queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= limit</code></li>
<li><code>1 <= queries[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Simulation
|
Java
|
class Solution {
public int[] queryResults(int limit, int[][] queries) {
Map<Integer, Integer> g = new HashMap<>();
Map<Integer, Integer> cnt = new HashMap<>();
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int x = queries[i][0], y = queries[i][1];
cnt.merge(y, 1, Integer::sum);
if (g.containsKey(x) && cnt.merge(g.get(x), -1, Integer::sum) == 0) {
cnt.remove(g.get(x));
}
g.put(x, y);
ans[i] = cnt.size();
}
return ans;
}
}
|
3,160 |
Find the Number of Distinct Colors Among the Balls
|
Medium
|
<p>You are given an integer <code>limit</code> and a 2D array <code>queries</code> of size <code>n x 2</code>.</p>
<p>There are <code>limit + 1</code> balls with <strong>distinct</strong> labels in the range <code>[0, limit]</code>. Initially, all balls are uncolored. For every query in <code>queries</code> that is of the form <code>[x, y]</code>, you mark ball <code>x</code> with the color <code>y</code>. After each query, you need to find the number of colors among the balls.</p>
<p>Return an array <code>result</code> of length <code>n</code>, where <code>result[i]</code> denotes the number of colors <em>after</em> <code>i<sup>th</sup></code> query.</p>
<p><strong>Note</strong> that when answering a query, lack of a color <em>will not</em> be considered as a color.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop.gif" style="width: 455px; height: 145px;" /></p>
<ul>
<li>After query 0, ball 1 has color 4.</li>
<li>After query 1, ball 1 has color 4, and ball 2 has color 5.</li>
<li>After query 2, ball 1 has color 3, and ball 2 has color 5.</li>
<li>After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop2.gif" style="width: 457px; height: 144px;" /></strong></p>
<ul>
<li>After query 0, ball 0 has color 1.</li>
<li>After query 1, ball 0 has color 1, and ball 1 has color 2.</li>
<li>After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.</li>
<li>After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.</li>
<li>After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= limit <= 10<sup>9</sup></code></li>
<li><code>1 <= n == queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= limit</code></li>
<li><code>1 <= queries[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Simulation
|
Python
|
class Solution:
def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
g = {}
cnt = Counter()
ans = []
for x, y in queries:
cnt[y] += 1
if x in g:
cnt[g[x]] -= 1
if cnt[g[x]] == 0:
cnt.pop(g[x])
g[x] = y
ans.append(len(cnt))
return ans
|
3,160 |
Find the Number of Distinct Colors Among the Balls
|
Medium
|
<p>You are given an integer <code>limit</code> and a 2D array <code>queries</code> of size <code>n x 2</code>.</p>
<p>There are <code>limit + 1</code> balls with <strong>distinct</strong> labels in the range <code>[0, limit]</code>. Initially, all balls are uncolored. For every query in <code>queries</code> that is of the form <code>[x, y]</code>, you mark ball <code>x</code> with the color <code>y</code>. After each query, you need to find the number of colors among the balls.</p>
<p>Return an array <code>result</code> of length <code>n</code>, where <code>result[i]</code> denotes the number of colors <em>after</em> <code>i<sup>th</sup></code> query.</p>
<p><strong>Note</strong> that when answering a query, lack of a color <em>will not</em> be considered as a color.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop.gif" style="width: 455px; height: 145px;" /></p>
<ul>
<li>After query 0, ball 1 has color 4.</li>
<li>After query 1, ball 1 has color 4, and ball 2 has color 5.</li>
<li>After query 2, ball 1 has color 3, and ball 2 has color 5.</li>
<li>After query 3, ball 1 has color 3, ball 2 has color 5, and ball 3 has color 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3160.Find%20the%20Number%20of%20Distinct%20Colors%20Among%20the%20Balls/images/ezgifcom-crop2.gif" style="width: 457px; height: 144px;" /></strong></p>
<ul>
<li>After query 0, ball 0 has color 1.</li>
<li>After query 1, ball 0 has color 1, and ball 1 has color 2.</li>
<li>After query 2, ball 0 has color 1, and balls 1 and 2 have color 2.</li>
<li>After query 3, ball 0 has color 1, balls 1 and 2 have color 2, and ball 3 has color 4.</li>
<li>After query 4, ball 0 has color 1, balls 1 and 2 have color 2, ball 3 has color 4, and ball 4 has color 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= limit <= 10<sup>9</sup></code></li>
<li><code>1 <= n == queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= limit</code></li>
<li><code>1 <= queries[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Simulation
|
TypeScript
|
function queryResults(limit: number, queries: number[][]): number[] {
const g = new Map<number, number>();
const cnt = new Map<number, number>();
const ans: number[] = [];
for (const [x, y] of queries) {
cnt.set(y, (cnt.get(y) ?? 0) + 1);
if (g.has(x)) {
const v = g.get(x)!;
cnt.set(v, cnt.get(v)! - 1);
if (cnt.get(v) === 0) {
cnt.delete(v);
}
}
g.set(x, y);
ans.push(cnt.size);
}
return ans;
}
|
3,162 |
Find the Number of Good Pairs I
|
Easy
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 50</code></li>
<li><code>1 <= nums1[i], nums2[j] <= 50</code></li>
<li><code>1 <= k <= 50</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int ans = 0;
for (int x : nums1) {
for (int y : nums2) {
if (x % (y * k) == 0) {
++ans;
}
}
}
return ans;
}
};
|
3,162 |
Find the Number of Good Pairs I
|
Easy
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 50</code></li>
<li><code>1 <= nums1[i], nums2[j] <= 50</code></li>
<li><code>1 <= k <= 50</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func numberOfPairs(nums1 []int, nums2 []int, k int) (ans int) {
for _, x := range nums1 {
for _, y := range nums2 {
if x%(y*k) == 0 {
ans++
}
}
}
return
}
|
3,162 |
Find the Number of Good Pairs I
|
Easy
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 50</code></li>
<li><code>1 <= nums1[i], nums2[j] <= 50</code></li>
<li><code>1 <= k <= 50</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int ans = 0;
for (int x : nums1) {
for (int y : nums2) {
if (x % (y * k) == 0) {
++ans;
}
}
}
return ans;
}
}
|
3,162 |
Find the Number of Good Pairs I
|
Easy
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 50</code></li>
<li><code>1 <= nums1[i], nums2[j] <= 50</code></li>
<li><code>1 <= k <= 50</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
return sum(x % (y * k) == 0 for x in nums1 for y in nums2)
|
3,162 |
Find the Number of Good Pairs I
|
Easy
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 50</code></li>
<li><code>1 <= nums1[i], nums2[j] <= 50</code></li>
<li><code>1 <= k <= 50</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function numberOfPairs(nums1: number[], nums2: number[], k: number): number {
let ans = 0;
for (const x of nums1) {
for (const y of nums2) {
if (x % (y * k) === 0) {
++ans;
}
}
}
return ans;
}
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
string compressedString(string word) {
string ans;
int n = word.length();
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && word[j] == word[i]) {
++j;
}
int k = j - i;
while (k > 0) {
int x = min(9, k);
ans.push_back('0' + x);
ans.push_back(word[i]);
k -= x;
}
i = j;
}
return ans;
}
};
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Go
|
func compressedString(word string) string {
ans := []byte{}
n := len(word)
for i := 0; i < n; {
j := i + 1
for j < n && word[j] == word[i] {
j++
}
k := j - i
for k > 0 {
x := min(9, k)
ans = append(ans, byte('0'+x))
ans = append(ans, word[i])
k -= x
}
i = j
}
return string(ans)
}
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Java
|
class Solution {
public String compressedString(String word) {
StringBuilder ans = new StringBuilder();
int n = word.length();
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && word.charAt(j) == word.charAt(i)) {
++j;
}
int k = j - i;
while (k > 0) {
int x = Math.min(9, k);
ans.append(x).append(word.charAt(i));
k -= x;
}
i = j;
}
return ans.toString();
}
}
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
JavaScript
|
/**
* @param {string} word
* @return {string}
*/
var compressedString = function (word) {
const ans = [];
const n = word.length;
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && word[j] === word[i]) {
++j;
}
let k = j - i;
while (k) {
const x = Math.min(k, 9);
ans.push(x + word[i]);
k -= x;
}
i = j;
}
return ans.join('');
};
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Python
|
class Solution:
def compressedString(self, word: str) -> str:
g = groupby(word)
ans = []
for c, v in g:
k = len(list(v))
while k:
x = min(9, k)
ans.append(str(x) + c)
k -= x
return "".join(ans)
|
3,163 |
String Compression III
|
Medium
|
<p>Given a string <code>word</code>, compress it using the following algorithm:</p>
<ul>
<li>Begin with an empty string <code>comp</code>. While <code>word</code> is <strong>not</strong> empty, use the following operation:
<ul>
<li>Remove a maximum length prefix of <code>word</code> made of a <em>single character</em> <code>c</code> repeating <strong>at most</strong> 9 times.</li>
<li>Append the length of the prefix followed by <code>c</code> to <code>comp</code>.</li>
</ul>
</li>
</ul>
<p>Return the string <code>comp</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "abcde"</span></p>
<p><strong>Output:</strong> <span class="example-io">"1a1b1c1d1e"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 5 times, choosing <code>"a"</code>, <code>"b"</code>, <code>"c"</code>, <code>"d"</code>, and <code>"e"</code> as the prefix in each operation.</p>
<p>For each prefix, append <code>"1"</code> followed by the character to <code>comp</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aaaaaaaaaaaaaabb"</span></p>
<p><strong>Output:</strong> <span class="example-io">"9a5a2b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>comp = ""</code>. Apply the operation 3 times, choosing <code>"aaaaaaaaa"</code>, <code>"aaaaa"</code>, and <code>"bb"</code> as the prefix in each operation.</p>
<ul>
<li>For prefix <code>"aaaaaaaaa"</code>, append <code>"9"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"aaaaa"</code>, append <code>"5"</code> followed by <code>"a"</code> to <code>comp</code>.</li>
<li>For prefix <code>"bb"</code>, append <code>"2"</code> followed by <code>"b"</code> to <code>comp</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
TypeScript
|
function compressedString(word: string): string {
const ans: string[] = [];
const n = word.length;
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && word[j] === word[i]) {
++j;
}
let k = j - i;
while (k) {
const x = Math.min(k, 9);
ans.push(x + word[i]);
k -= x;
}
i = j;
}
return ans.join('');
}
|
3,164 |
Find the Number of Good Pairs II
|
Medium
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>3</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
long long numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
unordered_map<int, int> cnt1;
for (int x : nums1) {
if (x % k == 0) {
cnt1[x / k]++;
}
}
if (cnt1.empty()) {
return 0;
}
unordered_map<int, int> cnt2;
for (int x : nums2) {
++cnt2[x];
}
int mx = 0;
for (auto& [x, _] : cnt1) {
mx = max(mx, x);
}
long long ans = 0;
for (auto& [x, v] : cnt2) {
long long s = 0;
for (int y = x; y <= mx; y += x) {
s += cnt1[y];
}
ans += s * v;
}
return ans;
}
};
|
3,164 |
Find the Number of Good Pairs II
|
Medium
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>3</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func numberOfPairs(nums1 []int, nums2 []int, k int) (ans int64) {
cnt1 := map[int]int{}
for _, x := range nums1 {
if x%k == 0 {
cnt1[x/k]++
}
}
if len(cnt1) == 0 {
return 0
}
cnt2 := map[int]int{}
for _, x := range nums2 {
cnt2[x]++
}
mx := 0
for x := range cnt1 {
mx = max(mx, x)
}
for x, v := range cnt2 {
s := 0
for y := x; y <= mx; y += x {
s += cnt1[y]
}
ans += int64(s) * int64(v)
}
return
}
|
3,164 |
Find the Number of Good Pairs II
|
Medium
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>3</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public long numberOfPairs(int[] nums1, int[] nums2, int k) {
Map<Integer, Integer> cnt1 = new HashMap<>();
for (int x : nums1) {
if (x % k == 0) {
cnt1.merge(x / k, 1, Integer::sum);
}
}
if (cnt1.isEmpty()) {
return 0;
}
Map<Integer, Integer> cnt2 = new HashMap<>();
for (int x : nums2) {
cnt2.merge(x, 1, Integer::sum);
}
long ans = 0;
int mx = Collections.max(cnt1.keySet());
for (var e : cnt2.entrySet()) {
int x = e.getKey(), v = e.getValue();
int s = 0;
for (int y = x; y <= mx; y += x) {
s += cnt1.getOrDefault(y, 0);
}
ans += 1L * s * v;
}
return ans;
}
}
|
3,164 |
Find the Number of Good Pairs II
|
Medium
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>3</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
cnt1 = Counter(x // k for x in nums1 if x % k == 0)
if not cnt1:
return 0
cnt2 = Counter(nums2)
ans = 0
mx = max(cnt1)
for x, v in cnt2.items():
s = sum(cnt1[y] for y in range(x, mx + 1, x))
ans += s * v
return ans
|
3,164 |
Find the Number of Good Pairs II
|
Medium
|
<p>You are given 2 integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>n</code> and <code>m</code> respectively. You are also given a <strong>positive</strong> integer <code>k</code>.</p>
<p>A pair <code>(i, j)</code> is called <strong>good</strong> if <code>nums1[i]</code> is divisible by <code>nums2[j] * k</code> (<code>0 <= i <= n - 1</code>, <code>0 <= j <= m - 1</code>).</p>
<p>Return the total number of <strong>good</strong> pairs.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,3,4], nums2 = [1,3,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
The 5 good pairs are <code>(0, 0)</code>, <code>(1, 0)</code>, <code>(1, 1)</code>, <code>(2, 0)</code>, and <code>(2, 2)</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,2,4,12], nums2 = [2,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 good pairs are <code>(3, 0)</code> and <code>(3, 1)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>3</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function numberOfPairs(nums1: number[], nums2: number[], k: number): number {
const cnt1: Map<number, number> = new Map();
for (const x of nums1) {
if (x % k === 0) {
cnt1.set((x / k) | 0, (cnt1.get((x / k) | 0) || 0) + 1);
}
}
if (cnt1.size === 0) {
return 0;
}
const cnt2: Map<number, number> = new Map();
for (const x of nums2) {
cnt2.set(x, (cnt2.get(x) || 0) + 1);
}
const mx = Math.max(...cnt1.keys());
let ans = 0;
for (const [x, v] of cnt2) {
let s = 0;
for (let y = x; y <= mx; y += x) {
s += cnt1.get(y) || 0;
}
ans += s * v;
}
return ans;
}
|
3,165 |
Maximum Sum of Subsequence With Non-adjacent Elements
|
Hard
|
<p>You are given an array <code>nums</code> consisting of integers. You are also given a 2D array <code>queries</code>, where <code>queries[i] = [pos<sub>i</sub>, x<sub>i</sub>]</code>.</p>
<p>For query <code>i</code>, we first set <code>nums[pos<sub>i</sub>]</code> equal to <code>x<sub>i</sub></code>, then we calculate the answer to query <code>i</code> which is the <strong>maximum</strong> sum of a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> where <strong>no two adjacent elements are selected</strong>.</p>
<p>Return the <em>sum</em> of the answers to all queries.</p>
<p>Since the final answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,5,9], queries = [[1,-2],[0,-3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is <code>3 + 9 = 12</code>.<br />
After the 2<sup>nd</sup> query, <code>nums = [-3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is 9.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,-1], queries = [[0,-5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [-5,-1]</code> and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] == [pos<sub>i</sub>, x<sub>i</sub>]</code></li>
<li><code>0 <= pos<sub>i</sub> <= nums.length - 1</code></li>
<li><code>-10<sup>5</sup> <= x<sub>i</sub> <= 10<sup>5</sup></code></li>
</ul>
|
Segment Tree; Array; Divide and Conquer; Dynamic Programming
|
C++
|
class Node {
public:
int l, r;
long long s00, s01, s10, s11;
Node(int l, int r)
: l(l)
, r(r)
, s00(0)
, s01(0)
, s10(0)
, s11(0) {}
};
class SegmentTree {
public:
vector<Node*> tr;
SegmentTree(int n)
: tr(n << 2) {
build(1, 1, n);
}
void build(int u, int l, int r) {
tr[u] = new Node(l, r);
if (l == r) {
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
long long query(int u, int l, int r) {
if (tr[u]->l >= l && tr[u]->r <= r) {
return tr[u]->s11;
}
int mid = (tr[u]->l + tr[u]->r) >> 1;
long long ans = 0;
if (r <= mid) {
ans = query(u << 1, l, r);
}
if (l > mid) {
ans = max(ans, query(u << 1 | 1, l, r));
}
return ans;
}
void pushup(int u) {
Node* left = tr[u << 1];
Node* right = tr[u << 1 | 1];
tr[u]->s00 = max(left->s00 + right->s10, left->s01 + right->s00);
tr[u]->s01 = max(left->s00 + right->s11, left->s01 + right->s01);
tr[u]->s10 = max(left->s10 + right->s10, left->s11 + right->s00);
tr[u]->s11 = max(left->s10 + right->s11, left->s11 + right->s01);
}
void modify(int u, int x, int v) {
if (tr[u]->l == tr[u]->r) {
tr[u]->s11 = max(0LL, (long long) v);
return;
}
int mid = (tr[u]->l + tr[u]->r) >> 1;
if (x <= mid) {
modify(u << 1, x, v);
} else {
modify(u << 1 | 1, x, v);
}
pushup(u);
}
~SegmentTree() {
for (auto node : tr) {
delete node;
}
}
};
class Solution {
public:
int maximumSumSubsequence(vector<int>& nums, vector<vector<int>>& queries) {
int n = nums.size();
SegmentTree tree(n);
for (int i = 0; i < n; ++i) {
tree.modify(1, i + 1, nums[i]);
}
long long ans = 0;
const int mod = 1e9 + 7;
for (const auto& q : queries) {
tree.modify(1, q[0] + 1, q[1]);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return (int) ans;
}
};
|
3,165 |
Maximum Sum of Subsequence With Non-adjacent Elements
|
Hard
|
<p>You are given an array <code>nums</code> consisting of integers. You are also given a 2D array <code>queries</code>, where <code>queries[i] = [pos<sub>i</sub>, x<sub>i</sub>]</code>.</p>
<p>For query <code>i</code>, we first set <code>nums[pos<sub>i</sub>]</code> equal to <code>x<sub>i</sub></code>, then we calculate the answer to query <code>i</code> which is the <strong>maximum</strong> sum of a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> where <strong>no two adjacent elements are selected</strong>.</p>
<p>Return the <em>sum</em> of the answers to all queries.</p>
<p>Since the final answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,5,9], queries = [[1,-2],[0,-3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is <code>3 + 9 = 12</code>.<br />
After the 2<sup>nd</sup> query, <code>nums = [-3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is 9.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,-1], queries = [[0,-5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [-5,-1]</code> and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] == [pos<sub>i</sub>, x<sub>i</sub>]</code></li>
<li><code>0 <= pos<sub>i</sub> <= nums.length - 1</code></li>
<li><code>-10<sup>5</sup> <= x<sub>i</sub> <= 10<sup>5</sup></code></li>
</ul>
|
Segment Tree; Array; Divide and Conquer; Dynamic Programming
|
Go
|
type Node struct {
l, r int
s00, s01, s10, s11 int
}
func NewNode(l, r int) *Node {
return &Node{l: l, r: r, s00: 0, s01: 0, s10: 0, s11: 0}
}
type SegmentTree struct {
tr []*Node
}
func NewSegmentTree(n int) *SegmentTree {
tr := make([]*Node, n*4)
tree := &SegmentTree{tr: tr}
tree.build(1, 1, n)
return tree
}
func (st *SegmentTree) build(u, l, r int) {
st.tr[u] = NewNode(l, r)
if l == r {
return
}
mid := (l + r) >> 1
st.build(u<<1, l, mid)
st.build(u<<1|1, mid+1, r)
}
func (st *SegmentTree) query(u, l, r int) int {
if st.tr[u].l >= l && st.tr[u].r <= r {
return st.tr[u].s11
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
ans := 0
if r <= mid {
ans = st.query(u<<1, l, r)
}
if l > mid {
ans = max(ans, st.query(u<<1|1, l, r))
}
return ans
}
func (st *SegmentTree) pushup(u int) {
left := st.tr[u<<1]
right := st.tr[u<<1|1]
st.tr[u].s00 = max(left.s00+right.s10, left.s01+right.s00)
st.tr[u].s01 = max(left.s00+right.s11, left.s01+right.s01)
st.tr[u].s10 = max(left.s10+right.s10, left.s11+right.s00)
st.tr[u].s11 = max(left.s10+right.s11, left.s11+right.s01)
}
func (st *SegmentTree) modify(u, x, v int) {
if st.tr[u].l == st.tr[u].r {
st.tr[u].s11 = max(0, v)
return
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
if x <= mid {
st.modify(u<<1, x, v)
} else {
st.modify(u<<1|1, x, v)
}
st.pushup(u)
}
func maximumSumSubsequence(nums []int, queries [][]int) (ans int) {
n := len(nums)
tree := NewSegmentTree(n)
for i, x := range nums {
tree.modify(1, i+1, x)
}
const mod int = 1e9 + 7
for _, q := range queries {
tree.modify(1, q[0]+1, q[1])
ans = (ans + tree.query(1, 1, n)) % mod
}
return
}
|
3,165 |
Maximum Sum of Subsequence With Non-adjacent Elements
|
Hard
|
<p>You are given an array <code>nums</code> consisting of integers. You are also given a 2D array <code>queries</code>, where <code>queries[i] = [pos<sub>i</sub>, x<sub>i</sub>]</code>.</p>
<p>For query <code>i</code>, we first set <code>nums[pos<sub>i</sub>]</code> equal to <code>x<sub>i</sub></code>, then we calculate the answer to query <code>i</code> which is the <strong>maximum</strong> sum of a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> where <strong>no two adjacent elements are selected</strong>.</p>
<p>Return the <em>sum</em> of the answers to all queries.</p>
<p>Since the final answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,5,9], queries = [[1,-2],[0,-3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is <code>3 + 9 = 12</code>.<br />
After the 2<sup>nd</sup> query, <code>nums = [-3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is 9.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,-1], queries = [[0,-5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [-5,-1]</code> and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] == [pos<sub>i</sub>, x<sub>i</sub>]</code></li>
<li><code>0 <= pos<sub>i</sub> <= nums.length - 1</code></li>
<li><code>-10<sup>5</sup> <= x<sub>i</sub> <= 10<sup>5</sup></code></li>
</ul>
|
Segment Tree; Array; Divide and Conquer; Dynamic Programming
|
Java
|
class Node {
int l, r;
long s00, s01, s10, s11;
Node(int l, int r) {
this.l = l;
this.r = r;
this.s00 = this.s01 = this.s10 = this.s11 = 0;
}
}
class SegmentTree {
Node[] tr;
SegmentTree(int n) {
tr = new Node[n * 4];
build(1, 1, n);
}
void build(int u, int l, int r) {
tr[u] = new Node(l, r);
if (l == r) {
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
long query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
return tr[u].s11;
}
int mid = (tr[u].l + tr[u].r) >> 1;
long ans = 0;
if (r <= mid) {
ans = query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, query(u << 1 | 1, l, r));
}
return ans;
}
void pushup(int u) {
Node left = tr[u << 1];
Node right = tr[u << 1 | 1];
tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
void modify(int u, int x, int v) {
if (tr[u].l == tr[u].r) {
tr[u].s11 = Math.max(0, v);
return;
}
int mid = (tr[u].l + tr[u].r) >> 1;
if (x <= mid) {
modify(u << 1, x, v);
} else {
modify(u << 1 | 1, x, v);
}
pushup(u);
}
}
class Solution {
public int maximumSumSubsequence(int[] nums, int[][] queries) {
int n = nums.length;
SegmentTree tree = new SegmentTree(n);
for (int i = 0; i < n; ++i) {
tree.modify(1, i + 1, nums[i]);
}
long ans = 0;
final int mod = (int) 1e9 + 7;
for (int[] q : queries) {
tree.modify(1, q[0] + 1, q[1]);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return (int) ans;
}
}
|
3,165 |
Maximum Sum of Subsequence With Non-adjacent Elements
|
Hard
|
<p>You are given an array <code>nums</code> consisting of integers. You are also given a 2D array <code>queries</code>, where <code>queries[i] = [pos<sub>i</sub>, x<sub>i</sub>]</code>.</p>
<p>For query <code>i</code>, we first set <code>nums[pos<sub>i</sub>]</code> equal to <code>x<sub>i</sub></code>, then we calculate the answer to query <code>i</code> which is the <strong>maximum</strong> sum of a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> where <strong>no two adjacent elements are selected</strong>.</p>
<p>Return the <em>sum</em> of the answers to all queries.</p>
<p>Since the final answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,5,9], queries = [[1,-2],[0,-3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is <code>3 + 9 = 12</code>.<br />
After the 2<sup>nd</sup> query, <code>nums = [-3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is 9.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,-1], queries = [[0,-5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [-5,-1]</code> and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] == [pos<sub>i</sub>, x<sub>i</sub>]</code></li>
<li><code>0 <= pos<sub>i</sub> <= nums.length - 1</code></li>
<li><code>-10<sup>5</sup> <= x<sub>i</sub> <= 10<sup>5</sup></code></li>
</ul>
|
Segment Tree; Array; Divide and Conquer; Dynamic Programming
|
Python
|
def max(a: int, b: int) -> int:
return a if a > b else b
class Node:
__slots__ = "l", "r", "s00", "s01", "s10", "s11"
def __init__(self, l: int, r: int):
self.l = l
self.r = r
self.s00 = self.s01 = self.s10 = self.s11 = 0
class SegmentTree:
__slots__ = "tr"
def __init__(self, n: int):
self.tr: List[Node | None] = [None] * (n << 2)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
mid = (l + r) >> 1
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
def query(self, u: int, l: int, r: int) -> int:
if self.tr[u].l >= l and self.tr[u].r <= r:
return self.tr[u].s11
mid = (self.tr[u].l + self.tr[u].r) >> 1
ans = 0
if r <= mid:
ans = self.query(u << 1, l, r)
if l > mid:
ans = max(ans, self.query(u << 1 | 1, l, r))
return ans
def pushup(self, u: int):
left, right = self.tr[u << 1], self.tr[u << 1 | 1]
self.tr[u].s00 = max(left.s00 + right.s10, left.s01 + right.s00)
self.tr[u].s01 = max(left.s00 + right.s11, left.s01 + right.s01)
self.tr[u].s10 = max(left.s10 + right.s10, left.s11 + right.s00)
self.tr[u].s11 = max(left.s10 + right.s11, left.s11 + right.s01)
def modify(self, u: int, x: int, v: int):
if self.tr[u].l == self.tr[u].r:
self.tr[u].s11 = max(0, v)
return
mid = (self.tr[u].l + self.tr[u].r) >> 1
if x <= mid:
self.modify(u << 1, x, v)
else:
self.modify(u << 1 | 1, x, v)
self.pushup(u)
class Solution:
def maximumSumSubsequence(self, nums: List[int], queries: List[List[int]]) -> int:
n = len(nums)
tree = SegmentTree(n)
for i, x in enumerate(nums, 1):
tree.modify(1, i, x)
ans = 0
mod = 10**9 + 7
for i, x in queries:
tree.modify(1, i + 1, x)
ans = (ans + tree.query(1, 1, n)) % mod
return ans
|
3,165 |
Maximum Sum of Subsequence With Non-adjacent Elements
|
Hard
|
<p>You are given an array <code>nums</code> consisting of integers. You are also given a 2D array <code>queries</code>, where <code>queries[i] = [pos<sub>i</sub>, x<sub>i</sub>]</code>.</p>
<p>For query <code>i</code>, we first set <code>nums[pos<sub>i</sub>]</code> equal to <code>x<sub>i</sub></code>, then we calculate the answer to query <code>i</code> which is the <strong>maximum</strong> sum of a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> where <strong>no two adjacent elements are selected</strong>.</p>
<p>Return the <em>sum</em> of the answers to all queries.</p>
<p>Since the final answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,5,9], queries = [[1,-2],[0,-3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is <code>3 + 9 = 12</code>.<br />
After the 2<sup>nd</sup> query, <code>nums = [-3,-2,9]</code> and the maximum sum of a subsequence with non-adjacent elements is 9.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,-1], queries = [[0,-5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
After the 1<sup>st</sup> query, <code>nums = [-5,-1]</code> and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] == [pos<sub>i</sub>, x<sub>i</sub>]</code></li>
<li><code>0 <= pos<sub>i</sub> <= nums.length - 1</code></li>
<li><code>-10<sup>5</sup> <= x<sub>i</sub> <= 10<sup>5</sup></code></li>
</ul>
|
Segment Tree; Array; Divide and Conquer; Dynamic Programming
|
TypeScript
|
class Node {
s00 = 0;
s01 = 0;
s10 = 0;
s11 = 0;
constructor(
public l: number,
public r: number,
) {}
}
class SegmentTree {
tr: Node[];
constructor(n: number) {
this.tr = Array(n * 4);
this.build(1, 1, n);
}
build(u: number, l: number, r: number) {
this.tr[u] = new Node(l, r);
if (l === r) {
return;
}
const mid = (l + r) >> 1;
this.build(u << 1, l, mid);
this.build((u << 1) | 1, mid + 1, r);
}
query(u: number, l: number, r: number): number {
if (this.tr[u].l >= l && this.tr[u].r <= r) {
return this.tr[u].s11;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
let ans = 0;
if (r <= mid) {
ans = this.query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, this.query((u << 1) | 1, l, r));
}
return ans;
}
pushup(u: number) {
const left = this.tr[u << 1];
const right = this.tr[(u << 1) | 1];
this.tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
this.tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
this.tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
this.tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
modify(u: number, x: number, v: number) {
if (this.tr[u].l === this.tr[u].r) {
this.tr[u].s11 = Math.max(0, v);
return;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
if (x <= mid) {
this.modify(u << 1, x, v);
} else {
this.modify((u << 1) | 1, x, v);
}
this.pushup(u);
}
}
function maximumSumSubsequence(nums: number[], queries: number[][]): number {
const n = nums.length;
const tree = new SegmentTree(n);
for (let i = 0; i < n; i++) {
tree.modify(1, i + 1, nums[i]);
}
let ans = 0;
const mod = 1e9 + 7;
for (const [i, x] of queries) {
tree.modify(1, i + 1, x);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return ans;
}
|
3,166 |
Calculate Parking Fees and Duration
|
Medium
|
<p>Table: <code>ParkingTransactions</code></p>
<pre>
+--------------+-----------+
| Column Name | Type |
+--------------+-----------+
| lot_id | int |
| car_id | int |
| entry_time | datetime |
| exit_time | datetime |
| fee_paid | decimal |
+--------------+-----------+
(lot_id, car_id, entry_time) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the ID of the parking lot, the ID of the car, the entry and exit times, and the fee paid for the parking duration.
</pre>
<p>Write a solution to find the <strong>total parking fee</strong> paid by each car <strong>across all parking lots</strong>, and the <strong>average hourly fee</strong> (rounded to <code>2</code> decimal places) paid by <strong>each</strong> car. Also, find the <strong>parking lot</strong> where each car spent the <strong>most total time</strong>.</p>
<p>Return <em>the result table ordered by </em><code>car_id</code><em><b> </b>in<b> ascending </b></em><em> order.</em></p>
<p><strong>Note:</strong> Test cases are generated in such a way that an individual car cannot be in multiple parking lots at the same time.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>ParkingTransactions table:</p>
<pre class="example-io">
+--------+--------+---------------------+---------------------+----------+
| lot_id | car_id | entry_time | exit_time | fee_paid |
+--------+--------+---------------------+---------------------+----------+
| 1 | 1001 | 2023-06-01 08:00:00 | 2023-06-01 10:30:00 | 5.00 |
| 1 | 1001 | 2023-06-02 11:00:00 | 2023-06-02 12:45:00 | 3.00 |
| 2 | 1001 | 2023-06-01 10:45:00 | 2023-06-01 12:00:00 | 6.00 |
| 2 | 1002 | 2023-06-01 09:00:00 | 2023-06-01 11:30:00 | 4.00 |
| 3 | 1001 | 2023-06-03 07:00:00 | 2023-06-03 09:00:00 | 4.00 |
| 3 | 1002 | 2023-06-02 12:00:00 | 2023-06-02 14:00:00 | 2.00 |
+--------+--------+---------------------+---------------------+----------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+--------+----------------+----------------+---------------+
| car_id | total_fee_paid | avg_hourly_fee | most_time_lot |
+--------+----------------+----------------+---------------+
| 1001 | 18.00 | 2.40 | 1 |
| 1002 | 6.00 | 1.33 | 2 |
+--------+----------------+----------------+---------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For car ID 1001:
<ul>
<li>From 2023-06-01 08:00:00 to 2023-06-01 10:30:00 in lot 1: 2.5 hours, fee 5.00</li>
<li>From 2023-06-02 11:00:00 to 2023-06-02 12:45:00 in lot 1: 1.75 hours, fee 3.00</li>
<li>From 2023-06-01 10:45:00 to 2023-06-01 12:00:00 in lot 2: 1.25 hours, fee 6.00</li>
<li>From 2023-06-03 07:00:00 to 2023-06-03 09:00:00 in lot 3: 2 hours, fee 4.00</li>
</ul>
Total fee paid: 18.00, total hours: 7.5, average hourly fee: 2.40, most time spent in lot 1: 4.25 hours.</li>
<li>For car ID 1002:
<ul>
<li>From 2023-06-01 09:00:00 to 2023-06-01 11:30:00 in lot 2: 2.5 hours, fee 4.00</li>
<li>From 2023-06-02 12:00:00 to 2023-06-02 14:00:00 in lot 3: 2 hours, fee 2.00</li>
</ul>
Total fee paid: 6.00, total hours: 4.5, average hourly fee: 1.33, most time spent in lot 2: 2.5 hours.</li>
</ul>
<p><b>Note:</b> Output table is ordered by car_id in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
car_id,
lot_id,
SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) AS duration
FROM ParkingTransactions
GROUP BY 1, 2
),
P AS (
SELECT
*,
RANK() OVER (
PARTITION BY car_id
ORDER BY duration DESC
) AS rk
FROM T
)
SELECT
t1.car_id,
SUM(fee_paid) AS total_fee_paid,
ROUND(
SUM(fee_paid) / (SUM(TIMESTAMPDIFF(SECOND, entry_time, exit_time)) / 3600),
2
) AS avg_hourly_fee,
t2.lot_id AS most_time_lot
FROM
ParkingTransactions AS t1
LEFT JOIN P AS t2 ON t1.car_id = t2.car_id AND t2.rk = 1
GROUP BY 1
ORDER BY 1;
|
3,167 |
Better Compression of String
|
Medium
|
<p>You are given a string <code>compressed</code> representing a compressed version of a string. The format is a character followed by its frequency. For example, <code>"a3b1a1c2"</code> is a compressed version of the string <code>"aaabacc"</code>.</p>
<p>We seek a <strong>better compression</strong> with the following conditions:</p>
<ol>
<li>Each character should appear <strong>only once</strong> in the compressed version.</li>
<li>The characters should be in <strong>alphabetical order</strong>.</li>
</ol>
<p>Return the <em>better compression</em> of <code>compressed</code>.</p>
<p><strong>Note:</strong> In the better version of compression, the order of letters may change, which is acceptable.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a3c9b2c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a3b2c10"</span></p>
<p><strong>Explanation:</strong></p>
<p>Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.</p>
<p>Hence, in the resulting string, it should have a size of 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "c2b3a1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a1b3c2"</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a2b4c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a2b4c1"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= compressed.length <= 6 * 10<sup>4</sup></code></li>
<li><code>compressed</code> consists only of lowercase English letters and digits.</li>
<li><code>compressed</code> is a valid compression, i.e., each character is followed by its frequency.</li>
<li>Frequencies are in the range <code>[1, 10<sup>4</sup>]</code> and have no leading zeroes.</li>
</ul>
|
Hash Table; String; Counting; Sorting
|
C++
|
class Solution {
public:
string betterCompression(string compressed) {
map<char, int> cnt;
int i = 0;
int n = compressed.length();
while (i < n) {
char c = compressed[i];
int j = i + 1;
int x = 0;
while (j < n && isdigit(compressed[j])) {
x = x * 10 + (compressed[j] - '0');
j++;
}
cnt[c] += x;
i = j;
}
stringstream ans;
for (const auto& entry : cnt) {
ans << entry.first << entry.second;
}
return ans.str();
}
};
|
3,167 |
Better Compression of String
|
Medium
|
<p>You are given a string <code>compressed</code> representing a compressed version of a string. The format is a character followed by its frequency. For example, <code>"a3b1a1c2"</code> is a compressed version of the string <code>"aaabacc"</code>.</p>
<p>We seek a <strong>better compression</strong> with the following conditions:</p>
<ol>
<li>Each character should appear <strong>only once</strong> in the compressed version.</li>
<li>The characters should be in <strong>alphabetical order</strong>.</li>
</ol>
<p>Return the <em>better compression</em> of <code>compressed</code>.</p>
<p><strong>Note:</strong> In the better version of compression, the order of letters may change, which is acceptable.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a3c9b2c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a3b2c10"</span></p>
<p><strong>Explanation:</strong></p>
<p>Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.</p>
<p>Hence, in the resulting string, it should have a size of 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "c2b3a1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a1b3c2"</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a2b4c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a2b4c1"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= compressed.length <= 6 * 10<sup>4</sup></code></li>
<li><code>compressed</code> consists only of lowercase English letters and digits.</li>
<li><code>compressed</code> is a valid compression, i.e., each character is followed by its frequency.</li>
<li>Frequencies are in the range <code>[1, 10<sup>4</sup>]</code> and have no leading zeroes.</li>
</ul>
|
Hash Table; String; Counting; Sorting
|
Go
|
func betterCompression(compressed string) string {
cnt := map[byte]int{}
n := len(compressed)
for i := 0; i < n; {
c := compressed[i]
j := i + 1
x := 0
for j < n && compressed[j] >= '0' && compressed[j] <= '9' {
x = x*10 + int(compressed[j]-'0')
j++
}
cnt[c] += x
i = j
}
ans := strings.Builder{}
for c := byte('a'); c <= byte('z'); c++ {
if cnt[c] > 0 {
ans.WriteByte(c)
ans.WriteString(strconv.Itoa(cnt[c]))
}
}
return ans.String()
}
|
3,167 |
Better Compression of String
|
Medium
|
<p>You are given a string <code>compressed</code> representing a compressed version of a string. The format is a character followed by its frequency. For example, <code>"a3b1a1c2"</code> is a compressed version of the string <code>"aaabacc"</code>.</p>
<p>We seek a <strong>better compression</strong> with the following conditions:</p>
<ol>
<li>Each character should appear <strong>only once</strong> in the compressed version.</li>
<li>The characters should be in <strong>alphabetical order</strong>.</li>
</ol>
<p>Return the <em>better compression</em> of <code>compressed</code>.</p>
<p><strong>Note:</strong> In the better version of compression, the order of letters may change, which is acceptable.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a3c9b2c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a3b2c10"</span></p>
<p><strong>Explanation:</strong></p>
<p>Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.</p>
<p>Hence, in the resulting string, it should have a size of 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "c2b3a1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a1b3c2"</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a2b4c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a2b4c1"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= compressed.length <= 6 * 10<sup>4</sup></code></li>
<li><code>compressed</code> consists only of lowercase English letters and digits.</li>
<li><code>compressed</code> is a valid compression, i.e., each character is followed by its frequency.</li>
<li>Frequencies are in the range <code>[1, 10<sup>4</sup>]</code> and have no leading zeroes.</li>
</ul>
|
Hash Table; String; Counting; Sorting
|
Java
|
class Solution {
public String betterCompression(String compressed) {
Map<Character, Integer> cnt = new TreeMap<>();
int i = 0;
int n = compressed.length();
while (i < n) {
char c = compressed.charAt(i);
int j = i + 1;
int x = 0;
while (j < n && Character.isDigit(compressed.charAt(j))) {
x = x * 10 + (compressed.charAt(j) - '0');
j++;
}
cnt.merge(c, x, Integer::sum);
i = j;
}
StringBuilder ans = new StringBuilder();
for (var e : cnt.entrySet()) {
ans.append(e.getKey()).append(e.getValue());
}
return ans.toString();
}
}
|
3,167 |
Better Compression of String
|
Medium
|
<p>You are given a string <code>compressed</code> representing a compressed version of a string. The format is a character followed by its frequency. For example, <code>"a3b1a1c2"</code> is a compressed version of the string <code>"aaabacc"</code>.</p>
<p>We seek a <strong>better compression</strong> with the following conditions:</p>
<ol>
<li>Each character should appear <strong>only once</strong> in the compressed version.</li>
<li>The characters should be in <strong>alphabetical order</strong>.</li>
</ol>
<p>Return the <em>better compression</em> of <code>compressed</code>.</p>
<p><strong>Note:</strong> In the better version of compression, the order of letters may change, which is acceptable.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a3c9b2c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a3b2c10"</span></p>
<p><strong>Explanation:</strong></p>
<p>Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.</p>
<p>Hence, in the resulting string, it should have a size of 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "c2b3a1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a1b3c2"</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a2b4c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a2b4c1"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= compressed.length <= 6 * 10<sup>4</sup></code></li>
<li><code>compressed</code> consists only of lowercase English letters and digits.</li>
<li><code>compressed</code> is a valid compression, i.e., each character is followed by its frequency.</li>
<li>Frequencies are in the range <code>[1, 10<sup>4</sup>]</code> and have no leading zeroes.</li>
</ul>
|
Hash Table; String; Counting; Sorting
|
Python
|
class Solution:
def betterCompression(self, compressed: str) -> str:
cnt = Counter()
i, n = 0, len(compressed)
while i < n:
j = i + 1
x = 0
while j < n and compressed[j].isdigit():
x = x * 10 + int(compressed[j])
j += 1
cnt[compressed[i]] += x
i = j
return "".join(sorted(f"{k}{v}" for k, v in cnt.items()))
|
3,167 |
Better Compression of String
|
Medium
|
<p>You are given a string <code>compressed</code> representing a compressed version of a string. The format is a character followed by its frequency. For example, <code>"a3b1a1c2"</code> is a compressed version of the string <code>"aaabacc"</code>.</p>
<p>We seek a <strong>better compression</strong> with the following conditions:</p>
<ol>
<li>Each character should appear <strong>only once</strong> in the compressed version.</li>
<li>The characters should be in <strong>alphabetical order</strong>.</li>
</ol>
<p>Return the <em>better compression</em> of <code>compressed</code>.</p>
<p><strong>Note:</strong> In the better version of compression, the order of letters may change, which is acceptable.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a3c9b2c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a3b2c10"</span></p>
<p><strong>Explanation:</strong></p>
<p>Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.</p>
<p>Hence, in the resulting string, it should have a size of 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "c2b3a1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a1b3c2"</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">compressed = "a2b4c1"</span></p>
<p><strong>Output:</strong> <span class="example-io">"a2b4c1"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= compressed.length <= 6 * 10<sup>4</sup></code></li>
<li><code>compressed</code> consists only of lowercase English letters and digits.</li>
<li><code>compressed</code> is a valid compression, i.e., each character is followed by its frequency.</li>
<li>Frequencies are in the range <code>[1, 10<sup>4</sup>]</code> and have no leading zeroes.</li>
</ul>
|
Hash Table; String; Counting; Sorting
|
TypeScript
|
function betterCompression(compressed: string): string {
const cnt = new Map<string, number>();
const n = compressed.length;
let i = 0;
while (i < n) {
const c = compressed[i];
let j = i + 1;
let x = 0;
while (j < n && /\d/.test(compressed[j])) {
x = x * 10 + +compressed[j];
j++;
}
cnt.set(c, (cnt.get(c) || 0) + x);
i = j;
}
const keys = Array.from(cnt.keys()).sort();
const ans: string[] = [];
for (const k of keys) {
ans.push(`${k}${cnt.get(k)}`);
}
return ans.join('');
}
|
3,168 |
Minimum Number of Chairs in a Waiting Room
|
Easy
|
<p>You are given a string <code>s</code>. Simulate events at each second <code>i</code>:</p>
<ul>
<li>If <code>s[i] == 'E'</code>, a person enters the waiting room and takes one of the chairs in it.</li>
<li>If <code>s[i] == 'L'</code>, a person leaves the waiting room, freeing up a chair.</li>
</ul>
<p>Return the <strong>minimum </strong>number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially <strong>empty</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "EEEEEEE"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELELEEL"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Leave</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELEELEELLL"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>Enter</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>Leave</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>s</code> consists only of the letters <code>'E'</code> and <code>'L'</code>.</li>
<li><code>s</code> represents a valid sequence of entries and exits.</li>
</ul>
|
String; Simulation
|
C++
|
class Solution {
public:
int minimumChairs(string s) {
int cnt = 0, left = 0;
for (char& c : s) {
if (c == 'E') {
if (left > 0) {
--left;
} else {
++cnt;
}
} else {
++left;
}
}
return cnt;
}
};
|
3,168 |
Minimum Number of Chairs in a Waiting Room
|
Easy
|
<p>You are given a string <code>s</code>. Simulate events at each second <code>i</code>:</p>
<ul>
<li>If <code>s[i] == 'E'</code>, a person enters the waiting room and takes one of the chairs in it.</li>
<li>If <code>s[i] == 'L'</code>, a person leaves the waiting room, freeing up a chair.</li>
</ul>
<p>Return the <strong>minimum </strong>number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially <strong>empty</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "EEEEEEE"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELELEEL"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Leave</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELEELEELLL"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>Enter</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>Leave</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>s</code> consists only of the letters <code>'E'</code> and <code>'L'</code>.</li>
<li><code>s</code> represents a valid sequence of entries and exits.</li>
</ul>
|
String; Simulation
|
Go
|
func minimumChairs(s string) int {
cnt, left := 0, 0
for _, c := range s {
if c == 'E' {
if left > 0 {
left--
} else {
cnt++
}
} else {
left++
}
}
return cnt
}
|
3,168 |
Minimum Number of Chairs in a Waiting Room
|
Easy
|
<p>You are given a string <code>s</code>. Simulate events at each second <code>i</code>:</p>
<ul>
<li>If <code>s[i] == 'E'</code>, a person enters the waiting room and takes one of the chairs in it.</li>
<li>If <code>s[i] == 'L'</code>, a person leaves the waiting room, freeing up a chair.</li>
</ul>
<p>Return the <strong>minimum </strong>number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially <strong>empty</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "EEEEEEE"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELELEEL"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Leave</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELEELEELLL"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>Enter</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>Leave</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>s</code> consists only of the letters <code>'E'</code> and <code>'L'</code>.</li>
<li><code>s</code> represents a valid sequence of entries and exits.</li>
</ul>
|
String; Simulation
|
Java
|
class Solution {
public int minimumChairs(String s) {
int cnt = 0, left = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == 'E') {
if (left > 0) {
--left;
} else {
++cnt;
}
} else {
++left;
}
}
return cnt;
}
}
|
3,168 |
Minimum Number of Chairs in a Waiting Room
|
Easy
|
<p>You are given a string <code>s</code>. Simulate events at each second <code>i</code>:</p>
<ul>
<li>If <code>s[i] == 'E'</code>, a person enters the waiting room and takes one of the chairs in it.</li>
<li>If <code>s[i] == 'L'</code>, a person leaves the waiting room, freeing up a chair.</li>
</ul>
<p>Return the <strong>minimum </strong>number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially <strong>empty</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "EEEEEEE"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELELEEL"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Leave</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELEELEELLL"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>Enter</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>Leave</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>s</code> consists only of the letters <code>'E'</code> and <code>'L'</code>.</li>
<li><code>s</code> represents a valid sequence of entries and exits.</li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def minimumChairs(self, s: str) -> int:
cnt = left = 0
for c in s:
if c == "E":
if left:
left -= 1
else:
cnt += 1
else:
left += 1
return cnt
|
3,168 |
Minimum Number of Chairs in a Waiting Room
|
Easy
|
<p>You are given a string <code>s</code>. Simulate events at each second <code>i</code>:</p>
<ul>
<li>If <code>s[i] == 'E'</code>, a person enters the waiting room and takes one of the chairs in it.</li>
<li>If <code>s[i] == 'L'</code>, a person leaves the waiting room, freeing up a chair.</li>
</ul>
<p>Return the <strong>minimum </strong>number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially <strong>empty</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "EEEEEEE"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELELEEL"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Leave</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Enter</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>Leave</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "ELEELEELLL"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.</p>
</div>
<table>
<tbody>
<tr>
<th>Second</th>
<th>Event</th>
<th>People in the Waiting Room</th>
<th>Available Chairs</th>
</tr>
<tr>
<td>0</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>Enter</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>Enter</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>Enter</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>Leave</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>Leave</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>Leave</td>
<td>0</td>
<td>3</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>s</code> consists only of the letters <code>'E'</code> and <code>'L'</code>.</li>
<li><code>s</code> represents a valid sequence of entries and exits.</li>
</ul>
|
String; Simulation
|
TypeScript
|
function minimumChairs(s: string): number {
let [cnt, left] = [0, 0];
for (const c of s) {
if (c === 'E') {
if (left > 0) {
--left;
} else {
++cnt;
}
} else {
++left;
}
}
return cnt;
}
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
C++
|
class Solution {
public:
int countDays(int days, vector<vector<int>>& meetings) {
sort(meetings.begin(), meetings.end());
int ans = 0, last = 0;
for (auto& e : meetings) {
int st = e[0], ed = e[1];
if (last < st) {
ans += st - last - 1;
}
last = max(last, ed);
}
ans += days - last;
return ans;
}
};
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
Go
|
func countDays(days int, meetings [][]int) (ans int) {
sort.Slice(meetings, func(i, j int) bool { return meetings[i][0] < meetings[j][0] })
last := 0
for _, e := range meetings {
st, ed := e[0], e[1]
if last < st {
ans += st - last - 1
}
last = max(last, ed)
}
ans += days - last
return
}
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
Java
|
class Solution {
public int countDays(int days, int[][] meetings) {
Arrays.sort(meetings, (a, b) -> a[0] - b[0]);
int ans = 0, last = 0;
for (var e : meetings) {
int st = e[0], ed = e[1];
if (last < st) {
ans += st - last - 1;
}
last = Math.max(last, ed);
}
ans += days - last;
return ans;
}
}
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
Python
|
class Solution:
def countDays(self, days: int, meetings: List[List[int]]) -> int:
meetings.sort()
ans = last = 0
for st, ed in meetings:
if last < st:
ans += st - last - 1
last = max(last, ed)
ans += days - last
return ans
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
Rust
|
impl Solution {
pub fn count_days(days: i32, mut meetings: Vec<Vec<i32>>) -> i32 {
meetings.sort_by_key(|m| m[0]);
let mut ans = 0;
let mut last = 0;
for e in meetings {
let st = e[0];
let ed = e[1];
if last < st {
ans += st - last - 1;
}
last = last.max(ed);
}
ans + (days - last)
}
}
|
3,169 |
Count Days Without Meetings
|
Medium
|
<p>You are given a positive integer <code>days</code> representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array <code>meetings</code> of size <code>n</code> where, <code>meetings[i] = [start_i, end_i]</code> represents the starting and ending days of meeting <code>i</code> (inclusive).</p>
<p>Return the count of days when the employee is available for work but no meetings are scheduled.</p>
<p><strong>Note: </strong>The meetings may overlap.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 10, meetings = [[5,7],[1,3],[9,10]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 4<sup>th</sup> and 8<sup>th</sup> days.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 5, meetings = [[2,4],[1,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no meeting scheduled on the 5<sup>th </sup>day.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">days = 6, meetings = [[1,6]]</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>Meetings are scheduled for all working days.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= days <= 10<sup>9</sup></code></li>
<li><code>1 <= meetings.length <= 10<sup>5</sup></code></li>
<li><code>meetings[i].length == 2</code></li>
<li><code><font face="monospace">1 <= meetings[i][0] <= meetings[i][1] <= days</font></code></li>
</ul>
|
Array; Sorting
|
TypeScript
|
function countDays(days: number, meetings: number[][]): number {
meetings.sort((a, b) => a[0] - b[0]);
let [ans, last] = [0, 0];
for (const [st, ed] of meetings) {
if (last < st) {
ans += st - last - 1;
}
last = Math.max(last, ed);
}
ans += days - last;
return ans;
}
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
C++
|
class Solution {
public:
string clearStars(string s) {
stack<int> g[26];
int n = s.length();
vector<bool> rem(n);
for (int i = 0; i < n; ++i) {
if (s[i] == '*') {
rem[i] = true;
for (int j = 0; j < 26; ++j) {
if (!g[j].empty()) {
rem[g[j].top()] = true;
g[j].pop();
break;
}
}
} else {
g[s[i] - 'a'].push(i);
}
}
string ans;
for (int i = 0; i < n; ++i) {
if (!rem[i]) {
ans.push_back(s[i]);
}
}
return ans;
}
};
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
C#
|
public class Solution {
public string ClearStars(string s) {
int n = s.Length;
List<int>[] g = new List<int>[26];
for (int i = 0; i < 26; i++) {
g[i] = new List<int>();
}
bool[] rem = new bool[n];
for (int i = 0; i < n; i++) {
char ch = s[i];
if (ch == '*') {
rem[i] = true;
for (int j = 0; j < 26; j++) {
if (g[j].Count > 0) {
int idx = g[j][g[j].Count - 1];
g[j].RemoveAt(g[j].Count - 1);
rem[idx] = true;
break;
}
}
} else {
g[ch - 'a'].Add(i);
}
}
var ans = new System.Text.StringBuilder();
for (int i = 0; i < n; i++) {
if (!rem[i]) {
ans.Append(s[i]);
}
}
return ans.ToString();
}
}
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
Go
|
func clearStars(s string) string {
g := make([][]int, 26)
n := len(s)
rem := make([]bool, n)
for i, c := range s {
if c == '*' {
rem[i] = true
for j := 0; j < 26; j++ {
if len(g[j]) > 0 {
rem[g[j][len(g[j])-1]] = true
g[j] = g[j][:len(g[j])-1]
break
}
}
} else {
g[c-'a'] = append(g[c-'a'], i)
}
}
ans := []byte{}
for i := range s {
if !rem[i] {
ans = append(ans, s[i])
}
}
return string(ans)
}
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
Java
|
class Solution {
public String clearStars(String s) {
Deque<Integer>[] g = new Deque[26];
Arrays.setAll(g, k -> new ArrayDeque<>());
int n = s.length();
boolean[] rem = new boolean[n];
for (int i = 0; i < n; ++i) {
if (s.charAt(i) == '*') {
rem[i] = true;
for (int j = 0; j < 26; ++j) {
if (!g[j].isEmpty()) {
rem[g[j].pop()] = true;
break;
}
}
} else {
g[s.charAt(i) - 'a'].push(i);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; ++i) {
if (!rem[i]) {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
Python
|
class Solution:
def clearStars(self, s: str) -> str:
g = defaultdict(list)
n = len(s)
rem = [False] * n
for i, c in enumerate(s):
if c == "*":
rem[i] = True
for a in ascii_lowercase:
if g[a]:
rem[g[a].pop()] = True
break
else:
g[c].append(i)
return "".join(c for i, c in enumerate(s) if not rem[i])
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
Rust
|
impl Solution {
pub fn clear_stars(s: String) -> String {
let n = s.len();
let s_bytes = s.as_bytes();
let mut g: Vec<Vec<usize>> = vec![vec![]; 26];
let mut rem = vec![false; n];
let chars: Vec<char> = s.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if ch == '*' {
rem[i] = true;
for j in 0..26 {
if let Some(idx) = g[j].pop() {
rem[idx] = true;
break;
}
}
} else {
g[(ch as u8 - b'a') as usize].push(i);
}
}
chars
.into_iter()
.enumerate()
.filter_map(|(i, ch)| if !rem[i] { Some(ch) } else { None })
.collect()
}
}
|
3,170 |
Lexicographically Minimum String After Removing Stars
|
Medium
|
<p>You are given a string <code>s</code>. It may contain any number of <code>'*'</code> characters. Your task is to remove all <code>'*'</code> characters.</p>
<p>While there is a <code>'*'</code>, do the following operation:</p>
<ul>
<li>Delete the leftmost <code>'*'</code> and the <strong>smallest</strong> non-<code>'*'</code> character to its <em>left</em>. If there are several smallest characters, you can delete any of them.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> resulting string after removing all <code>'*'</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaba*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aab"</span></p>
<p><strong>Explanation:</strong></p>
<p>We should delete one of the <code>'a'</code> characters with <code>'*'</code>. If we choose <code>s[3]</code>, <code>s</code> becomes the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no <code>'*'</code> in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters and <code>'*'</code>.</li>
<li>The input is generated such that it is possible to delete all <code>'*'</code> characters.</li>
</ul>
|
Stack; Greedy; Hash Table; String; Heap (Priority Queue)
|
TypeScript
|
function clearStars(s: string): string {
const g: number[][] = Array.from({ length: 26 }, () => []);
const n = s.length;
const rem: boolean[] = Array(n).fill(false);
for (let i = 0; i < n; ++i) {
if (s[i] === '*') {
rem[i] = true;
for (let j = 0; j < 26; ++j) {
if (g[j].length) {
rem[g[j].pop()!] = true;
break;
}
}
} else {
g[s.charCodeAt(i) - 97].push(i);
}
}
return s
.split('')
.filter((_, i) => !rem[i])
.join('');
}
|
3,171 |
Find Subarray With Bitwise OR Closest to K
|
Hard
|
<p>You are given an array <code>nums</code> and an integer <code>k</code>. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that the <strong>absolute difference</strong> between <code>k</code> and the bitwise <code>OR</code> of the subarray elements is as<strong> small</strong> as possible. In other words, select a subarray <code>nums[l..r]</code> such that <code>|k - (nums[l] OR nums[l + 1] ... OR nums[r])|</code> is minimum.</p>
<p>Return the <strong>minimum</strong> possible value of the absolute difference.</p>
<p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,4,5], k = 3</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[0..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 3| = 0</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,3], k = 2</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[1..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 2| = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray with <code>OR</code> value 1, which gives the minimum absolute difference <code>|10 - 1| = 9</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
C++
|
class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
int mx = *max_element(nums.begin(), nums.end());
int m = 32 - __builtin_clz(mx);
int n = nums.size();
int ans = INT_MAX;
vector<int> cnt(m);
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
ans = min(ans, abs(s - k));
for (int h = 0; h < m; ++h) {
if (nums[j] >> h & 1) {
++cnt[h];
}
}
while (i < j && s > k) {
for (int h = 0; h < m; ++h) {
if (nums[i] >> h & 1 && --cnt[h] == 0) {
s ^= 1 << h;
}
}
ans = min(ans, abs(s - k));
++i;
}
}
return ans;
}
};
|
3,171 |
Find Subarray With Bitwise OR Closest to K
|
Hard
|
<p>You are given an array <code>nums</code> and an integer <code>k</code>. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that the <strong>absolute difference</strong> between <code>k</code> and the bitwise <code>OR</code> of the subarray elements is as<strong> small</strong> as possible. In other words, select a subarray <code>nums[l..r]</code> such that <code>|k - (nums[l] OR nums[l + 1] ... OR nums[r])|</code> is minimum.</p>
<p>Return the <strong>minimum</strong> possible value of the absolute difference.</p>
<p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,4,5], k = 3</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[0..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 3| = 0</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,3], k = 2</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[1..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 2| = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray with <code>OR</code> value 1, which gives the minimum absolute difference <code>|10 - 1| = 9</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Go
|
func minimumDifference(nums []int, k int) int {
m := bits.Len(uint(slices.Max(nums)))
cnt := make([]int, m)
ans := math.MaxInt32
s, i := 0, 0
for j, x := range nums {
s |= x
ans = min(ans, abs(s-k))
for h := 0; h < m; h++ {
if x>>h&1 == 1 {
cnt[h]++
}
}
for i < j && s > k {
y := nums[i]
for h := 0; h < m; h++ {
if y>>h&1 == 1 {
cnt[h]--
if cnt[h] == 0 {
s ^= 1 << h
}
}
}
ans = min(ans, abs(s-k))
i++
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,171 |
Find Subarray With Bitwise OR Closest to K
|
Hard
|
<p>You are given an array <code>nums</code> and an integer <code>k</code>. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that the <strong>absolute difference</strong> between <code>k</code> and the bitwise <code>OR</code> of the subarray elements is as<strong> small</strong> as possible. In other words, select a subarray <code>nums[l..r]</code> such that <code>|k - (nums[l] OR nums[l + 1] ... OR nums[r])|</code> is minimum.</p>
<p>Return the <strong>minimum</strong> possible value of the absolute difference.</p>
<p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,4,5], k = 3</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[0..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 3| = 0</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,3], k = 2</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[1..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 2| = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray with <code>OR</code> value 1, which gives the minimum absolute difference <code>|10 - 1| = 9</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Java
|
class Solution {
public int minimumDifference(int[] nums, int k) {
int mx = 0;
for (int x : nums) {
mx = Math.max(mx, x);
}
int m = 32 - Integer.numberOfLeadingZeros(mx);
int[] cnt = new int[m];
int n = nums.length;
int ans = Integer.MAX_VALUE;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
ans = Math.min(ans, Math.abs(s - k));
for (int h = 0; h < m; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
while (i < j && s > k) {
for (int h = 0; h < m; ++h) {
if ((nums[i] >> h & 1) == 1 && --cnt[h] == 0) {
s ^= 1 << h;
}
}
++i;
ans = Math.min(ans, Math.abs(s - k));
}
}
return ans;
}
}
|
3,171 |
Find Subarray With Bitwise OR Closest to K
|
Hard
|
<p>You are given an array <code>nums</code> and an integer <code>k</code>. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that the <strong>absolute difference</strong> between <code>k</code> and the bitwise <code>OR</code> of the subarray elements is as<strong> small</strong> as possible. In other words, select a subarray <code>nums[l..r]</code> such that <code>|k - (nums[l] OR nums[l + 1] ... OR nums[r])|</code> is minimum.</p>
<p>Return the <strong>minimum</strong> possible value of the absolute difference.</p>
<p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,4,5], k = 3</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[0..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 3| = 0</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,3], k = 2</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[1..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 2| = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray with <code>OR</code> value 1, which gives the minimum absolute difference <code>|10 - 1| = 9</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Python
|
class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
m = max(nums).bit_length()
cnt = [0] * m
s = i = 0
ans = inf
for j, x in enumerate(nums):
s |= x
ans = min(ans, abs(s - k))
for h in range(m):
if x >> h & 1:
cnt[h] += 1
while i < j and s > k:
y = nums[i]
for h in range(m):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
ans = min(ans, abs(s - k))
return ans
|
3,171 |
Find Subarray With Bitwise OR Closest to K
|
Hard
|
<p>You are given an array <code>nums</code> and an integer <code>k</code>. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that the <strong>absolute difference</strong> between <code>k</code> and the bitwise <code>OR</code> of the subarray elements is as<strong> small</strong> as possible. In other words, select a subarray <code>nums[l..r]</code> such that <code>|k - (nums[l] OR nums[l + 1] ... OR nums[r])|</code> is minimum.</p>
<p>Return the <strong>minimum</strong> possible value of the absolute difference.</p>
<p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,4,5], k = 3</span></p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[0..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 3| = 0</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,3], k = 2</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>nums[1..1]</code> has <code>OR</code> value 3, which gives the minimum absolute difference <code>|3 - 2| = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray with <code>OR</code> value 1, which gives the minimum absolute difference <code>|10 - 1| = 9</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
TypeScript
|
function minimumDifference(nums: number[], k: number): number {
const m = Math.max(...nums).toString(2).length;
const n = nums.length;
const cnt: number[] = Array(m).fill(0);
let ans = Infinity;
for (let i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
ans = Math.min(ans, Math.abs(s - k));
for (let h = 0; h < m; ++h) {
if ((nums[j] >> h) & 1) {
++cnt[h];
}
}
while (i < j && s > k) {
for (let h = 0; h < m; ++h) {
if ((nums[i] >> h) & 1 && --cnt[h] === 0) {
s ^= 1 << h;
}
}
ans = Math.min(ans, Math.abs(s - k));
++i;
}
}
return ans;
}
|
3,172 |
Second Day Verification
|
Easy
|
<p>Table: <code>emails</code></p>
<pre>
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| email_id | int |
| user_id | int |
| signup_date | datetime |
+-------------+----------+
(email_id, user_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the email ID, user ID, and signup date.
</pre>
<p>Table: <code>texts</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| text_id | int |
| email_id | int |
| signup_action | enum |
| action_date | datetime |
+---------------+----------+
(text_id, email_id) is the primary key (combination of columns with unique values) for this table.
signup_action is an enum type of ('Verified', 'Not Verified').
Each row of this table contains the text ID, email ID, signup action, and action date.
</pre>
<p>Write a Solution to find the user IDs of those who <strong>verified</strong> their <strong>sign-up</strong> on the <strong>second day</strong>.</p>
<p>Return <em>the result table ordered by</em> <code>user_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>emails table:</p>
<pre class="example-io">
+----------+---------+---------------------+
| email_id | user_id | signup_date |
+----------+---------+---------------------+
| 125 | 7771 | 2022-06-14 09:30:00|
| 433 | 1052 | 2022-07-09 08:15:00|
| 234 | 7005 | 2022-08-20 10:00:00|
+----------+---------+---------------------+
</pre>
<p>texts table:</p>
<pre class="example-io">
+---------+----------+--------------+---------------------+
| text_id | email_id | signup_action| action_date |
+---------+----------+--------------+---------------------+
| 1 | 125 | Verified | 2022-06-15 08:30:00|
| 2 | 433 | Not Verified | 2022-07-10 10:45:00|
| 4 | 234 | Verified | 2022-08-21 09:30:00|
+---------+----------+--------------+---------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------+
| user_id |
+---------+
| 7005 |
| 7771 |
+---------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>User with user_id 7005 and email_id 234 signed up on 2022-08-20 10:00:00 and verified on second day of the signup.</li>
<li>User with user_id 7771 and email_id 125 signed up on 2022-06-14 09:30:00 and verified on second day of the signup.</li>
</ul>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT user_id
FROM
Emails AS e
JOIN texts AS t
ON e.email_id = t.email_id
AND DATEDIFF(action_date, signup_date) = 1
AND signup_action = 'Verified'
ORDER BY 1;
|
3,173 |
Bitwise OR of Adjacent Elements
|
Easy
|
<p>Given an array <code>nums</code> of length <code>n</code>, return an array <code>answer</code> of length <code>n - 1</code> such that <code>answer[i] = nums[i] | nums[i + 1]</code> where <code>|</code> is the bitwise <code>OR</code> operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,7,15]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,7,15]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [8,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[12,6]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,4,9,11]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,13,11]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
vector<int> orArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n - 1);
for (int i = 0; i < n - 1; ++i) {
ans[i] = nums[i] | nums[i + 1];
}
return ans;
}
};
|
3,173 |
Bitwise OR of Adjacent Elements
|
Easy
|
<p>Given an array <code>nums</code> of length <code>n</code>, return an array <code>answer</code> of length <code>n - 1</code> such that <code>answer[i] = nums[i] | nums[i + 1]</code> where <code>|</code> is the bitwise <code>OR</code> operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,7,15]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,7,15]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [8,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[12,6]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,4,9,11]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,13,11]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func orArray(nums []int) (ans []int) {
for i, x := range nums[1:] {
ans = append(ans, x|nums[i])
}
return
}
|
3,173 |
Bitwise OR of Adjacent Elements
|
Easy
|
<p>Given an array <code>nums</code> of length <code>n</code>, return an array <code>answer</code> of length <code>n - 1</code> such that <code>answer[i] = nums[i] | nums[i + 1]</code> where <code>|</code> is the bitwise <code>OR</code> operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,7,15]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,7,15]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [8,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[12,6]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,4,9,11]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,13,11]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int[] orArray(int[] nums) {
int n = nums.length;
int[] ans = new int[n - 1];
for (int i = 0; i < n - 1; ++i) {
ans[i] = nums[i] | nums[i + 1];
}
return ans;
}
}
|
3,173 |
Bitwise OR of Adjacent Elements
|
Easy
|
<p>Given an array <code>nums</code> of length <code>n</code>, return an array <code>answer</code> of length <code>n - 1</code> such that <code>answer[i] = nums[i] | nums[i + 1]</code> where <code>|</code> is the bitwise <code>OR</code> operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,7,15]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,7,15]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [8,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[12,6]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,4,9,11]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,13,11]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def orArray(self, nums: List[int]) -> List[int]:
return [a | b for a, b in pairwise(nums)]
|
3,173 |
Bitwise OR of Adjacent Elements
|
Easy
|
<p>Given an array <code>nums</code> of length <code>n</code>, return an array <code>answer</code> of length <code>n - 1</code> such that <code>answer[i] = nums[i] | nums[i + 1]</code> where <code>|</code> is the bitwise <code>OR</code> operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,7,15]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,7,15]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [8,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[12,6]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,4,9,11]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,13,11]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function orArray(nums: number[]): number[] {
return nums.slice(0, -1).map((v, i) => v | nums[i + 1]);
}
|
3,174 |
Clear Digits
|
Easy
|
<p>You are given a string <code>s</code>.</p>
<p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p>
<ul>
<li>Delete the <em>first</em> digit and the <strong>closest</strong> <b>non-digit</b> character to its <em>left</em>.</li>
</ul>
<p>Return the resulting string after removing all digits.</p>
<p><strong>Note</strong> that the operation <em>cannot</em> be performed on a digit that does not have any non-digit character to its left.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no digit in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cb34"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<p>First, we apply the operation on <code>s[2]</code>, and <code>s</code> becomes <code>"c4"</code>.</p>
<p>Then we apply the operation on <code>s[1]</code>, and <code>s</code> becomes <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters and digits.</li>
<li>The input is generated such that it is possible to delete all digits.</li>
</ul>
|
Stack; String; Simulation
|
C++
|
class Solution {
public:
string clearDigits(string s) {
string stk;
for (char c : s) {
if (isdigit(c)) {
stk.pop_back();
} else {
stk.push_back(c);
}
}
return stk;
}
};
|
3,174 |
Clear Digits
|
Easy
|
<p>You are given a string <code>s</code>.</p>
<p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p>
<ul>
<li>Delete the <em>first</em> digit and the <strong>closest</strong> <b>non-digit</b> character to its <em>left</em>.</li>
</ul>
<p>Return the resulting string after removing all digits.</p>
<p><strong>Note</strong> that the operation <em>cannot</em> be performed on a digit that does not have any non-digit character to its left.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no digit in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cb34"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<p>First, we apply the operation on <code>s[2]</code>, and <code>s</code> becomes <code>"c4"</code>.</p>
<p>Then we apply the operation on <code>s[1]</code>, and <code>s</code> becomes <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters and digits.</li>
<li>The input is generated such that it is possible to delete all digits.</li>
</ul>
|
Stack; String; Simulation
|
Go
|
func clearDigits(s string) string {
stk := []byte{}
for i := range s {
if s[i] >= '0' && s[i] <= '9' {
stk = stk[:len(stk)-1]
} else {
stk = append(stk, s[i])
}
}
return string(stk)
}
|
3,174 |
Clear Digits
|
Easy
|
<p>You are given a string <code>s</code>.</p>
<p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p>
<ul>
<li>Delete the <em>first</em> digit and the <strong>closest</strong> <b>non-digit</b> character to its <em>left</em>.</li>
</ul>
<p>Return the resulting string after removing all digits.</p>
<p><strong>Note</strong> that the operation <em>cannot</em> be performed on a digit that does not have any non-digit character to its left.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no digit in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cb34"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<p>First, we apply the operation on <code>s[2]</code>, and <code>s</code> becomes <code>"c4"</code>.</p>
<p>Then we apply the operation on <code>s[1]</code>, and <code>s</code> becomes <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters and digits.</li>
<li>The input is generated such that it is possible to delete all digits.</li>
</ul>
|
Stack; String; Simulation
|
Java
|
class Solution {
public String clearDigits(String s) {
StringBuilder stk = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
stk.deleteCharAt(stk.length() - 1);
} else {
stk.append(c);
}
}
return stk.toString();
}
}
|
3,174 |
Clear Digits
|
Easy
|
<p>You are given a string <code>s</code>.</p>
<p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p>
<ul>
<li>Delete the <em>first</em> digit and the <strong>closest</strong> <b>non-digit</b> character to its <em>left</em>.</li>
</ul>
<p>Return the resulting string after removing all digits.</p>
<p><strong>Note</strong> that the operation <em>cannot</em> be performed on a digit that does not have any non-digit character to its left.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no digit in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cb34"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<p>First, we apply the operation on <code>s[2]</code>, and <code>s</code> becomes <code>"c4"</code>.</p>
<p>Then we apply the operation on <code>s[1]</code>, and <code>s</code> becomes <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters and digits.</li>
<li>The input is generated such that it is possible to delete all digits.</li>
</ul>
|
Stack; String; Simulation
|
Python
|
class Solution:
def clearDigits(self, s: str) -> str:
stk = []
for c in s:
if c.isdigit():
stk.pop()
else:
stk.append(c)
return "".join(stk)
|
3,174 |
Clear Digits
|
Easy
|
<p>You are given a string <code>s</code>.</p>
<p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p>
<ul>
<li>Delete the <em>first</em> digit and the <strong>closest</strong> <b>non-digit</b> character to its <em>left</em>.</li>
</ul>
<p>Return the resulting string after removing all digits.</p>
<p><strong>Note</strong> that the operation <em>cannot</em> be performed on a digit that does not have any non-digit character to its left.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abc"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no digit in the string.<!-- notionvc: ff07e34f-b1d6-41fb-9f83-5d0ba3c1ecde --></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cb34"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<p>First, we apply the operation on <code>s[2]</code>, and <code>s</code> becomes <code>"c4"</code>.</p>
<p>Then we apply the operation on <code>s[1]</code>, and <code>s</code> becomes <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters and digits.</li>
<li>The input is generated such that it is possible to delete all digits.</li>
</ul>
|
Stack; String; Simulation
|
TypeScript
|
function clearDigits(s: string): string {
const stk: string[] = [];
for (const c of s) {
if (!isNaN(parseInt(c))) {
stk.pop();
} else {
stk.push(c);
}
}
return stk.join('');
}
|
3,175 |
Find The First Player to win K Games in a Row
|
Medium
|
<p>A competition consists of <code>n</code> players numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given an integer array <code>skills</code> of size <code>n</code> and a <strong>positive</strong> integer <code>k</code>, where <code>skills[i]</code> is the skill level of player <code>i</code>. All integers in <code>skills</code> are <strong>unique</strong>.</p>
<p>All players are standing in a queue in order from player <code>0</code> to player <code>n - 1</code>.</p>
<p>The competition process is as follows:</p>
<ul>
<li>The first two players in the queue play a game, and the player with the <strong>higher</strong> skill level wins.</li>
<li>After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.</li>
</ul>
<p>The winner of the competition is the <strong>first</strong> player who wins <code>k</code> games <strong>in a row</strong>.</p>
<p>Return the initial index of the <em>winning</em> player.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [4,2,6,3,9], k = 2</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2,3,4]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is <code>[0,2,3,4,1]</code>.</li>
<li>Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is <code>[2,3,4,1,0]</code>.</li>
<li>Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is <code>[2,4,1,0,3]</code>.</li>
</ul>
<p>Player 2 won <code>k = 2</code> games in a row, so the winner is player 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [2,5,4], k = 3</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
<li>Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is <code>[1,0,2]</code>.</li>
<li>Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
</ul>
<p>Player 1 won <code>k = 3</code> games in a row, so the winner is player 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == skills.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= skills[i] <= 10<sup>6</sup></code></li>
<li>All integers in <code>skills</code> are unique.</li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
int findWinningPlayer(vector<int>& skills, int k) {
int n = skills.size();
k = min(k, n - 1);
int i = 0, cnt = 0;
for (int j = 1; j < n; ++j) {
if (skills[i] < skills[j]) {
i = j;
cnt = 1;
} else {
++cnt;
}
if (cnt == k) {
break;
}
}
return i;
}
};
|
3,175 |
Find The First Player to win K Games in a Row
|
Medium
|
<p>A competition consists of <code>n</code> players numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given an integer array <code>skills</code> of size <code>n</code> and a <strong>positive</strong> integer <code>k</code>, where <code>skills[i]</code> is the skill level of player <code>i</code>. All integers in <code>skills</code> are <strong>unique</strong>.</p>
<p>All players are standing in a queue in order from player <code>0</code> to player <code>n - 1</code>.</p>
<p>The competition process is as follows:</p>
<ul>
<li>The first two players in the queue play a game, and the player with the <strong>higher</strong> skill level wins.</li>
<li>After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.</li>
</ul>
<p>The winner of the competition is the <strong>first</strong> player who wins <code>k</code> games <strong>in a row</strong>.</p>
<p>Return the initial index of the <em>winning</em> player.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [4,2,6,3,9], k = 2</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2,3,4]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is <code>[0,2,3,4,1]</code>.</li>
<li>Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is <code>[2,3,4,1,0]</code>.</li>
<li>Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is <code>[2,4,1,0,3]</code>.</li>
</ul>
<p>Player 2 won <code>k = 2</code> games in a row, so the winner is player 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [2,5,4], k = 3</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
<li>Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is <code>[1,0,2]</code>.</li>
<li>Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
</ul>
<p>Player 1 won <code>k = 3</code> games in a row, so the winner is player 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == skills.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= skills[i] <= 10<sup>6</sup></code></li>
<li>All integers in <code>skills</code> are unique.</li>
</ul>
|
Array; Simulation
|
Go
|
func findWinningPlayer(skills []int, k int) int {
n := len(skills)
k = min(k, n-1)
i, cnt := 0, 0
for j := 1; j < n; j++ {
if skills[i] < skills[j] {
i = j
cnt = 1
} else {
cnt++
}
if cnt == k {
break
}
}
return i
}
|
3,175 |
Find The First Player to win K Games in a Row
|
Medium
|
<p>A competition consists of <code>n</code> players numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given an integer array <code>skills</code> of size <code>n</code> and a <strong>positive</strong> integer <code>k</code>, where <code>skills[i]</code> is the skill level of player <code>i</code>. All integers in <code>skills</code> are <strong>unique</strong>.</p>
<p>All players are standing in a queue in order from player <code>0</code> to player <code>n - 1</code>.</p>
<p>The competition process is as follows:</p>
<ul>
<li>The first two players in the queue play a game, and the player with the <strong>higher</strong> skill level wins.</li>
<li>After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.</li>
</ul>
<p>The winner of the competition is the <strong>first</strong> player who wins <code>k</code> games <strong>in a row</strong>.</p>
<p>Return the initial index of the <em>winning</em> player.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [4,2,6,3,9], k = 2</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2,3,4]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is <code>[0,2,3,4,1]</code>.</li>
<li>Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is <code>[2,3,4,1,0]</code>.</li>
<li>Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is <code>[2,4,1,0,3]</code>.</li>
</ul>
<p>Player 2 won <code>k = 2</code> games in a row, so the winner is player 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [2,5,4], k = 3</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
<li>Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is <code>[1,0,2]</code>.</li>
<li>Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
</ul>
<p>Player 1 won <code>k = 3</code> games in a row, so the winner is player 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == skills.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= skills[i] <= 10<sup>6</sup></code></li>
<li>All integers in <code>skills</code> are unique.</li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int findWinningPlayer(int[] skills, int k) {
int n = skills.length;
k = Math.min(k, n - 1);
int i = 0, cnt = 0;
for (int j = 1; j < n; ++j) {
if (skills[i] < skills[j]) {
i = j;
cnt = 1;
} else {
++cnt;
}
if (cnt == k) {
break;
}
}
return i;
}
}
|
3,175 |
Find The First Player to win K Games in a Row
|
Medium
|
<p>A competition consists of <code>n</code> players numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given an integer array <code>skills</code> of size <code>n</code> and a <strong>positive</strong> integer <code>k</code>, where <code>skills[i]</code> is the skill level of player <code>i</code>. All integers in <code>skills</code> are <strong>unique</strong>.</p>
<p>All players are standing in a queue in order from player <code>0</code> to player <code>n - 1</code>.</p>
<p>The competition process is as follows:</p>
<ul>
<li>The first two players in the queue play a game, and the player with the <strong>higher</strong> skill level wins.</li>
<li>After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.</li>
</ul>
<p>The winner of the competition is the <strong>first</strong> player who wins <code>k</code> games <strong>in a row</strong>.</p>
<p>Return the initial index of the <em>winning</em> player.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [4,2,6,3,9], k = 2</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2,3,4]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is <code>[0,2,3,4,1]</code>.</li>
<li>Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is <code>[2,3,4,1,0]</code>.</li>
<li>Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is <code>[2,4,1,0,3]</code>.</li>
</ul>
<p>Player 2 won <code>k = 2</code> games in a row, so the winner is player 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [2,5,4], k = 3</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
<li>Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is <code>[1,0,2]</code>.</li>
<li>Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
</ul>
<p>Player 1 won <code>k = 3</code> games in a row, so the winner is player 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == skills.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= skills[i] <= 10<sup>6</sup></code></li>
<li>All integers in <code>skills</code> are unique.</li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def findWinningPlayer(self, skills: List[int], k: int) -> int:
n = len(skills)
k = min(k, n - 1)
i = cnt = 0
for j in range(1, n):
if skills[i] < skills[j]:
i = j
cnt = 1
else:
cnt += 1
if cnt == k:
break
return i
|
3,175 |
Find The First Player to win K Games in a Row
|
Medium
|
<p>A competition consists of <code>n</code> players numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given an integer array <code>skills</code> of size <code>n</code> and a <strong>positive</strong> integer <code>k</code>, where <code>skills[i]</code> is the skill level of player <code>i</code>. All integers in <code>skills</code> are <strong>unique</strong>.</p>
<p>All players are standing in a queue in order from player <code>0</code> to player <code>n - 1</code>.</p>
<p>The competition process is as follows:</p>
<ul>
<li>The first two players in the queue play a game, and the player with the <strong>higher</strong> skill level wins.</li>
<li>After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.</li>
</ul>
<p>The winner of the competition is the <strong>first</strong> player who wins <code>k</code> games <strong>in a row</strong>.</p>
<p>Return the initial index of the <em>winning</em> player.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [4,2,6,3,9], k = 2</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2,3,4]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 0 is higher than that of player 1, player 0 wins. The resulting queue is <code>[0,2,3,4,1]</code>.</li>
<li>Players 0 and 2 play a game, since the skill of player 2 is higher than that of player 0, player 2 wins. The resulting queue is <code>[2,3,4,1,0]</code>.</li>
<li>Players 2 and 3 play a game, since the skill of player 2 is higher than that of player 3, player 2 wins. The resulting queue is <code>[2,4,1,0,3]</code>.</li>
</ul>
<p>Player 2 won <code>k = 2</code> games in a row, so the winner is player 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">skills = [2,5,4], k = 3</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>Initially, the queue of players is <code>[0,1,2]</code>. The following process happens:</p>
<ul>
<li>Players 0 and 1 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
<li>Players 1 and 2 play a game, since the skill of player 1 is higher than that of player 2, player 1 wins. The resulting queue is <code>[1,0,2]</code>.</li>
<li>Players 1 and 0 play a game, since the skill of player 1 is higher than that of player 0, player 1 wins. The resulting queue is <code>[1,2,0]</code>.</li>
</ul>
<p>Player 1 won <code>k = 3</code> games in a row, so the winner is player 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == skills.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= skills[i] <= 10<sup>6</sup></code></li>
<li>All integers in <code>skills</code> are unique.</li>
</ul>
|
Array; Simulation
|
TypeScript
|
function findWinningPlayer(skills: number[], k: number): number {
const n = skills.length;
k = Math.min(k, n - 1);
let [i, cnt] = [0, 0];
for (let j = 1; j < n; ++j) {
if (skills[i] < skills[j]) {
i = j;
cnt = 1;
} else {
++cnt;
}
if (cnt === k) {
break;
}
}
return i;
}
|
3,176 |
Find the Maximum Length of a Good Subsequence I
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(nums.length, 25)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
C++
|
class Solution {
public:
int maximumLength(vector<int>& nums, int k) {
int n = nums.size();
int f[n][k + 1];
memset(f, 0, sizeof(f));
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int h = 0; h <= k; ++h) {
for (int j = 0; j < i; ++j) {
if (nums[i] == nums[j]) {
f[i][h] = max(f[i][h], f[j][h]);
} else if (h) {
f[i][h] = max(f[i][h], f[j][h - 1]);
}
}
++f[i][h];
}
ans = max(ans, f[i][k]);
}
return ans;
}
};
|
3,176 |
Find the Maximum Length of a Good Subsequence I
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(nums.length, 25)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
Go
|
func maximumLength(nums []int, k int) (ans int) {
f := make([][]int, len(nums))
for i := range f {
f[i] = make([]int, k+1)
}
for i, x := range nums {
for h := 0; h <= k; h++ {
for j, y := range nums[:i] {
if x == y {
f[i][h] = max(f[i][h], f[j][h])
} else if h > 0 {
f[i][h] = max(f[i][h], f[j][h-1])
}
}
f[i][h]++
}
ans = max(ans, f[i][k])
}
return
}
|
3,176 |
Find the Maximum Length of a Good Subsequence I
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(nums.length, 25)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
Java
|
class Solution {
public int maximumLength(int[] nums, int k) {
int n = nums.length;
int[][] f = new int[n][k + 1];
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int h = 0; h <= k; ++h) {
for (int j = 0; j < i; ++j) {
if (nums[i] == nums[j]) {
f[i][h] = Math.max(f[i][h], f[j][h]);
} else if (h > 0) {
f[i][h] = Math.max(f[i][h], f[j][h - 1]);
}
}
++f[i][h];
}
ans = Math.max(ans, f[i][k]);
}
return ans;
}
}
|
3,176 |
Find the Maximum Length of a Good Subsequence I
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(nums.length, 25)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
Python
|
class Solution:
def maximumLength(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [[1] * (k + 1) for _ in range(n)]
ans = 0
for i, x in enumerate(nums):
for h in range(k + 1):
for j, y in enumerate(nums[:i]):
if x == y:
f[i][h] = max(f[i][h], f[j][h] + 1)
elif h:
f[i][h] = max(f[i][h], f[j][h - 1] + 1)
ans = max(ans, f[i][k])
return ans
|
3,176 |
Find the Maximum Length of a Good Subsequence I
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(nums.length, 25)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
TypeScript
|
function maximumLength(nums: number[], k: number): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0));
let ans = 0;
for (let i = 0; i < n; ++i) {
for (let h = 0; h <= k; ++h) {
for (let j = 0; j < i; ++j) {
if (nums[i] === nums[j]) {
f[i][h] = Math.max(f[i][h], f[j][h]);
} else if (h) {
f[i][h] = Math.max(f[i][h], f[j][h - 1]);
}
}
++f[i][h];
}
ans = Math.max(ans, f[i][k]);
}
return ans;
}
|
3,177 |
Find the Maximum Length of a Good Subsequence II
|
Hard
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(50, nums.length)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
C++
|
class Solution {
public:
int maximumLength(vector<int>& nums, int k) {
int n = nums.size();
vector<vector<int>> f(n, vector<int>(k + 1));
vector<unordered_map<int, int>> mp(k + 1);
vector<vector<int>> g(k + 1, vector<int>(3));
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int h = 0; h <= k; ++h) {
f[i][h] = mp[h][nums[i]];
if (h > 0) {
if (g[h - 1][0] != nums[i]) {
f[i][h] = max(f[i][h], g[h - 1][1]);
} else {
f[i][h] = max(f[i][h], g[h - 1][2]);
}
}
++f[i][h];
mp[h][nums[i]] = max(mp[h][nums[i]], f[i][h]);
if (g[h][0] != nums[i]) {
if (f[i][h] >= g[h][1]) {
g[h][2] = g[h][1];
g[h][1] = f[i][h];
g[h][0] = nums[i];
} else {
g[h][2] = max(g[h][2], f[i][h]);
}
} else {
g[h][1] = max(g[h][1], f[i][h]);
}
ans = max(ans, f[i][h]);
}
}
return ans;
}
};
|
3,177 |
Find the Maximum Length of a Good Subsequence II
|
Hard
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(50, nums.length)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
Go
|
func maximumLength(nums []int, k int) int {
n := len(nums)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, k+1)
}
mp := make([]map[int]int, k+1)
for i := range mp {
mp[i] = make(map[int]int)
}
g := make([][3]int, k+1)
ans := 0
for i := 0; i < n; i++ {
for h := 0; h <= k; h++ {
f[i][h] = mp[h][nums[i]]
if h > 0 {
if g[h-1][0] != nums[i] {
if g[h-1][1] > f[i][h] {
f[i][h] = g[h-1][1]
}
} else {
if g[h-1][2] > f[i][h] {
f[i][h] = g[h-1][2]
}
}
}
f[i][h]++
if f[i][h] > mp[h][nums[i]] {
mp[h][nums[i]] = f[i][h]
}
if g[h][0] != nums[i] {
if f[i][h] >= g[h][1] {
g[h][2] = g[h][1]
g[h][1] = f[i][h]
g[h][0] = nums[i]
} else if f[i][h] > g[h][2] {
g[h][2] = f[i][h]
}
} else {
if f[i][h] > g[h][1] {
g[h][1] = f[i][h]
}
}
if f[i][h] > ans {
ans = f[i][h]
}
}
}
return ans
}
|
3,177 |
Find the Maximum Length of a Good Subsequence II
|
Hard
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. A sequence of integers <code>seq</code> is called <strong>good</strong> if there are <strong>at most</strong> <code>k</code> indices <code>i</code> in the range <code>[0, seq.length - 2]</code> such that <code>seq[i] != seq[i + 1]</code>.</p>
<p>Return the <strong>maximum</strong> possible length of a <strong>good</strong> <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,<u>2</u>,<u>1</u>,<u>1</u>,3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,1], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum length subsequence is <code>[<u>1</u>,2,3,4,5,<u>1</u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= min(50, nums.length)</code></li>
</ul>
|
Array; Hash Table; Dynamic Programming
|
Java
|
class Solution {
public int maximumLength(int[] nums, int k) {
int n = nums.length;
int[][] f = new int[n][k + 1];
Map<Integer, Integer>[] mp = new HashMap[k + 1];
Arrays.setAll(mp, i -> new HashMap<>());
int[][] g = new int[k + 1][3];
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int h = 0; h <= k; ++h) {
f[i][h] = mp[h].getOrDefault(nums[i], 0);
if (h > 0) {
if (g[h - 1][0] != nums[i]) {
f[i][h] = Math.max(f[i][h], g[h - 1][1]);
} else {
f[i][h] = Math.max(f[i][h], g[h - 1][2]);
}
}
++f[i][h];
mp[h].merge(nums[i], f[i][h], Integer::max);
if (g[h][0] != nums[i]) {
if (f[i][h] >= g[h][1]) {
g[h][2] = g[h][1];
g[h][1] = f[i][h];
g[h][0] = nums[i];
} else {
g[h][2] = Math.max(g[h][2], f[i][h]);
}
} else {
g[h][1] = Math.max(g[h][1], f[i][h]);
}
ans = Math.max(ans, f[i][h]);
}
}
return ans;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.