id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
3,053
|
Classifying Triangles by Lengths
|
Easy
|
<p>Table: <font face="monospace"><code>Triangles</code></font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| A | int |
| B | int |
| C | int |
+-------------+------+
(A, B, C) is the primary key for this table.
Each row include the lengths of each of a triangle's three sides.
</pre>
<p>Write a query to find the type of <strong>triangle</strong>. Output one of the following for each row:</p>
<ul>
<li><strong>Equilateral</strong>: It's a triangle with <code>3</code> sides of equal length.</li>
<li><strong>Isosceles</strong>: It's a triangle with <code>2</code> sides of equal length.</li>
<li><strong>Scalene</strong>: It's a triangle with <code>3</code> sides of differing lengths.</li>
<li><strong>Not A Triangle: </strong>The given values of <code>A</code>, <code>B</code>, and <code>C</code> don't form a triangle.</li>
</ul>
<p>Return <em>the result table in <strong>any order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Triangles table:
+----+----+----+
| A | B | C |
+----+----+----+
| 20 | 20 | 23 |
| 20 | 20 | 20 |
| 20 | 21 | 22 |
| 13 | 14 | 30 |
+----+----+----+
<strong>Output:</strong>
+----------------+
| triangle_type |
+----------------+
| Isosceles |
| Equilateral |
| Scalene |
| Not A Triangle |
+----------------+
<strong>Explanation:</strong>
- Values in the first row from an Isosceles triangle, because A = B.
- Values in the second row from an Equilateral triangle, because A = B = C.
- Values in the third row from an Scalene triangle, because A != B != C.
- Values in the fourth row cannot form a triangle, because the combined value of sides A and B is not larger than that of side C.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
CASE
WHEN A + B <= C
OR A + C <= B
OR B + C <= A THEN 'Not A Triangle'
WHEN A = B
AND B = c THEN 'Equilateral'
WHEN (A = B) + (B = C) + (A = C) = 1 THEN 'Isosceles'
ELSE 'Scalene'
END AS triangle_type
FROM Triangles;
|
3,054
|
Binary Tree Nodes
|
Medium
|
<p>Table: <font face="monospace"><code>Tree</code></font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| N | int |
| P | int |
+-------------+------+
N is the column of unique values for this table.
Each row includes N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.
</pre>
<p>Write a solution to find the node type of the Binary Tree. Output one of the following for each node:</p>
<ul>
<li><strong>Root</strong>: if the node is the root node.</li>
<li><strong>Leaf</strong>: if the node is the leaf node.</li>
<li><strong>Inner</strong>: if the node is neither root nor leaf node.</li>
</ul>
<p>Return <em>the result table ordered by node value in <strong>ascending order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Tree table:
+---+------+
| N | P |
+---+------+
| 1 | 2 |
| 3 | 2 |
| 6 | 8 |
| 9 | 8 |
| 2 | 5 |
| 8 | 5 |
| 5 | null |
+---+------+
<strong>Output:</strong>
+---+-------+
| N | Type |
+---+-------+
| 1 | Leaf |
| 2 | Inner |
| 3 | Leaf |
| 5 | Root |
| 6 | Leaf |
| 8 | Inner |
| 9 | Leaf |
+---+-------+
<strong>Explanation:</strong>
- Node 5 is the root node since it has no parent node.
- Nodes 1, 3, 6, and 9 are leaf nodes because they don't have any child nodes.
- Nodes 2, and 8 are inner nodes as they serve as parents to some of the nodes in the structure.
</pre>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/tree-node/description/" target="_blank"> 608: Tree Node.</a></p>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT DISTINCT
t1.N AS N,
IF(t1.P IS NULL, 'Root', IF(t2.P IS NULL, 'Leaf', 'Inner')) AS Type
FROM
Tree AS t1
LEFT JOIN Tree AS t2 ON t1.N = t2.p
ORDER BY 1;
|
3,055
|
Top Percentile Fraud
|
Medium
|
<p>Table: <code>Fraud</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| policy_id | int |
| state | varchar |
| fraud_score | int |
+-------------+---------+
policy_id is column of unique values for this table.
This table contains policy id, state, and fraud score.
</pre>
<p>The Leetcode Insurance Corp has developed an ML-driven <strong>predictive model </strong>to detect the <strong>likelihood</strong> of fraudulent claims. Consequently, they allocate their most seasoned claim adjusters to address the top <code>5%</code> of <strong>claims</strong> <strong>flagged</strong> by this model.</p>
<p>Write a solution to find the top <code>5</code> <strong>percentile</strong> of claims from <strong>each state</strong>.</p>
<p>Return <em>the result table ordered by </em><code>state</code><em> in <strong>ascending</strong> order, </em><code>fraud_score</code><em> in <strong>descending</strong> order, and </em><code>policy_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 1:</strong></p>
<pre>
<strong>Input:</strong>
Fraud table:
+-----------+------------+-------------+
| policy_id | state | fraud_score |
+-----------+------------+-------------+
| 1 | California | 0.92 |
| 2 | California | 0.68 |
| 3 | California | 0.17 |
| 4 | New York | 0.94 |
| 5 | New York | 0.81 |
| 6 | New York | 0.77 |
| 7 | Texas | 0.98 |
| 8 | Texas | 0.97 |
| 9 | Texas | 0.96 |
| 10 | Florida | 0.97 |
| 11 | Florida | 0.98 |
| 12 | Florida | 0.78 |
| 13 | Florida | 0.88 |
| 14 | Florida | 0.66 |
+-----------+------------+-------------+
<strong>Output:</strong>
+-----------+------------+-------------+
| policy_id | state | fraud_score |
+-----------+------------+-------------+
| 1 | California | 0.92 |
| 11 | Florida | 0.98 |
| 4 | New York | 0.94 |
| 7 | Texas | 0.98 |
+-----------+------------+-------------+
<strong>Explanation</strong>
- For the state of California, only policy ID 1, with a fraud score of 0.92, falls within the top 5 percentile for this state.
- For the state of Florida, only policy ID 11, with a fraud score of 0.98, falls within the top 5 percentile for this state.
- For the state of New York, only policy ID 4, with a fraud score of 0.94, falls within the top 5 percentile for this state.
- For the state of Texas, only policy ID 7, with a fraud score of 0.98, falls within the top 5 percentile for this state.
Output table is ordered by state in ascending order, fraud score in descending order, and policy ID in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY state
ORDER BY fraud_score DESC
) AS rk
FROM Fraud
)
SELECT policy_id, state, fraud_score
FROM T
WHERE rk = 1
ORDER BY 2, 3 DESC, 1;
|
3,056
|
Snaps Analysis
|
Medium
|
<p>Table: <code>Activities</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| activity_id | int |
| user_id | int |
| activity_type | enum |
| time_spent | decimal |
+---------------+---------+
activity_id is column of unique values for this table.
activity_type is an ENUM (category) type of ('send', 'open').
This table contains activity id, user id, activity type and time spent.
</pre>
<p>Table: <code>Age</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| age_bucket | enum |
+-------------+------+
user_id is the column of unique values for this table.
age_bucket is an ENUM (category) type of ('21-25', '26-30', '31-35').
This table contains user id and age group.</pre>
<p>Write a solution to calculate the <strong>percentage</strong> of the total time spent on <strong>sending</strong> and <strong>opening snaps</strong> for <strong>each age group</strong>. Precentage should be <strong>rounded</strong> to <code>2</code> decimal places.</p>
<p>Return <em>the result table </em><em>in <strong>any</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Activities table:
+-------------+---------+---------------+------------+
| activity_id | user_id | activity_type | time_spent |
+-------------+---------+---------------+------------+
| 7274 | 123 | open | 4.50 |
| 2425 | 123 | send | 3.50 |
| 1413 | 456 | send | 5.67 |
| 2536 | 456 | open | 3.00 |
| 8564 | 456 | send | 8.24 |
| 5235 | 789 | send | 6.24 |
| 4251 | 123 | open | 1.25 |
| 1435 | 789 | open | 5.25 |
+-------------+---------+---------------+------------+
Age table:
+---------+------------+
| user_id | age_bucket |
+---------+------------+
| 123 | 31-35 |
| 789 | 21-25 |
| 456 | 26-30 |
+---------+------------+
<strong>Output:</strong>
+------------+-----------+-----------+
| age_bucket | send_perc | open_perc |
+------------+-----------+-----------+
| 31-35 | 37.84 | 62.16 |
| 26-30 | 82.26 | 17.74 |
| 21-25 | 54.31 | 45.69 |
+------------+-----------+-----------+
<strong>Explanation:</strong>
For age group 31-35:
- There is only one user belonging to this group with the user ID 123.
- The total time spent on sending snaps by this user is 3.50, and the time spent on opening snaps is 4.50 + 1.25 = 5.75.
- The overall time spent by this user is 3.50 + 5.75 = 9.25.
- Therefore, the sending snap percentage will be (3.50 / 9.25) * 100 = 37.84, and the opening snap percentage will be (5.75 / 9.25) * 100 = 62.16.
For age group 26-30:
- There is only one user belonging to this group with the user ID 456.
- The total time spent on sending snaps by this user is 5.67 + 8.24 = 13.91, and the time spent on opening snaps is 3.00.
- The overall time spent by this user is 13.91 + 3.00 = 16.91.
- Therefore, the sending snap percentage will be (13.91 / 16.91) * 100 = 82.26, and the opening snap percentage will be (3.00 / 16.91) * 100 = 17.74.
For age group 21-25:
- There is only one user belonging to this group with the user ID 789.
- The total time spent on sending snaps by this user is 6.24, and the time spent on opening snaps is 5.25.
- The overall time spent by this user is 6.24 + 5.25 = 11.49.
- Therefore, the sending snap percentage will be (6.24 / 11.49) * 100 = 54.31, and the opening snap percentage will be (5.25 / 11.49) * 100 = 45.69.
All percentages in output table rounded to the two decimal places.
</pre>
|
Database
|
Python
|
import pandas as pd
def snap_analysis(activities: pd.DataFrame, age: pd.DataFrame) -> pd.DataFrame:
merged_df = pd.merge(activities, age, on="user_id")
total_time_per_age_activity = (
merged_df.groupby(["age_bucket", "activity_type"])["time_spent"]
.sum()
.reset_index()
)
pivot_df = total_time_per_age_activity.pivot(
index="age_bucket", columns="activity_type", values="time_spent"
).reset_index()
pivot_df = pivot_df.fillna(0)
pivot_df["send_perc"] = round(
100 * pivot_df["send"] / (pivot_df["send"] + pivot_df["open"]), 2
)
pivot_df["open_perc"] = round(
100 * pivot_df["open"] / (pivot_df["send"] + pivot_df["open"]), 2
)
return pivot_df[["age_bucket", "send_perc", "open_perc"]]
|
3,056
|
Snaps Analysis
|
Medium
|
<p>Table: <code>Activities</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| activity_id | int |
| user_id | int |
| activity_type | enum |
| time_spent | decimal |
+---------------+---------+
activity_id is column of unique values for this table.
activity_type is an ENUM (category) type of ('send', 'open').
This table contains activity id, user id, activity type and time spent.
</pre>
<p>Table: <code>Age</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| age_bucket | enum |
+-------------+------+
user_id is the column of unique values for this table.
age_bucket is an ENUM (category) type of ('21-25', '26-30', '31-35').
This table contains user id and age group.</pre>
<p>Write a solution to calculate the <strong>percentage</strong> of the total time spent on <strong>sending</strong> and <strong>opening snaps</strong> for <strong>each age group</strong>. Precentage should be <strong>rounded</strong> to <code>2</code> decimal places.</p>
<p>Return <em>the result table </em><em>in <strong>any</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Activities table:
+-------------+---------+---------------+------------+
| activity_id | user_id | activity_type | time_spent |
+-------------+---------+---------------+------------+
| 7274 | 123 | open | 4.50 |
| 2425 | 123 | send | 3.50 |
| 1413 | 456 | send | 5.67 |
| 2536 | 456 | open | 3.00 |
| 8564 | 456 | send | 8.24 |
| 5235 | 789 | send | 6.24 |
| 4251 | 123 | open | 1.25 |
| 1435 | 789 | open | 5.25 |
+-------------+---------+---------------+------------+
Age table:
+---------+------------+
| user_id | age_bucket |
+---------+------------+
| 123 | 31-35 |
| 789 | 21-25 |
| 456 | 26-30 |
+---------+------------+
<strong>Output:</strong>
+------------+-----------+-----------+
| age_bucket | send_perc | open_perc |
+------------+-----------+-----------+
| 31-35 | 37.84 | 62.16 |
| 26-30 | 82.26 | 17.74 |
| 21-25 | 54.31 | 45.69 |
+------------+-----------+-----------+
<strong>Explanation:</strong>
For age group 31-35:
- There is only one user belonging to this group with the user ID 123.
- The total time spent on sending snaps by this user is 3.50, and the time spent on opening snaps is 4.50 + 1.25 = 5.75.
- The overall time spent by this user is 3.50 + 5.75 = 9.25.
- Therefore, the sending snap percentage will be (3.50 / 9.25) * 100 = 37.84, and the opening snap percentage will be (5.75 / 9.25) * 100 = 62.16.
For age group 26-30:
- There is only one user belonging to this group with the user ID 456.
- The total time spent on sending snaps by this user is 5.67 + 8.24 = 13.91, and the time spent on opening snaps is 3.00.
- The overall time spent by this user is 13.91 + 3.00 = 16.91.
- Therefore, the sending snap percentage will be (13.91 / 16.91) * 100 = 82.26, and the opening snap percentage will be (3.00 / 16.91) * 100 = 17.74.
For age group 21-25:
- There is only one user belonging to this group with the user ID 789.
- The total time spent on sending snaps by this user is 6.24, and the time spent on opening snaps is 5.25.
- The overall time spent by this user is 6.24 + 5.25 = 11.49.
- Therefore, the sending snap percentage will be (6.24 / 11.49) * 100 = 54.31, and the opening snap percentage will be (5.25 / 11.49) * 100 = 45.69.
All percentages in output table rounded to the two decimal places.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
age_bucket,
ROUND(100 * SUM(IF(activity_type = 'send', time_spent, 0)) / SUM(time_spent), 2) AS send_perc,
ROUND(100 * SUM(IF(activity_type = 'open', time_spent, 0)) / SUM(time_spent), 2) AS open_perc
FROM
Activities
JOIN Age USING (user_id)
GROUP BY 1;
|
3,057
|
Employees Project Allocation
|
Hard
|
<p>Table: <code>Project</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
| workload | int |
+-------------+---------+
employee_id is the primary key (column with unique values) of this table.
employee_id is a foreign key (reference column) to <code>Employee</code> table.
Each row of this table indicates that the employee with employee_id is working on the project with project_id and the workload of the project.
</pre>
<p>Table: <code>Employees</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| team | varchar |
+------------------+---------+
employee_id is the primary key (column with unique values) of this table.
Each row of this table contains information about one employee.
</pre>
<p>Write a solution to find the <strong>employees</strong> who are allocated to projects with a <strong>workload that exceeds the average</strong> workload of all employees for <strong>their respective teams</strong></p>
<p>Return t<em>he result table ordered by</em> <code>employee_id</code>, <code>project_id</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Project table:
+-------------+-------------+----------+
| project_id | employee_id | workload |
+-------------+-------------+----------+
| 1 | 1 | 45 |
| 1 | 2 | 90 |
| 2 | 3 | 12 |
| 2 | 4 | 68 |
+-------------+-------------+----------+
Employees table:
+-------------+--------+------+
| employee_id | name | team |
+-------------+--------+------+
| 1 | Khaled | A |
| 2 | Ali | B |
| 3 | John | B |
| 4 | Doe | A |
+-------------+--------+------+
<strong>Output:</strong>
+-------------+------------+---------------+------------------+
| employee_id | project_id | employee_name | project_workload |
+-------------+------------+---------------+------------------+
| 2 | 1 | Ali | 90 |
| 4 | 2 | Doe | 68 |
+-------------+------------+---------------+------------------+
<strong>Explanation:</strong>
- Employee with ID 1 has a project workload of 45 and belongs to Team A, where the average workload is 56.50. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 2 has a project workload of 90 and belongs to Team B, where the average workload is 51.00. Since his project workload does exceed the team's average workload, he will be included.
- Employee with ID 3 has a project workload of 12 and belongs to Team B, where the average workload is 51.00. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 4 has a project workload of 68 and belongs to Team A, where the average workload is 56.50. Since his project workload does exceed the team's average workload, he will be included.
Result table orderd by employee_id, project_id in ascending order.
</pre>
|
Database
|
Python
|
import pandas as pd
def employees_with_above_avg_workload(
project: pd.DataFrame, employees: pd.DataFrame
) -> pd.DataFrame:
merged_df = pd.merge(project, employees, on="employee_id")
avg_workload_per_team = merged_df.groupby("team")["workload"].mean().reset_index()
merged_df = pd.merge(
merged_df, avg_workload_per_team, on="team", suffixes=("", "_avg")
)
ans = merged_df[merged_df["workload"] > merged_df["workload_avg"]]
ans = ans[["employee_id", "project_id", "name", "workload"]]
ans = ans.rename(columns={"name": "employee_name", "workload": "project_workload"})
return ans.sort_values(by=["employee_id", "project_id"])
|
3,057
|
Employees Project Allocation
|
Hard
|
<p>Table: <code>Project</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
| workload | int |
+-------------+---------+
employee_id is the primary key (column with unique values) of this table.
employee_id is a foreign key (reference column) to <code>Employee</code> table.
Each row of this table indicates that the employee with employee_id is working on the project with project_id and the workload of the project.
</pre>
<p>Table: <code>Employees</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| team | varchar |
+------------------+---------+
employee_id is the primary key (column with unique values) of this table.
Each row of this table contains information about one employee.
</pre>
<p>Write a solution to find the <strong>employees</strong> who are allocated to projects with a <strong>workload that exceeds the average</strong> workload of all employees for <strong>their respective teams</strong></p>
<p>Return t<em>he result table ordered by</em> <code>employee_id</code>, <code>project_id</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Project table:
+-------------+-------------+----------+
| project_id | employee_id | workload |
+-------------+-------------+----------+
| 1 | 1 | 45 |
| 1 | 2 | 90 |
| 2 | 3 | 12 |
| 2 | 4 | 68 |
+-------------+-------------+----------+
Employees table:
+-------------+--------+------+
| employee_id | name | team |
+-------------+--------+------+
| 1 | Khaled | A |
| 2 | Ali | B |
| 3 | John | B |
| 4 | Doe | A |
+-------------+--------+------+
<strong>Output:</strong>
+-------------+------------+---------------+------------------+
| employee_id | project_id | employee_name | project_workload |
+-------------+------------+---------------+------------------+
| 2 | 1 | Ali | 90 |
| 4 | 2 | Doe | 68 |
+-------------+------------+---------------+------------------+
<strong>Explanation:</strong>
- Employee with ID 1 has a project workload of 45 and belongs to Team A, where the average workload is 56.50. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 2 has a project workload of 90 and belongs to Team B, where the average workload is 51.00. Since his project workload does exceed the team's average workload, he will be included.
- Employee with ID 3 has a project workload of 12 and belongs to Team B, where the average workload is 51.00. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 4 has a project workload of 68 and belongs to Team A, where the average workload is 56.50. Since his project workload does exceed the team's average workload, he will be included.
Result table orderd by employee_id, project_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT team, AVG(workload) AS avg_workload
FROM
Project
JOIN Employees USING (employee_id)
GROUP BY 1
)
SELECT
employee_id,
project_id,
name AS employee_name,
workload AS project_workload
FROM
Project
JOIN Employees USING (employee_id)
JOIN T USING (team)
WHERE workload > avg_workload
ORDER BY 1, 2;
|
3,058
|
Friends With No Mutual Friends
|
Medium
|
<p>Table: <code>Friends</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id1 | int |
| user_id2 | int |
+-------------+------+
(user_id1, user_id2) is the primary key (combination of columns with unique values) for this table.
Each row contains user id1, user id2, both of whom are friends with each other.
</pre>
<p>Write a solution to find <strong>all</strong> <strong>pairs</strong> of users who are friends with each other and have <strong>no mutual</strong> friends.</p>
<p>Return <em>the result table ordered by </em><code>user_id1,</code> <code>user_id2</code><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Friends table:
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 1 | 5 |
| 6 | 7 |
| 3 | 4 |
| 2 | 5 |
| 8 | 9 |
+----------+----------+
<strong>Output:</strong>
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 6 | 7 |
| 8 | 9 |
+----------+----------+
<strong>Explanation:</strong>
- Users 1 and 2 are friends with each other, but they share a mutual friend with user ID 5, so this pair is not included.
- Users 2 and 3 are friends, they both share a mutual friend with user ID 4, resulting in exclusion, similarly for users 2 and 4 who share a mutual friend with user ID 3, hence not included.
- Users 1 and 5 are friends with each other, but they share a mutual friend with user ID 2, so this pair is not included.
- Users 6 and 7, as well as users 8 and 9, are friends with each other, and they don't have any mutual friends, hence included.
- Users 3 and 4 are friends with each other, but their mutual connection with user ID 2 means they are not included, similarly for users 2 and 5 are friends but are excluded due to their mutual connection with user ID 1.
Output table is ordered by user_id1 in ascending order.</pre>
|
Database
|
Python
|
import pandas as pd
def friends_with_no_mutual_friends(friends: pd.DataFrame) -> pd.DataFrame:
cp = friends.copy()
t = cp[["user_id1", "user_id2"]].copy()
t = pd.concat(
[
t,
cp[["user_id2", "user_id1"]].rename(
columns={"user_id2": "user_id1", "user_id1": "user_id2"}
),
]
)
merged = t.merge(t, left_on="user_id2", right_on="user_id2")
ans = cp[
~cp.apply(
lambda x: (x["user_id1"], x["user_id2"])
in zip(merged["user_id1_x"], merged["user_id1_y"]),
axis=1,
)
]
return ans.sort_values(by=["user_id1", "user_id2"])
|
3,058
|
Friends With No Mutual Friends
|
Medium
|
<p>Table: <code>Friends</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id1 | int |
| user_id2 | int |
+-------------+------+
(user_id1, user_id2) is the primary key (combination of columns with unique values) for this table.
Each row contains user id1, user id2, both of whom are friends with each other.
</pre>
<p>Write a solution to find <strong>all</strong> <strong>pairs</strong> of users who are friends with each other and have <strong>no mutual</strong> friends.</p>
<p>Return <em>the result table ordered by </em><code>user_id1,</code> <code>user_id2</code><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Friends table:
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 1 | 5 |
| 6 | 7 |
| 3 | 4 |
| 2 | 5 |
| 8 | 9 |
+----------+----------+
<strong>Output:</strong>
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 6 | 7 |
| 8 | 9 |
+----------+----------+
<strong>Explanation:</strong>
- Users 1 and 2 are friends with each other, but they share a mutual friend with user ID 5, so this pair is not included.
- Users 2 and 3 are friends, they both share a mutual friend with user ID 4, resulting in exclusion, similarly for users 2 and 4 who share a mutual friend with user ID 3, hence not included.
- Users 1 and 5 are friends with each other, but they share a mutual friend with user ID 2, so this pair is not included.
- Users 6 and 7, as well as users 8 and 9, are friends with each other, and they don't have any mutual friends, hence included.
- Users 3 and 4 are friends with each other, but their mutual connection with user ID 2 means they are not included, similarly for users 2 and 5 are friends but are excluded due to their mutual connection with user ID 1.
Output table is ordered by user_id1 in ascending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT user_id1, user_id2 FROM Friends
UNION ALL
SELECT user_id2, user_id1 FROM Friends
)
SELECT user_id1, user_id2
FROM Friends
WHERE
(user_id1, user_id2) NOT IN (
SELECT t1.user_id1, t2.user_id1
FROM
T AS t1
JOIN T AS t2 ON t1.user_id2 = t2.user_id2
)
ORDER BY 1, 2;
|
3,059
|
Find All Unique Email Domains
|
Easy
|
<p>Table: <code>Emails</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
</pre>
<p>Write a solution to find all <strong>unique email domains</strong> and count the number of <strong>individuals</strong> associated with each domain. <strong>Consider only</strong> those domains that <strong>end</strong> with <strong>.com</strong>.</p>
<p>Return <em>the result table orderd by email domains in </em><strong>ascending</strong><em> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Emails table:
+-----+-----------------------+
| id | email |
+-----+-----------------------+
| 336 | hwkiy@test.edu |
| 489 | adcmaf@outlook.com |
| 449 | vrzmwyum@yahoo.com |
| 95 | tof@test.edu |
| 320 | jxhbagkpm@example.org |
| 411 | zxcf@outlook.com |
+----+------------------------+
<strong>Output:</strong>
+--------------+-------+
| email_domain | count |
+--------------+-------+
| outlook.com | 2 |
| yahoo.com | 1 |
+--------------+-------+
<strong>Explanation:</strong>
- The valid domains ending with ".com" are only "outlook.com" and "yahoo.com", with respective counts of 2 and 1.
Output table is ordered by email_domains in ascending order.
</pre>
|
Database
|
Python
|
import pandas as pd
def find_unique_email_domains(emails: pd.DataFrame) -> pd.DataFrame:
emails["email_domain"] = emails["email"].str.split("@").str[-1]
emails = emails[emails["email"].str.contains(".com")]
return (
emails.groupby("email_domain")
.size()
.reset_index(name="count")
.sort_values(by="email_domain")
)
|
3,059
|
Find All Unique Email Domains
|
Easy
|
<p>Table: <code>Emails</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
</pre>
<p>Write a solution to find all <strong>unique email domains</strong> and count the number of <strong>individuals</strong> associated with each domain. <strong>Consider only</strong> those domains that <strong>end</strong> with <strong>.com</strong>.</p>
<p>Return <em>the result table orderd by email domains in </em><strong>ascending</strong><em> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Emails table:
+-----+-----------------------+
| id | email |
+-----+-----------------------+
| 336 | hwkiy@test.edu |
| 489 | adcmaf@outlook.com |
| 449 | vrzmwyum@yahoo.com |
| 95 | tof@test.edu |
| 320 | jxhbagkpm@example.org |
| 411 | zxcf@outlook.com |
+----+------------------------+
<strong>Output:</strong>
+--------------+-------+
| email_domain | count |
+--------------+-------+
| outlook.com | 2 |
| yahoo.com | 1 |
+--------------+-------+
<strong>Explanation:</strong>
- The valid domains ending with ".com" are only "outlook.com" and "yahoo.com", with respective counts of 2 and 1.
Output table is ordered by email_domains in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT SUBSTRING_INDEX(email, '@', -1) AS email_domain, COUNT(1) AS count
FROM Emails
WHERE email LIKE '%.com'
GROUP BY 1
ORDER BY 1;
|
3,060
|
User Activities within Time Bounds
|
Hard
|
<p>Table: <code>Sessions</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| user_id | int |
| session_start | datetime |
| session_end | datetime |
| session_id | int |
| session_type | enum |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.
</pre>
<p>Write a solution to find the the <strong>users</strong> who have had <strong>at least two</strong><strong> session</strong> of the <strong>same</strong> type (either '<strong>Viewer</strong>' or '<strong>Streamer</strong>') with a <strong>maximum</strong> gap of <code>12</code> hours <strong>between</strong> sessions.</p>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <b>ascending</b> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<pre>
<strong>Input:</strong>
Sessions table:
+---------+---------------------+---------------------+------------+--------------+
| user_id | session_start | session_end | session_id | session_type |
+---------+---------------------+---------------------+------------+--------------+
| 101 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 1 | Viewer |
| 101 | 2023-11-01 10:00:00 | 2023-11-01 11:00:00 | 2 | Streamer |
| 102 | 2023-11-01 13:00:00 | 2023-11-01 14:00:00 | 3 | Viewer |
| 102 | 2023-11-01 15:00:00 | 2023-11-01 16:00:00 | 4 | Viewer |
| 101 | 2023-11-02 09:00:00 | 2023-11-02 10:00:00 | 5 | Viewer |
| 102 | 2023-11-02 12:00:00 | 2023-11-02 13:00:00 | 6 | Streamer |
| 101 | 2023-11-02 13:00:00 | 2023-11-02 14:00:00 | 7 | Streamer |
| 102 | 2023-11-02 16:00:00 | 2023-11-02 17:00:00 | 8 | Viewer |
| 103 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 9 | Viewer |
| 103 | 2023-11-02 20:00:00 | 2023-11-02 23:00:00 | 10 | Viewer |
| 103 | 2023-11-03 09:00:00 | 2023-11-03 10:00:00 | 11 | Viewer |
+---------+---------------------+---------------------+------------+--------------+
<strong>Output:</strong>
+---------+
| user_id |
+---------+
| 102 |
| 103 |
+---------+
<strong>Explanation:</strong>
- User ID 101 will not be included in the final output as they do not have any two sessions of the same session type.
- User ID 102 will be included in the final output as they had two viewer sessions with session IDs 3 and 4, respectively, and the time gap between them was less than 12 hours.
- User ID 103 participated in two viewer sessions with a gap of less than 12 hours between them, identified by session IDs 10 and 11. Therefore, user 103 will be included in the final output.
Output table is ordered by user_id in increasing order.
</pre>
|
Database
|
Python
|
import pandas as pd
def user_activities(sessions: pd.DataFrame) -> pd.DataFrame:
sessions = sessions.sort_values(by=["user_id", "session_start"])
sessions["prev_session_end"] = sessions.groupby(["user_id", "session_type"])[
"session_end"
].shift(1)
sessions_filtered = sessions[
sessions["session_start"] - sessions["prev_session_end"]
<= pd.Timedelta(hours=12)
]
return pd.DataFrame({"user_id": sessions_filtered["user_id"].unique()})
|
3,060
|
User Activities within Time Bounds
|
Hard
|
<p>Table: <code>Sessions</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| user_id | int |
| session_start | datetime |
| session_end | datetime |
| session_id | int |
| session_type | enum |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.
</pre>
<p>Write a solution to find the the <strong>users</strong> who have had <strong>at least two</strong><strong> session</strong> of the <strong>same</strong> type (either '<strong>Viewer</strong>' or '<strong>Streamer</strong>') with a <strong>maximum</strong> gap of <code>12</code> hours <strong>between</strong> sessions.</p>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <b>ascending</b> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<pre>
<strong>Input:</strong>
Sessions table:
+---------+---------------------+---------------------+------------+--------------+
| user_id | session_start | session_end | session_id | session_type |
+---------+---------------------+---------------------+------------+--------------+
| 101 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 1 | Viewer |
| 101 | 2023-11-01 10:00:00 | 2023-11-01 11:00:00 | 2 | Streamer |
| 102 | 2023-11-01 13:00:00 | 2023-11-01 14:00:00 | 3 | Viewer |
| 102 | 2023-11-01 15:00:00 | 2023-11-01 16:00:00 | 4 | Viewer |
| 101 | 2023-11-02 09:00:00 | 2023-11-02 10:00:00 | 5 | Viewer |
| 102 | 2023-11-02 12:00:00 | 2023-11-02 13:00:00 | 6 | Streamer |
| 101 | 2023-11-02 13:00:00 | 2023-11-02 14:00:00 | 7 | Streamer |
| 102 | 2023-11-02 16:00:00 | 2023-11-02 17:00:00 | 8 | Viewer |
| 103 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 9 | Viewer |
| 103 | 2023-11-02 20:00:00 | 2023-11-02 23:00:00 | 10 | Viewer |
| 103 | 2023-11-03 09:00:00 | 2023-11-03 10:00:00 | 11 | Viewer |
+---------+---------------------+---------------------+------------+--------------+
<strong>Output:</strong>
+---------+
| user_id |
+---------+
| 102 |
| 103 |
+---------+
<strong>Explanation:</strong>
- User ID 101 will not be included in the final output as they do not have any two sessions of the same session type.
- User ID 102 will be included in the final output as they had two viewer sessions with session IDs 3 and 4, respectively, and the time gap between them was less than 12 hours.
- User ID 103 participated in two viewer sessions with a gap of less than 12 hours between them, identified by session IDs 10 and 11. Therefore, user 103 will be included in the final output.
Output table is ordered by user_id in increasing order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
user_id,
session_start,
LAG(session_end) OVER (
PARTITION BY user_id, session_type
ORDER BY session_end
) AS prev_session_end
FROM Sessions
)
SELECT DISTINCT
user_id
FROM T
WHERE TIMESTAMPDIFF(HOUR, prev_session_end, session_start) <= 12;
|
3,061
|
Calculate Trapping Rain Water
|
Hard
|
<p>Table: <font face="monospace">Heights</font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| height | int |
+-------------+------+
id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
Each row of this table contains an id and height.
</pre>
<p>Write a solution to calculate the amount of rainwater can be <strong>trapped between the bars</strong> in the landscape, considering that each bar has a <strong>width</strong> of <code>1</code> unit.</p>
<p>Return <em>the result table in </em><strong>any</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Heights table:
+-----+--------+
| id | height |
+-----+--------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| 9 | 2 |
| 10 | 1 |
| 11 | 2 |
| 12 | 1 |
+-----+--------+
<strong>Output:</strong>
+---------------------+
| total_trapped_water |
+---------------------+
| 6 |
+---------------------+
<strong>Explanation:</strong>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3061.Calculate%20Trapping%20Rain%20Water/images/trapping_rain_water.png" style="width:500px; height:200px;" />
The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
</pre>
|
Database
|
Python
|
import pandas as pd
def calculate_trapped_rain_water(heights: pd.DataFrame) -> pd.DataFrame:
heights["l"] = heights["height"].cummax()
heights["r"] = heights["height"][::-1].cummax()[::-1]
heights["trapped_water"] = heights[["l", "r"]].min(axis=1) - heights["height"]
return pd.DataFrame({"total_trapped_water": [heights["trapped_water"].sum()]})
|
3,061
|
Calculate Trapping Rain Water
|
Hard
|
<p>Table: <font face="monospace">Heights</font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| height | int |
+-------------+------+
id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
Each row of this table contains an id and height.
</pre>
<p>Write a solution to calculate the amount of rainwater can be <strong>trapped between the bars</strong> in the landscape, considering that each bar has a <strong>width</strong> of <code>1</code> unit.</p>
<p>Return <em>the result table in </em><strong>any</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Heights table:
+-----+--------+
| id | height |
+-----+--------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| 9 | 2 |
| 10 | 1 |
| 11 | 2 |
| 12 | 1 |
+-----+--------+
<strong>Output:</strong>
+---------------------+
| total_trapped_water |
+---------------------+
| 6 |
+---------------------+
<strong>Explanation:</strong>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3061.Calculate%20Trapping%20Rain%20Water/images/trapping_rain_water.png" style="width:500px; height:200px;" />
The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
MAX(height) OVER (ORDER BY id) AS l,
MAX(height) OVER (ORDER BY id DESC) AS r
FROM Heights
)
SELECT SUM(LEAST(l, r) - height) AS total_trapped_water
FROM T;
|
3,062
|
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
string gameResult(ListNode* head) {
int odd = 0, even = 0;
for (; head != nullptr; head = head->next->next) {
int a = head->val;
int b = head->next->val;
odd += a < b;
even += a > b;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
};
|
3,062
|
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func gameResult(head *ListNode) string {
var odd, even int
for ; head != nil; head = head.Next.Next {
a, b := head.Val, head.Next.Val
if a < b {
odd++
}
if a > b {
even++
}
}
if odd > even {
return "Odd"
}
if odd < even {
return "Even"
}
return "Tie"
}
|
3,062
|
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Java
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public String gameResult(ListNode head) {
int odd = 0, even = 0;
for (; head != null; head = head.next.next) {
int a = head.val;
int b = head.next.val;
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
}
|
3,062
|
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def gameResult(self, head: Optional[ListNode]) -> str:
odd = even = 0
while head:
a = head.val
b = head.next.val
odd += a < b
even += a > b
head = head.next.next
if odd > even:
return "Odd"
if odd < even:
return "Even"
return "Tie"
|
3,062
|
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
TypeScript
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function gameResult(head: ListNode | null): string {
let [odd, even] = [0, 0];
for (; head; head = head.next.next) {
const [a, b] = [head.val, head.next.val];
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return 'Odd';
}
if (odd < even) {
return 'Even';
}
return 'Tie';
}
|
3,063
|
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* frequenciesOfElements(ListNode* head) {
unordered_map<int, int> cnt;
for (; head; head = head->next) {
cnt[head->val]++;
}
ListNode* dummy = new ListNode();
for (auto& [_, val] : cnt) {
dummy->next = new ListNode(val, dummy->next);
}
return dummy->next;
}
};
|
3,063
|
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func frequenciesOfElements(head *ListNode) *ListNode {
cnt := map[int]int{}
for ; head != nil; head = head.Next {
cnt[head.Val]++
}
dummy := &ListNode{}
for _, val := range cnt {
dummy.Next = &ListNode{val, dummy.Next}
}
return dummy.Next
}
|
3,063
|
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Java
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode frequenciesOfElements(ListNode head) {
Map<Integer, Integer> cnt = new HashMap<>();
for (; head != null; head = head.next) {
cnt.merge(head.val, 1, Integer::sum);
}
ListNode dummy = new ListNode();
for (int val : cnt.values()) {
dummy.next = new ListNode(val, dummy.next);
}
return dummy.next;
}
}
|
3,063
|
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]:
cnt = Counter()
while head:
cnt[head.val] += 1
head = head.next
dummy = ListNode()
for val in cnt.values():
dummy.next = ListNode(val, dummy.next)
return dummy.next
|
3,063
|
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
TypeScript
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function frequenciesOfElements(head: ListNode | null): ListNode | null {
const cnt: Map<number, number> = new Map();
for (; head; head = head.next) {
cnt.set(head.val, (cnt.get(head.val) || 0) + 1);
}
const dummy = new ListNode();
for (const val of cnt.values()) {
dummy.next = new ListNode(val, dummy.next);
}
return dummy.next;
}
|
3,064
|
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
C++
|
/**
* Definition of commonSetBits API.
* int commonSetBits(int num);
*/
class Solution {
public:
int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
if (commonSetBits(1 << i)) {
n |= 1 << i;
}
}
return n;
}
};
|
3,064
|
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Go
|
/**
* Definition of commonSetBits API.
* func commonSetBits(num int) int;
*/
func findNumber() (n int) {
for i := 0; i < 32; i++ {
if commonSetBits(1<<i) > 0 {
n |= 1 << i
}
}
return
}
|
3,064
|
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Java
|
/**
* Definition of commonSetBits API (defined in the parent class Problem).
* int commonSetBits(int num);
*/
public class Solution extends Problem {
public int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
if (commonSetBits(1 << i) > 0) {
n |= 1 << i;
}
}
return n;
}
}
|
3,064
|
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Python
|
# Definition of commonSetBits API.
# def commonSetBits(num: int) -> int:
class Solution:
def findNumber(self) -> int:
return sum(1 << i for i in range(32) if commonSetBits(1 << i))
|
3,064
|
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
TypeScript
|
/**
* Definition of commonSetBits API.
* var commonSetBits = function(num: number): number {}
*/
function findNumber(): number {
let n = 0;
for (let i = 0; i < 32; ++i) {
if (commonSetBits(1 << i)) {
n |= 1 << i;
}
}
return n;
}
|
3,065
|
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
int ans = 0;
for (int x : nums) {
if (x < k) {
++ans;
}
}
return ans;
}
};
|
3,065
|
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Go
|
func minOperations(nums []int, k int) (ans int) {
for _, x := range nums {
if x < k {
ans++
}
}
return
}
|
3,065
|
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
int ans = 0;
for (int x : nums) {
if (x < k) {
++ans;
}
}
return ans;
}
}
|
3,065
|
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(x < k for x in nums)
|
3,065
|
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
return nums.filter(x => x < k).length;
}
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
using ll = long long;
priority_queue<ll, vector<ll>, greater<ll>> pq;
for (int x : nums) {
pq.push(x);
}
int ans = 0;
for (; pq.size() > 1 && pq.top() < k; ++ans) {
ll x = pq.top();
pq.pop();
ll y = pq.top();
pq.pop();
pq.push(x * 2 + y);
}
return ans;
}
};
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Go
|
func minOperations(nums []int, k int) (ans int) {
pq := &hp{nums}
heap.Init(pq)
for ; pq.Len() > 1 && pq.IntSlice[0] < k; ans++ {
x, y := heap.Pop(pq).(int), heap.Pop(pq).(int)
heap.Push(pq, x*2+y)
}
return
}
type hp struct{ sort.IntSlice }
func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Pop() interface{} {
old := h.IntSlice
n := len(old)
x := old[n-1]
h.IntSlice = old[0 : n-1]
return x
}
func (h *hp) Push(x interface{}) {
h.IntSlice = append(h.IntSlice, x.(int))
}
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
PriorityQueue<Long> pq = new PriorityQueue<>();
for (int x : nums) {
pq.offer((long) x);
}
int ans = 0;
for (; pq.size() > 1 && pq.peek() < k; ++ans) {
long x = pq.poll(), y = pq.poll();
pq.offer(x * 2 + y);
}
return ans;
}
}
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
heapify(nums)
ans = 0
while len(nums) > 1 and nums[0] < k:
x, y = heappop(nums), heappop(nums)
heappush(nums, x * 2 + y)
ans += 1
return ans
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Rust
|
use std::collections::BinaryHeap;
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
let mut pq = BinaryHeap::new();
for &x in &nums {
pq.push(-(x as i64));
}
let mut ans = 0;
while pq.len() > 1 && -pq.peek().unwrap() < k as i64 {
let x = -pq.pop().unwrap();
let y = -pq.pop().unwrap();
pq.push(-(x * 2 + y));
ans += 1;
}
ans
}
}
|
3,066
|
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</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 = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 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>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
const pq = new MinPriorityQueue();
for (const x of nums) {
pq.enqueue(x);
}
let ans = 0;
for (; pq.size() > 1 && pq.front().element < k; ++ans) {
const x = pq.dequeue().element;
const y = pq.dequeue().element;
pq.enqueue(x * 2 + y);
}
return ans;
}
|
3,067
|
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
C++
|
class Solution {
public:
vector<int> countPairsOfConnectableServers(vector<vector<int>>& edges, int signalSpeed) {
int n = edges.size() + 1;
vector<pair<int, int>> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1], w = e[2];
g[a].emplace_back(b, w);
g[b].emplace_back(a, w);
}
function<int(int, int, int)> dfs = [&](int a, int fa, int ws) {
int cnt = ws % signalSpeed == 0;
for (auto& [b, w] : g[a]) {
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
};
vector<int> ans(n);
for (int a = 0; a < n; ++a) {
int s = 0;
for (auto& [b, w] : g[a]) {
int t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
};
|
3,067
|
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Go
|
func countPairsOfConnectableServers(edges [][]int, signalSpeed int) []int {
n := len(edges) + 1
type pair struct{ x, w int }
g := make([][]pair, n)
for _, e := range edges {
a, b, w := e[0], e[1], e[2]
g[a] = append(g[a], pair{b, w})
g[b] = append(g[b], pair{a, w})
}
var dfs func(a, fa, ws int) int
dfs = func(a, fa, ws int) int {
cnt := 0
if ws%signalSpeed == 0 {
cnt++
}
for _, e := range g[a] {
b, w := e.x, e.w
if b != fa {
cnt += dfs(b, a, ws+w)
}
}
return cnt
}
ans := make([]int, n)
for a := 0; a < n; a++ {
s := 0
for _, e := range g[a] {
b, w := e.x, e.w
t := dfs(b, a, w)
ans[a] += s * t
s += t
}
}
return ans
}
|
3,067
|
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Java
|
class Solution {
private int signalSpeed;
private List<int[]>[] g;
public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {
int n = edges.length + 1;
g = new List[n];
this.signalSpeed = signalSpeed;
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1], w = e[2];
g[a].add(new int[] {b, w});
g[b].add(new int[] {a, w});
}
int[] ans = new int[n];
for (int a = 0; a < n; ++a) {
int s = 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
int t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
private int dfs(int a, int fa, int ws) {
int cnt = ws % signalSpeed == 0 ? 1 : 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
}
}
|
3,067
|
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Python
|
class Solution:
def countPairsOfConnectableServers(
self, edges: List[List[int]], signalSpeed: int
) -> List[int]:
def dfs(a: int, fa: int, ws: int) -> int:
cnt = 0 if ws % signalSpeed else 1
for b, w in g[a]:
if b != fa:
cnt += dfs(b, a, ws + w)
return cnt
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b, w in edges:
g[a].append((b, w))
g[b].append((a, w))
ans = [0] * n
for a in range(n):
s = 0
for b, w in g[a]:
t = dfs(b, a, w)
ans[a] += s * t
s += t
return ans
|
3,067
|
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
TypeScript
|
function countPairsOfConnectableServers(edges: number[][], signalSpeed: number): number[] {
const n = edges.length + 1;
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (const [a, b, w] of edges) {
g[a].push([b, w]);
g[b].push([a, w]);
}
const dfs = (a: number, fa: number, ws: number): number => {
let cnt = ws % signalSpeed === 0 ? 1 : 0;
for (const [b, w] of g[a]) {
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
};
const ans: number[] = Array(n).fill(0);
for (let a = 0; a < n; ++a) {
let s = 0;
for (const [b, w] of g[a]) {
const t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
C++
|
class Solution {
public:
long long maximumValueSum(vector<int>& nums, int k, vector<vector<int>>& edges) {
long long f0 = 0, f1 = -0x3f3f3f3f;
for (int x : nums) {
long long tmp = f0;
f0 = max(f0 + x, f1 + (x ^ k));
f1 = max(f1 + x, tmp + (x ^ k));
}
return f0;
}
};
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
C#
|
public class Solution {
public long MaximumValueSum(int[] nums, int k, int[][] edges) {
long f0 = 0, f1 = -0x3f3f3f3f;
foreach (int x in nums) {
long tmp = f0;
f0 = Math.Max(f0 + x, f1 + (x ^ k));
f1 = Math.Max(f1 + x, tmp + (x ^ k));
}
return f0;
}
}
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Go
|
func maximumValueSum(nums []int, k int, edges [][]int) int64 {
f0, f1 := 0, -0x3f3f3f3f
for _, x := range nums {
f0, f1 = max(f0+x, f1+(x^k)), max(f1+x, f0+(x^k))
}
return int64(f0)
}
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Java
|
class Solution {
public long maximumValueSum(int[] nums, int k, int[][] edges) {
long f0 = 0, f1 = -0x3f3f3f3f;
for (int x : nums) {
long tmp = f0;
f0 = Math.max(f0 + x, f1 + (x ^ k));
f1 = Math.max(f1 + x, tmp + (x ^ k));
}
return f0;
}
}
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Python
|
class Solution:
def maximumValueSum(self, nums: List[int], k: int, edges: List[List[int]]) -> int:
f0, f1 = 0, -inf
for x in nums:
f0, f1 = max(f0 + x, f1 + (x ^ k)), max(f1 + x, f0 + (x ^ k))
return f0
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Rust
|
impl Solution {
pub fn maximum_value_sum(nums: Vec<i32>, k: i32, edges: Vec<Vec<i32>>) -> i64 {
let mut f0: i64 = 0;
let mut f1: i64 = i64::MIN;
for &x in &nums {
let tmp = f0;
f0 = std::cmp::max(f0 + x as i64, f1 + (x ^ k) as i64);
f1 = std::cmp::max(f1 + x as i64, tmp + (x ^ k) as i64);
}
f0
}
}
|
3,068
|
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
TypeScript
|
function maximumValueSum(nums: number[], k: number, edges: number[][]): number {
let [f0, f1] = [0, -Infinity];
for (const x of nums) {
[f0, f1] = [Math.max(f0 + x, f1 + (x ^ k)), Math.max(f1 + x, f0 + (x ^ k))];
}
return f0;
}
|
3,069
|
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
vector<int> resultArray(vector<int>& nums) {
int n = nums.size();
vector<int> arr1 = {nums[0]};
vector<int> arr2 = {nums[1]};
for (int k = 2; k < n; ++k) {
if (arr1.back() > arr2.back()) {
arr1.push_back(nums[k]);
} else {
arr2.push_back(nums[k]);
}
}
arr1.insert(arr1.end(), arr2.begin(), arr2.end());
return arr1;
}
};
|
3,069
|
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Go
|
func resultArray(nums []int) []int {
arr1 := []int{nums[0]}
arr2 := []int{nums[1]}
for _, x := range nums[2:] {
if arr1[len(arr1)-1] > arr2[len(arr2)-1] {
arr1 = append(arr1, x)
} else {
arr2 = append(arr2, x)
}
}
return append(arr1, arr2...)
}
|
3,069
|
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int[] resultArray(int[] nums) {
int n = nums.length;
int[] arr1 = new int[n];
int[] arr2 = new int[n];
arr1[0] = nums[0];
arr2[0] = nums[1];
int i = 0, j = 0;
for (int k = 2; k < n; ++k) {
if (arr1[i] > arr2[j]) {
arr1[++i] = nums[k];
} else {
arr2[++j] = nums[k];
}
}
for (int k = 0; k <= j; ++k) {
arr1[++i] = arr2[k];
}
return arr1;
}
}
|
3,069
|
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def resultArray(self, nums: List[int]) -> List[int]:
arr1 = [nums[0]]
arr2 = [nums[1]]
for x in nums[2:]:
if arr1[-1] > arr2[-1]:
arr1.append(x)
else:
arr2.append(x)
return arr1 + arr2
|
3,069
|
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
TypeScript
|
function resultArray(nums: number[]): number[] {
const arr1: number[] = [nums[0]];
const arr2: number[] = [nums[1]];
for (const x of nums.slice(2)) {
if (arr1.at(-1)! > arr2.at(-1)!) {
arr1.push(x);
} else {
arr2.push(x);
}
}
return arr1.concat(arr2);
}
|
3,070
|
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
C++
|
class Solution {
public:
int countSubmatrices(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
int s[m + 1][n + 1];
memset(s, 0, sizeof(s));
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1];
if (s[i][j] <= k) {
++ans;
}
}
}
return ans;
}
};
|
3,070
|
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Go
|
func countSubmatrices(grid [][]int, k int) (ans int) {
s := make([][]int, len(grid)+1)
for i := range s {
s[i] = make([]int, len(grid[0])+1)
}
for i, row := range grid {
for j, x := range row {
s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + x
if s[i+1][j+1] <= k {
ans++
}
}
}
return
}
|
3,070
|
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Java
|
class Solution {
public int countSubmatrices(int[][] grid, int k) {
int m = grid.length, n = grid[0].length;
int[][] s = new int[m + 1][n + 1];
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1];
if (s[i][j] <= k) {
++ans;
}
}
}
return ans;
}
}
|
3,070
|
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Python
|
class Solution:
def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
s = [[0] * (len(grid[0]) + 1) for _ in range(len(grid) + 1)]
ans = 0
for i, row in enumerate(grid, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
ans += s[i][j] <= k
return ans
|
3,070
|
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
TypeScript
|
function countSubmatrices(grid: number[][], k: number): number {
const m = grid.length;
const n = grid[0].length;
const s: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
let ans: number = 0;
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1];
if (s[i][j] <= k) {
++ans;
}
}
}
return ans;
}
|
3,071
|
Minimum Operations to Write the Letter Y on a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p>
<ul>
<li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li>
<li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li>
<li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li>
</ul>
<p>The Letter <strong>Y</strong> is written on the grid if and only if:</p>
<ul>
<li>All values at cells belonging to the Y are equal.</li>
<li>All values at cells not belonging to the Y are equal.</li>
<li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 49 </code></li>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>0 <= grid[i][j] <= 2</code></li>
<li><code>n</code> is odd.</li>
</ul>
|
Array; Hash Table; Counting; Matrix
|
C++
|
class Solution {
public:
int minimumOperationsToWriteY(vector<vector<int>>& grid) {
int n = grid.size();
int cnt1[3]{};
int cnt2[3]{};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
bool a = i == j && i <= n / 2;
bool b = i + j == n - 1 && i <= n / 2;
bool c = j == n / 2 && i >= n / 2;
if (a || b || c) {
++cnt1[grid[i][j]];
} else {
++cnt2[grid[i][j]];
}
}
}
int ans = n * n;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (i != j) {
ans = min(ans, n * n - cnt1[i] - cnt2[j]);
}
}
}
return ans;
}
};
|
3,071
|
Minimum Operations to Write the Letter Y on a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p>
<ul>
<li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li>
<li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li>
<li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li>
</ul>
<p>The Letter <strong>Y</strong> is written on the grid if and only if:</p>
<ul>
<li>All values at cells belonging to the Y are equal.</li>
<li>All values at cells not belonging to the Y are equal.</li>
<li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 49 </code></li>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>0 <= grid[i][j] <= 2</code></li>
<li><code>n</code> is odd.</li>
</ul>
|
Array; Hash Table; Counting; Matrix
|
Go
|
func minimumOperationsToWriteY(grid [][]int) int {
n := len(grid)
cnt1 := [3]int{}
cnt2 := [3]int{}
for i, row := range grid {
for j, x := range row {
a := i == j && i <= n/2
b := i+j == n-1 && i <= n/2
c := j == n/2 && i >= n/2
if a || b || c {
cnt1[x]++
} else {
cnt2[x]++
}
}
}
ans := n * n
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i != j {
ans = min(ans, n*n-cnt1[i]-cnt2[j])
}
}
}
return ans
}
|
3,071
|
Minimum Operations to Write the Letter Y on a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p>
<ul>
<li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li>
<li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li>
<li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li>
</ul>
<p>The Letter <strong>Y</strong> is written on the grid if and only if:</p>
<ul>
<li>All values at cells belonging to the Y are equal.</li>
<li>All values at cells not belonging to the Y are equal.</li>
<li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 49 </code></li>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>0 <= grid[i][j] <= 2</code></li>
<li><code>n</code> is odd.</li>
</ul>
|
Array; Hash Table; Counting; Matrix
|
Java
|
class Solution {
public int minimumOperationsToWriteY(int[][] grid) {
int n = grid.length;
int[] cnt1 = new int[3];
int[] cnt2 = new int[3];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
boolean a = i == j && i <= n / 2;
boolean b = i + j == n - 1 && i <= n / 2;
boolean c = j == n / 2 && i >= n / 2;
if (a || b || c) {
++cnt1[grid[i][j]];
} else {
++cnt2[grid[i][j]];
}
}
}
int ans = n * n;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (i != j) {
ans = Math.min(ans, n * n - cnt1[i] - cnt2[j]);
}
}
}
return ans;
}
}
|
3,071
|
Minimum Operations to Write the Letter Y on a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p>
<ul>
<li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li>
<li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li>
<li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li>
</ul>
<p>The Letter <strong>Y</strong> is written on the grid if and only if:</p>
<ul>
<li>All values at cells belonging to the Y are equal.</li>
<li>All values at cells not belonging to the Y are equal.</li>
<li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 49 </code></li>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>0 <= grid[i][j] <= 2</code></li>
<li><code>n</code> is odd.</li>
</ul>
|
Array; Hash Table; Counting; Matrix
|
Python
|
class Solution:
def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int:
n = len(grid)
cnt1 = Counter()
cnt2 = Counter()
for i, row in enumerate(grid):
for j, x in enumerate(row):
a = i == j and i <= n // 2
b = i + j == n - 1 and i <= n // 2
c = j == n // 2 and i >= n // 2
if a or b or c:
cnt1[x] += 1
else:
cnt2[x] += 1
return min(
n * n - cnt1[i] - cnt2[j] for i in range(3) for j in range(3) if i != j
)
|
3,071
|
Minimum Operations to Write the Letter Y on a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p>
<ul>
<li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li>
<li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li>
<li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li>
</ul>
<p>The Letter <strong>Y</strong> is written on the grid if and only if:</p>
<ul>
<li>All values at cells belonging to the Y are equal.</li>
<li>All values at cells not belonging to the Y are equal.</li>
<li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" />
<pre>
<strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 49 </code></li>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>0 <= grid[i][j] <= 2</code></li>
<li><code>n</code> is odd.</li>
</ul>
|
Array; Hash Table; Counting; Matrix
|
TypeScript
|
function minimumOperationsToWriteY(grid: number[][]): number {
const n = grid.length;
const cnt1: number[] = Array(3).fill(0);
const cnt2: number[] = Array(3).fill(0);
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
const a = i === j && i <= n >> 1;
const b = i + j === n - 1 && i <= n >> 1;
const c = j === n >> 1 && i >= n >> 1;
if (a || b || c) {
++cnt1[grid[i][j]];
} else {
++cnt2[grid[i][j]];
}
}
}
let ans = n * n;
for (let i = 0; i < 3; ++i) {
for (let j = 0; j < 3; ++j) {
if (i !== j) {
ans = Math.min(ans, n * n - cnt1[i] - cnt2[j]);
}
}
}
return ans;
}
|
3,072
|
Distribute Elements Into Two Arrays II
|
Hard
|
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p>
<p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If <code>greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li>
<li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the integer array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3]
<strong>Output:</strong> [2,3,1,3]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Hence, the array result formed by concatenation is [2,3,1,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,14,3,1,2]
<strong>Output:</strong> [5,3,1,2,14]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.
In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.
After 5 operations, arr1 = [5,3,1,2] and arr2 = [14].
Hence, the array result formed by concatenation is [5,3,1,2,14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3]
<strong>Output:</strong> [3,3,3,3]
<strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].
Hence, the array result formed by concatenation is [3,3,3,3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Simulation
|
C++
|
class BinaryIndexedTree {
private:
int n;
vector<int> c;
public:
BinaryIndexedTree(int n)
: n(n)
, c(n + 1) {}
void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
int query(int x) {
int s = 0;
for (; x > 0; x -= x & -x) {
s += c[x];
}
return s;
}
};
class Solution {
public:
vector<int> resultArray(vector<int>& nums) {
vector<int> st = nums;
sort(st.begin(), st.end());
int n = st.size();
BinaryIndexedTree tree1(n + 1);
BinaryIndexedTree tree2(n + 1);
tree1.update(distance(st.begin(), lower_bound(st.begin(), st.end(), nums[0])) + 1, 1);
tree2.update(distance(st.begin(), lower_bound(st.begin(), st.end(), nums[1])) + 1, 1);
vector<int> arr1 = {nums[0]};
vector<int> arr2 = {nums[1]};
for (int k = 2; k < n; ++k) {
int x = distance(st.begin(), lower_bound(st.begin(), st.end(), nums[k])) + 1;
int a = arr1.size() - tree1.query(x);
int b = arr2.size() - tree2.query(x);
if (a > b) {
arr1.push_back(nums[k]);
tree1.update(x, 1);
} else if (a < b) {
arr2.push_back(nums[k]);
tree2.update(x, 1);
} else if (arr1.size() <= arr2.size()) {
arr1.push_back(nums[k]);
tree1.update(x, 1);
} else {
arr2.push_back(nums[k]);
tree2.update(x, 1);
}
}
arr1.insert(arr1.end(), arr2.begin(), arr2.end());
return arr1;
}
};
|
3,072
|
Distribute Elements Into Two Arrays II
|
Hard
|
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p>
<p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If <code>greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li>
<li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the integer array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3]
<strong>Output:</strong> [2,3,1,3]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Hence, the array result formed by concatenation is [2,3,1,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,14,3,1,2]
<strong>Output:</strong> [5,3,1,2,14]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.
In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.
After 5 operations, arr1 = [5,3,1,2] and arr2 = [14].
Hence, the array result formed by concatenation is [5,3,1,2,14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3]
<strong>Output:</strong> [3,3,3,3]
<strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].
Hence, the array result formed by concatenation is [3,3,3,3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Simulation
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) *BinaryIndexedTree {
return &BinaryIndexedTree{n: n, c: make([]int, n+1)}
}
func (bit *BinaryIndexedTree) update(x, delta int) {
for ; x <= bit.n; x += x & -x {
bit.c[x] += delta
}
}
func (bit *BinaryIndexedTree) query(x int) int {
s := 0
for ; x > 0; x -= x & -x {
s += bit.c[x]
}
return s
}
func resultArray(nums []int) []int {
st := make([]int, len(nums))
copy(st, nums)
sort.Ints(st)
n := len(st)
tree1 := NewBinaryIndexedTree(n + 1)
tree2 := NewBinaryIndexedTree(n + 1)
tree1.update(sort.SearchInts(st, nums[0])+1, 1)
tree2.update(sort.SearchInts(st, nums[1])+1, 1)
arr1 := []int{nums[0]}
arr2 := []int{nums[1]}
for _, x := range nums[2:] {
i := sort.SearchInts(st, x) + 1
a := len(arr1) - tree1.query(i)
b := len(arr2) - tree2.query(i)
if a > b {
arr1 = append(arr1, x)
tree1.update(i, 1)
} else if a < b {
arr2 = append(arr2, x)
tree2.update(i, 1)
} else if len(arr1) <= len(arr2) {
arr1 = append(arr1, x)
tree1.update(i, 1)
} else {
arr2 = append(arr2, x)
tree2.update(i, 1)
}
}
arr1 = append(arr1, arr2...)
return arr1
}
|
3,072
|
Distribute Elements Into Two Arrays II
|
Hard
|
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p>
<p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If <code>greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li>
<li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the integer array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3]
<strong>Output:</strong> [2,3,1,3]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Hence, the array result formed by concatenation is [2,3,1,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,14,3,1,2]
<strong>Output:</strong> [5,3,1,2,14]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.
In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.
After 5 operations, arr1 = [5,3,1,2] and arr2 = [14].
Hence, the array result formed by concatenation is [5,3,1,2,14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3]
<strong>Output:</strong> [3,3,3,3]
<strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].
Hence, the array result formed by concatenation is [3,3,3,3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Simulation
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
public int query(int x) {
int s = 0;
for (; x > 0; x -= x & -x) {
s += c[x];
}
return s;
}
}
class Solution {
public int[] resultArray(int[] nums) {
int[] st = nums.clone();
Arrays.sort(st);
int n = st.length;
BinaryIndexedTree tree1 = new BinaryIndexedTree(n + 1);
BinaryIndexedTree tree2 = new BinaryIndexedTree(n + 1);
tree1.update(Arrays.binarySearch(st, nums[0]) + 1, 1);
tree2.update(Arrays.binarySearch(st, nums[1]) + 1, 1);
int[] arr1 = new int[n];
int[] arr2 = new int[n];
arr1[0] = nums[0];
arr2[0] = nums[1];
int i = 1, j = 1;
for (int k = 2; k < n; ++k) {
int x = Arrays.binarySearch(st, nums[k]) + 1;
int a = i - tree1.query(x);
int b = j - tree2.query(x);
if (a > b) {
arr1[i++] = nums[k];
tree1.update(x, 1);
} else if (a < b) {
arr2[j++] = nums[k];
tree2.update(x, 1);
} else if (i <= j) {
arr1[i++] = nums[k];
tree1.update(x, 1);
} else {
arr2[j++] = nums[k];
tree2.update(x, 1);
}
}
for (int k = 0; k < j; ++k) {
arr1[i++] = arr2[k];
}
return arr1;
}
}
|
3,072
|
Distribute Elements Into Two Arrays II
|
Hard
|
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p>
<p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If <code>greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li>
<li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the integer array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3]
<strong>Output:</strong> [2,3,1,3]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Hence, the array result formed by concatenation is [2,3,1,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,14,3,1,2]
<strong>Output:</strong> [5,3,1,2,14]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.
In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.
After 5 operations, arr1 = [5,3,1,2] and arr2 = [14].
Hence, the array result formed by concatenation is [5,3,1,2,14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3]
<strong>Output:</strong> [3,3,3,3]
<strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].
Hence, the array result formed by concatenation is [3,3,3,3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Simulation
|
Python
|
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def resultArray(self, nums: List[int]) -> List[int]:
st = sorted(set(nums))
m = len(st)
tree1 = BinaryIndexedTree(m + 1)
tree2 = BinaryIndexedTree(m + 1)
tree1.update(bisect_left(st, nums[0]) + 1, 1)
tree2.update(bisect_left(st, nums[1]) + 1, 1)
arr1 = [nums[0]]
arr2 = [nums[1]]
for x in nums[2:]:
i = bisect_left(st, x) + 1
a = len(arr1) - tree1.query(i)
b = len(arr2) - tree2.query(i)
if a > b:
arr1.append(x)
tree1.update(i, 1)
elif a < b:
arr2.append(x)
tree2.update(i, 1)
elif len(arr1) <= len(arr2):
arr1.append(x)
tree1.update(i, 1)
else:
arr2.append(x)
tree2.update(i, 1)
return arr1 + arr2
|
3,072
|
Distribute Elements Into Two Arrays II
|
Hard
|
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p>
<p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If <code>greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li>
<li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li>
<li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the integer array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3]
<strong>Output:</strong> [2,3,1,3]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.
After 4 operations, arr1 = [2,3] and arr2 = [1,3].
Hence, the array result formed by concatenation is [2,3,1,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,14,3,1,2]
<strong>Output:</strong> [5,3,1,2,14]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14].
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.
In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.
After 5 operations, arr1 = [5,3,1,2] and arr2 = [14].
Hence, the array result formed by concatenation is [5,3,1,2,14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3]
<strong>Output:</strong> [3,3,3,3]
<strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].
Hence, the array result formed by concatenation is [3,3,3,3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Simulation
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, delta: number): void {
for (; x <= this.n; x += x & -x) {
this.c[x] += delta;
}
}
query(x: number): number {
let s = 0;
for (; x > 0; x -= x & -x) {
s += this.c[x];
}
return s;
}
}
function resultArray(nums: number[]): number[] {
const st: number[] = nums.slice().sort((a, b) => a - b);
const n: number = st.length;
const search = (x: number): number => {
let [l, r] = [0, n];
while (l < r) {
const mid = (l + r) >> 1;
if (st[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const tree1: BinaryIndexedTree = new BinaryIndexedTree(n + 1);
const tree2: BinaryIndexedTree = new BinaryIndexedTree(n + 1);
tree1.update(search(nums[0]) + 1, 1);
tree2.update(search(nums[1]) + 1, 1);
const arr1: number[] = [nums[0]];
const arr2: number[] = [nums[1]];
for (const x of nums.slice(2)) {
const i: number = search(x) + 1;
const a: number = arr1.length - tree1.query(i);
const b: number = arr2.length - tree2.query(i);
if (a > b) {
arr1.push(x);
tree1.update(i, 1);
} else if (a < b) {
arr2.push(x);
tree2.update(i, 1);
} else if (arr1.length <= arr2.length) {
arr1.push(x);
tree1.update(i, 1);
} else {
arr2.push(x);
tree2.update(i, 1);
}
}
return arr1.concat(arr2);
}
|
3,073
|
Maximum Increasing Triplet Value
|
Medium
|
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i < j < k</code> <em>and</em> <code>nums[i] < nums[j] < nums[k]</code>.</p>
<p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p>
<div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p>
<p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p>
<p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation: </strong> There are only two increasing triplets:</p>
<p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p>
<p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p>
<p>Thus the answer would be <code>4</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that at least one triplet meets the given condition.</li>
</ul>
|
Array; Ordered Set
|
C++
|
class Solution {
public:
int maximumTripletValue(vector<int>& nums) {
int n = nums.size();
vector<int> right(n, nums.back());
for (int i = n - 2; ~i; --i) {
right[i] = max(nums[i], right[i + 1]);
}
set<int> ts;
ts.insert(nums[0]);
int ans = 0;
for (int j = 1; j < n - 1; ++j) {
if (right[j + 1] > nums[j]) {
auto it = ts.lower_bound(nums[j]);
if (it != ts.begin()) {
--it;
ans = max(ans, *it - nums[j] + right[j + 1]);
}
}
ts.insert(nums[j]);
}
return ans;
}
};
|
3,073
|
Maximum Increasing Triplet Value
|
Medium
|
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i < j < k</code> <em>and</em> <code>nums[i] < nums[j] < nums[k]</code>.</p>
<p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p>
<div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p>
<p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p>
<p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation: </strong> There are only two increasing triplets:</p>
<p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p>
<p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p>
<p>Thus the answer would be <code>4</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that at least one triplet meets the given condition.</li>
</ul>
|
Array; Ordered Set
|
Go
|
func maximumTripletValue(nums []int) (ans int) {
n := len(nums)
right := make([]int, n)
right[n-1] = nums[n-1]
for i := n - 2; i >= 0; i-- {
right[i] = max(nums[i], right[i+1])
}
ts := treemap.NewWithIntComparator()
ts.Put(nums[0], nil)
for j := 1; j < n-1; j++ {
if right[j+1] > nums[j] {
val, _ := ts.Floor(nums[j] - 1)
if val != nil {
ans = max(ans, val.(int)-nums[j]+right[j+1])
}
}
ts.Put(nums[j], nil)
}
return
}
|
3,073
|
Maximum Increasing Triplet Value
|
Medium
|
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i < j < k</code> <em>and</em> <code>nums[i] < nums[j] < nums[k]</code>.</p>
<p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p>
<div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p>
<p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p>
<p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation: </strong> There are only two increasing triplets:</p>
<p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p>
<p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p>
<p>Thus the answer would be <code>4</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that at least one triplet meets the given condition.</li>
</ul>
|
Array; Ordered Set
|
Java
|
class Solution {
public int maximumTripletValue(int[] nums) {
int n = nums.length;
int[] right = new int[n];
right[n - 1] = nums[n - 1];
for (int i = n - 2; i >= 0; --i) {
right[i] = Math.max(nums[i], right[i + 1]);
}
TreeSet<Integer> ts = new TreeSet<>();
ts.add(nums[0]);
int ans = 0;
for (int j = 1; j < n - 1; ++j) {
if (right[j + 1] > nums[j]) {
Integer it = ts.lower(nums[j]);
if (it != null) {
ans = Math.max(ans, it - nums[j] + right[j + 1]);
}
}
ts.add(nums[j]);
}
return ans;
}
}
|
3,073
|
Maximum Increasing Triplet Value
|
Medium
|
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i < j < k</code> <em>and</em> <code>nums[i] < nums[j] < nums[k]</code>.</p>
<p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p>
<div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p>
<p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p>
<p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation: </strong> There are only two increasing triplets:</p>
<p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p>
<p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p>
<p>Thus the answer would be <code>4</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that at least one triplet meets the given condition.</li>
</ul>
|
Array; Ordered Set
|
Python
|
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
n = len(nums)
right = [nums[-1]] * n
for i in range(n - 2, -1, -1):
right[i] = max(nums[i], right[i + 1])
sl = SortedList([nums[0]])
ans = 0
for j in range(1, n - 1):
if right[j + 1] > nums[j]:
i = sl.bisect_left(nums[j]) - 1
if i >= 0:
ans = max(ans, sl[i] - nums[j] + right[j + 1])
sl.add(nums[j])
return ans
|
3,073
|
Maximum Increasing Triplet Value
|
Medium
|
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i < j < k</code> <em>and</em> <code>nums[i] < nums[j] < nums[k]</code>.</p>
<p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p>
<div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p>
<p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p>
<p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation: </strong> There are only two increasing triplets:</p>
<p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p>
<p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p>
<p>Thus the answer would be <code>4</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that at least one triplet meets the given condition.</li>
</ul>
|
Array; Ordered Set
|
TypeScript
|
function maximumTripletValue(nums: number[]): number {
const n = nums.length;
const right: number[] = Array(n).fill(nums[n - 1]);
for (let i = n - 2; ~i; --i) {
right[i] = Math.max(nums[i], right[i + 1]);
}
const ts = new TreeSet<number>();
ts.add(nums[0]);
let ans = 0;
for (let j = 1; j < n - 1; ++j) {
if (right[j + 1] > nums[j]) {
const val = ts.lower(nums[j]);
if (val !== undefined) {
ans = Math.max(ans, val - nums[j] + right[j + 1]);
}
}
ts.add(nums[j]);
}
return ans;
}
type Compare<T> = (lhs: T, rhs: T) => number;
class RBTreeNode<T = number> {
data: T;
count: number;
left: RBTreeNode<T> | null;
right: RBTreeNode<T> | null;
parent: RBTreeNode<T> | null;
color: number;
constructor(data: T) {
this.data = data;
this.left = this.right = this.parent = null;
this.color = 0;
this.count = 1;
}
sibling(): RBTreeNode<T> | null {
if (!this.parent) return null; // sibling null if no parent
return this.isOnLeft() ? this.parent.right : this.parent.left;
}
isOnLeft(): boolean {
return this === this.parent!.left;
}
hasRedChild(): boolean {
return (
Boolean(this.left && this.left.color === 0) ||
Boolean(this.right && this.right.color === 0)
);
}
}
class RBTree<T> {
root: RBTreeNode<T> | null;
lt: (l: T, r: T) => boolean;
constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) {
this.root = null;
this.lt = (l: T, r: T) => compare(l, r) < 0;
}
rotateLeft(pt: RBTreeNode<T>): void {
const right = pt.right!;
pt.right = right.left;
if (pt.right) pt.right.parent = pt;
right.parent = pt.parent;
if (!pt.parent) this.root = right;
else if (pt === pt.parent.left) pt.parent.left = right;
else pt.parent.right = right;
right.left = pt;
pt.parent = right;
}
rotateRight(pt: RBTreeNode<T>): void {
const left = pt.left!;
pt.left = left.right;
if (pt.left) pt.left.parent = pt;
left.parent = pt.parent;
if (!pt.parent) this.root = left;
else if (pt === pt.parent.left) pt.parent.left = left;
else pt.parent.right = left;
left.right = pt;
pt.parent = left;
}
swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void {
const tmp = p1.color;
p1.color = p2.color;
p2.color = tmp;
}
swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void {
const tmp = p1.data;
p1.data = p2.data;
p2.data = tmp;
}
fixAfterInsert(pt: RBTreeNode<T>): void {
let parent = null;
let grandParent = null;
while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) {
parent = pt.parent;
grandParent = pt.parent.parent;
/* Case : A
Parent of pt is left child of Grand-parent of pt */
if (parent === grandParent?.left) {
const uncle = grandParent.right;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle && uncle.color === 0) {
grandParent.color = 0;
parent.color = 1;
uncle.color = 1;
pt = grandParent;
} else {
/* Case : 2
pt is right child of its parent
Left-rotation required */
if (pt === parent.right) {
this.rotateLeft(parent);
pt = parent;
parent = pt.parent;
}
/* Case : 3
pt is left child of its parent
Right-rotation required */
this.rotateRight(grandParent);
this.swapColor(parent!, grandParent);
pt = parent!;
}
} else {
/* Case : B
Parent of pt is right child of Grand-parent of pt */
const uncle = grandParent!.left;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle != null && uncle.color === 0) {
grandParent!.color = 0;
parent.color = 1;
uncle.color = 1;
pt = grandParent!;
} else {
/* Case : 2
pt is left child of its parent
Right-rotation required */
if (pt === parent.left) {
this.rotateRight(parent);
pt = parent;
parent = pt.parent;
}
/* Case : 3
pt is right child of its parent
Left-rotation required */
this.rotateLeft(grandParent!);
this.swapColor(parent!, grandParent!);
pt = parent!;
}
}
}
this.root!.color = 1;
}
delete(val: T): boolean {
const node = this.find(val);
if (!node) return false;
node.count--;
if (!node.count) this.deleteNode(node);
return true;
}
deleteAll(val: T): boolean {
const node = this.find(val);
if (!node) return false;
this.deleteNode(node);
return true;
}
deleteNode(v: RBTreeNode<T>): void {
const u = BSTreplace(v);
// True when u and v are both black
const uvBlack = (u === null || u.color === 1) && v.color === 1;
const parent = v.parent!;
if (!u) {
// u is null therefore v is leaf
if (v === this.root) this.root = null;
// v is root, making root null
else {
if (uvBlack) {
// u and v both black
// v is leaf, fix double black at v
this.fixDoubleBlack(v);
} else {
// u or v is red
if (v.sibling()) {
// sibling is not null, make it red"
v.sibling()!.color = 0;
}
}
// delete v from the tree
if (v.isOnLeft()) parent.left = null;
else parent.right = null;
}
return;
}
if (!v.left || !v.right) {
// v has 1 child
if (v === this.root) {
// v is root, assign the value of u to v, and delete u
v.data = u.data;
v.left = v.right = null;
} else {
// Detach v from tree and move u up
if (v.isOnLeft()) parent.left = u;
else parent.right = u;
u.parent = parent;
if (uvBlack) this.fixDoubleBlack(u);
// u and v both black, fix double black at u
else u.color = 1; // u or v red, color u black
}
return;
}
// v has 2 children, swap data with successor and recurse
this.swapData(u, v);
this.deleteNode(u);
// find node that replaces a deleted node in BST
function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null {
// when node have 2 children
if (x.left && x.right) return successor(x.right);
// when leaf
if (!x.left && !x.right) return null;
// when single child
return x.left ?? x.right;
}
// find node that do not have a left child
// in the subtree of the given node
function successor(x: RBTreeNode<T>): RBTreeNode<T> {
let temp = x;
while (temp.left) temp = temp.left;
return temp;
}
}
fixDoubleBlack(x: RBTreeNode<T>): void {
if (x === this.root) return; // Reached root
const sibling = x.sibling();
const parent = x.parent!;
if (!sibling) {
// No sibiling, double black pushed up
this.fixDoubleBlack(parent);
} else {
if (sibling.color === 0) {
// Sibling red
parent.color = 0;
sibling.color = 1;
if (sibling.isOnLeft()) this.rotateRight(parent);
// left case
else this.rotateLeft(parent); // right case
this.fixDoubleBlack(x);
} else {
// Sibling black
if (sibling.hasRedChild()) {
// at least 1 red children
if (sibling.left && sibling.left.color === 0) {
if (sibling.isOnLeft()) {
// left left
sibling.left.color = sibling.color;
sibling.color = parent.color;
this.rotateRight(parent);
} else {
// right left
sibling.left.color = parent.color;
this.rotateRight(sibling);
this.rotateLeft(parent);
}
} else {
if (sibling.isOnLeft()) {
// left right
sibling.right!.color = parent.color;
this.rotateLeft(sibling);
this.rotateRight(parent);
} else {
// right right
sibling.right!.color = sibling.color;
sibling.color = parent.color;
this.rotateLeft(parent);
}
}
parent.color = 1;
} else {
// 2 black children
sibling.color = 0;
if (parent.color === 1) this.fixDoubleBlack(parent);
else parent.color = 1;
}
}
}
}
insert(data: T): boolean {
// search for a position to insert
let parent = this.root;
while (parent) {
if (this.lt(data, parent.data)) {
if (!parent.left) break;
else parent = parent.left;
} else if (this.lt(parent.data, data)) {
if (!parent.right) break;
else parent = parent.right;
} else break;
}
// insert node into parent
const node = new RBTreeNode(data);
if (!parent) this.root = node;
else if (this.lt(node.data, parent.data)) parent.left = node;
else if (this.lt(parent.data, node.data)) parent.right = node;
else {
parent.count++;
return false;
}
node.parent = parent;
this.fixAfterInsert(node);
return true;
}
find(data: T): RBTreeNode<T> | null {
let p = this.root;
while (p) {
if (this.lt(data, p.data)) {
p = p.left;
} else if (this.lt(p.data, data)) {
p = p.right;
} else break;
}
return p ?? null;
}
*inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> {
if (!root) return;
for (const v of this.inOrder(root.left!)) yield v;
yield root.data;
for (const v of this.inOrder(root.right!)) yield v;
}
*reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> {
if (!root) return;
for (const v of this.reverseInOrder(root.right!)) yield v;
yield root.data;
for (const v of this.reverseInOrder(root.left!)) yield v;
}
}
class TreeSet<T = number> {
_size: number;
tree: RBTree<T>;
compare: Compare<T>;
constructor(
collection: T[] | Compare<T> = [],
compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0),
) {
if (typeof collection === 'function') {
compare = collection;
collection = [];
}
this._size = 0;
this.compare = compare;
this.tree = new RBTree(compare);
for (const val of collection) this.add(val);
}
size(): number {
return this._size;
}
has(val: T): boolean {
return !!this.tree.find(val);
}
add(val: T): boolean {
const successful = this.tree.insert(val);
this._size += successful ? 1 : 0;
return successful;
}
delete(val: T): boolean {
const deleted = this.tree.deleteAll(val);
this._size -= deleted ? 1 : 0;
return deleted;
}
ceil(val: T): T | undefined {
let p = this.tree.root;
let higher = null;
while (p) {
if (this.compare(p.data, val) >= 0) {
higher = p;
p = p.left;
} else {
p = p.right;
}
}
return higher?.data;
}
floor(val: T): T | undefined {
let p = this.tree.root;
let lower = null;
while (p) {
if (this.compare(val, p.data) >= 0) {
lower = p;
p = p.right;
} else {
p = p.left;
}
}
return lower?.data;
}
higher(val: T): T | undefined {
let p = this.tree.root;
let higher = null;
while (p) {
if (this.compare(val, p.data) < 0) {
higher = p;
p = p.left;
} else {
p = p.right;
}
}
return higher?.data;
}
lower(val: T): T | undefined {
let p = this.tree.root;
let lower = null;
while (p) {
if (this.compare(p.data, val) < 0) {
lower = p;
p = p.right;
} else {
p = p.left;
}
}
return lower?.data;
}
first(): T | undefined {
return this.tree.inOrder().next().value;
}
last(): T | undefined {
return this.tree.reverseInOrder().next().value;
}
shift(): T | undefined {
const first = this.first();
if (first === undefined) return undefined;
this.delete(first);
return first;
}
pop(): T | undefined {
const last = this.last();
if (last === undefined) return undefined;
this.delete(last);
return last;
}
*[Symbol.iterator](): Generator<T, void, void> {
for (const val of this.values()) yield val;
}
*keys(): Generator<T, void, void> {
for (const val of this.values()) yield val;
}
*values(): Generator<T, undefined, void> {
for (const val of this.tree.inOrder()) yield val;
return undefined;
}
/**
* Return a generator for reverse order traversing the set
*/
*rvalues(): Generator<T, undefined, void> {
for (const val of this.tree.reverseInOrder()) yield val;
return undefined;
}
}
|
3,074
|
Apple Redistribution into Boxes
|
Easy
|
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p>
<p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p>
<p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p>
<p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We will need to use all the boxes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == apple.length <= 50</code></li>
<li><code>1 <= m == capacity.length <= 50</code></li>
<li><code>1 <= apple[i], capacity[i] <= 50</code></li>
<li>The input is generated such that it's possible to redistribute packs of apples into boxes.</li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
int minimumBoxes(vector<int>& apple, vector<int>& capacity) {
sort(capacity.rbegin(), capacity.rend());
int s = accumulate(apple.begin(), apple.end(), 0);
for (int i = 1;; ++i) {
s -= capacity[i - 1];
if (s <= 0) {
return i;
}
}
}
};
|
3,074
|
Apple Redistribution into Boxes
|
Easy
|
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p>
<p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p>
<p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p>
<p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We will need to use all the boxes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == apple.length <= 50</code></li>
<li><code>1 <= m == capacity.length <= 50</code></li>
<li><code>1 <= apple[i], capacity[i] <= 50</code></li>
<li>The input is generated such that it's possible to redistribute packs of apples into boxes.</li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func minimumBoxes(apple []int, capacity []int) int {
sort.Ints(capacity)
s := 0
for _, x := range apple {
s += x
}
for i := 1; ; i++ {
s -= capacity[len(capacity)-i]
if s <= 0 {
return i
}
}
}
|
3,074
|
Apple Redistribution into Boxes
|
Easy
|
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p>
<p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p>
<p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p>
<p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We will need to use all the boxes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == apple.length <= 50</code></li>
<li><code>1 <= m == capacity.length <= 50</code></li>
<li><code>1 <= apple[i], capacity[i] <= 50</code></li>
<li>The input is generated such that it's possible to redistribute packs of apples into boxes.</li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public int minimumBoxes(int[] apple, int[] capacity) {
Arrays.sort(capacity);
int s = 0;
for (int x : apple) {
s += x;
}
for (int i = 1, n = capacity.length;; ++i) {
s -= capacity[n - i];
if (s <= 0) {
return i;
}
}
}
}
|
3,074
|
Apple Redistribution into Boxes
|
Easy
|
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p>
<p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p>
<p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p>
<p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We will need to use all the boxes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == apple.length <= 50</code></li>
<li><code>1 <= m == capacity.length <= 50</code></li>
<li><code>1 <= apple[i], capacity[i] <= 50</code></li>
<li>The input is generated such that it's possible to redistribute packs of apples into boxes.</li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
capacity.sort(reverse=True)
s = sum(apple)
for i, c in enumerate(capacity, 1):
s -= c
if s <= 0:
return i
|
3,074
|
Apple Redistribution into Boxes
|
Easy
|
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p>
<p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p>
<p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p>
<p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We will need to use all the boxes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == apple.length <= 50</code></li>
<li><code>1 <= m == capacity.length <= 50</code></li>
<li><code>1 <= apple[i], capacity[i] <= 50</code></li>
<li>The input is generated such that it's possible to redistribute packs of apples into boxes.</li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function minimumBoxes(apple: number[], capacity: number[]): number {
capacity.sort((a, b) => b - a);
let s = apple.reduce((acc, cur) => acc + cur, 0);
for (let i = 1; ; ++i) {
s -= capacity[i - 1];
if (s <= 0) {
return i;
}
}
}
|
3,075
|
Maximize Happiness of Selected Children
|
Medium
|
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p>
<p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p>
<p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,2,3], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
The sum of the happiness values of the selected children is 3 + 1 = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,1,1,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
The sum of the happiness values of the selected children is 1 + 0 = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> happiness = [2,3,4,5], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can pick 1 child in the following way:
- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
The sum of the happiness values of the selected children is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == happiness.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= happiness[i] <= 10<sup>8</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
long long maximumHappinessSum(vector<int>& happiness, int k) {
sort(happiness.rbegin(), happiness.rend());
long long ans = 0;
for (int i = 0, n = happiness.size(); i < k; ++i) {
int x = happiness[i] - i;
ans += max(x, 0);
}
return ans;
}
};
|
3,075
|
Maximize Happiness of Selected Children
|
Medium
|
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p>
<p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p>
<p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,2,3], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
The sum of the happiness values of the selected children is 3 + 1 = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,1,1,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
The sum of the happiness values of the selected children is 1 + 0 = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> happiness = [2,3,4,5], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can pick 1 child in the following way:
- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
The sum of the happiness values of the selected children is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == happiness.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= happiness[i] <= 10<sup>8</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func maximumHappinessSum(happiness []int, k int) (ans int64) {
sort.Ints(happiness)
for i := 0; i < k; i++ {
x := happiness[len(happiness)-i-1] - i
ans += int64(max(x, 0))
}
return
}
|
3,075
|
Maximize Happiness of Selected Children
|
Medium
|
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p>
<p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p>
<p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,2,3], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
The sum of the happiness values of the selected children is 3 + 1 = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,1,1,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
The sum of the happiness values of the selected children is 1 + 0 = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> happiness = [2,3,4,5], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can pick 1 child in the following way:
- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
The sum of the happiness values of the selected children is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == happiness.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= happiness[i] <= 10<sup>8</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public long maximumHappinessSum(int[] happiness, int k) {
Arrays.sort(happiness);
long ans = 0;
for (int i = 0, n = happiness.length; i < k; ++i) {
int x = happiness[n - i - 1] - i;
ans += Math.max(x, 0);
}
return ans;
}
}
|
3,075
|
Maximize Happiness of Selected Children
|
Medium
|
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p>
<p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p>
<p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,2,3], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
The sum of the happiness values of the selected children is 3 + 1 = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,1,1,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
The sum of the happiness values of the selected children is 1 + 0 = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> happiness = [2,3,4,5], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can pick 1 child in the following way:
- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
The sum of the happiness values of the selected children is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == happiness.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= happiness[i] <= 10<sup>8</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def maximumHappinessSum(self, happiness: List[int], k: int) -> int:
happiness.sort(reverse=True)
ans = 0
for i, x in enumerate(happiness[:k]):
x -= i
ans += max(x, 0)
return ans
|
3,075
|
Maximize Happiness of Selected Children
|
Medium
|
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p>
<p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p>
<p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,2,3], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
The sum of the happiness values of the selected children is 3 + 1 = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> happiness = [1,1,1,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can pick 2 children in the following way:
- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
The sum of the happiness values of the selected children is 1 + 0 = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> happiness = [2,3,4,5], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can pick 1 child in the following way:
- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
The sum of the happiness values of the selected children is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == happiness.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= happiness[i] <= 10<sup>8</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function maximumHappinessSum(happiness: number[], k: number): number {
happiness.sort((a, b) => b - a);
let ans = 0;
for (let i = 0; i < k; ++i) {
const x = happiness[i] - i;
ans += Math.max(x, 0);
}
return ans;
}
|
3,076
|
Shortest Uncommon Substring in an Array
|
Medium
|
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p>
<p>Find a string array <code>answer</code> of size <code>n</code> such that:</p>
<ul>
<li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li>
</ul>
<p>Return <em>the array </em><code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = ["cab","ad","bad","c"]
<strong>Output:</strong> ["ab","","ba",""]
<strong>Explanation:</strong> We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = ["abc","bcd","abcd"]
<strong>Output:</strong> ["","","abcd"]
<strong>Explanation:</strong> We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arr.length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>1 <= arr[i].length <= 20</code></li>
<li><code>arr[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; Hash Table; String
|
C++
|
class Solution {
public:
vector<string> shortestSubstrings(vector<string>& arr) {
int n = arr.size();
vector<string> ans(n);
for (int i = 0; i < n; ++i) {
int m = arr[i].size();
for (int j = 1; j <= m && ans[i].empty(); ++j) {
for (int l = 0; l <= m - j; ++l) {
string sub = arr[i].substr(l, j);
if (ans[i].empty() || sub < ans[i]) {
bool ok = true;
for (int k = 0; k < n && ok; ++k) {
if (k != i && arr[k].find(sub) != string::npos) {
ok = false;
}
}
if (ok) {
ans[i] = sub;
}
}
}
}
}
return ans;
}
};
|
3,076
|
Shortest Uncommon Substring in an Array
|
Medium
|
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p>
<p>Find a string array <code>answer</code> of size <code>n</code> such that:</p>
<ul>
<li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li>
</ul>
<p>Return <em>the array </em><code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = ["cab","ad","bad","c"]
<strong>Output:</strong> ["ab","","ba",""]
<strong>Explanation:</strong> We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = ["abc","bcd","abcd"]
<strong>Output:</strong> ["","","abcd"]
<strong>Explanation:</strong> We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arr.length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>1 <= arr[i].length <= 20</code></li>
<li><code>arr[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; Hash Table; String
|
Go
|
func shortestSubstrings(arr []string) []string {
ans := make([]string, len(arr))
for i, s := range arr {
m := len(s)
for j := 1; j <= m && len(ans[i]) == 0; j++ {
for l := 0; l <= m-j; l++ {
sub := s[l : l+j]
if len(ans[i]) == 0 || ans[i] > sub {
ok := true
for k, t := range arr {
if k != i && strings.Contains(t, sub) {
ok = false
break
}
}
if ok {
ans[i] = sub
}
}
}
}
}
return ans
}
|
3,076
|
Shortest Uncommon Substring in an Array
|
Medium
|
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p>
<p>Find a string array <code>answer</code> of size <code>n</code> such that:</p>
<ul>
<li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li>
</ul>
<p>Return <em>the array </em><code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = ["cab","ad","bad","c"]
<strong>Output:</strong> ["ab","","ba",""]
<strong>Explanation:</strong> We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = ["abc","bcd","abcd"]
<strong>Output:</strong> ["","","abcd"]
<strong>Explanation:</strong> We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arr.length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>1 <= arr[i].length <= 20</code></li>
<li><code>arr[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; Hash Table; String
|
Java
|
class Solution {
public String[] shortestSubstrings(String[] arr) {
int n = arr.length;
String[] ans = new String[n];
Arrays.fill(ans, "");
for (int i = 0; i < n; ++i) {
int m = arr[i].length();
for (int j = 1; j <= m && ans[i].isEmpty(); ++j) {
for (int l = 0; l <= m - j; ++l) {
String sub = arr[i].substring(l, l + j);
if (ans[i].isEmpty() || sub.compareTo(ans[i]) < 0) {
boolean ok = true;
for (int k = 0; k < n && ok; ++k) {
if (k != i && arr[k].contains(sub)) {
ok = false;
}
}
if (ok) {
ans[i] = sub;
}
}
}
}
}
return ans;
}
}
|
3,076
|
Shortest Uncommon Substring in an Array
|
Medium
|
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p>
<p>Find a string array <code>answer</code> of size <code>n</code> such that:</p>
<ul>
<li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li>
</ul>
<p>Return <em>the array </em><code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = ["cab","ad","bad","c"]
<strong>Output:</strong> ["ab","","ba",""]
<strong>Explanation:</strong> We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = ["abc","bcd","abcd"]
<strong>Output:</strong> ["","","abcd"]
<strong>Explanation:</strong> We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arr.length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>1 <= arr[i].length <= 20</code></li>
<li><code>arr[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; Hash Table; String
|
Python
|
class Solution:
def shortestSubstrings(self, arr: List[str]) -> List[str]:
ans = [""] * len(arr)
for i, s in enumerate(arr):
m = len(s)
for j in range(1, m + 1):
for l in range(m - j + 1):
sub = s[l : l + j]
if not ans[i] or ans[i] > sub:
if all(k == i or sub not in t for k, t in enumerate(arr)):
ans[i] = sub
if ans[i]:
break
return ans
|
3,076
|
Shortest Uncommon Substring in an Array
|
Medium
|
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p>
<p>Find a string array <code>answer</code> of size <code>n</code> such that:</p>
<ul>
<li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li>
</ul>
<p>Return <em>the array </em><code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr = ["cab","ad","bad","c"]
<strong>Output:</strong> ["ab","","ba",""]
<strong>Explanation:</strong> We have the following:
- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".
- For the string "ad", there is no substring that does not occur in any other string.
- For the string "bad", the shortest substring that does not occur in any other string is "ba".
- For the string "c", there is no substring that does not occur in any other string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr = ["abc","bcd","abcd"]
<strong>Output:</strong> ["","","abcd"]
<strong>Explanation:</strong> We have the following:
- For the string "abc", there is no substring that does not occur in any other string.
- For the string "bcd", there is no substring that does not occur in any other string.
- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arr.length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>1 <= arr[i].length <= 20</code></li>
<li><code>arr[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; Hash Table; String
|
TypeScript
|
function shortestSubstrings(arr: string[]): string[] {
const n: number = arr.length;
const ans: string[] = Array(n).fill('');
for (let i = 0; i < n; ++i) {
const m: number = arr[i].length;
for (let j = 1; j <= m && ans[i] === ''; ++j) {
for (let l = 0; l <= m - j; ++l) {
const sub: string = arr[i].slice(l, l + j);
if (ans[i] === '' || sub.localeCompare(ans[i]) < 0) {
let ok: boolean = true;
for (let k = 0; k < n && ok; ++k) {
if (k !== i && arr[k].includes(sub)) {
ok = false;
}
}
if (ok) {
ans[i] = sub;
}
}
}
}
}
return ans;
}
|
3,077
|
Maximum Strength of K Disjoint Subarrays
|
Hard
|
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p>
<p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 <= i <= k-1</code>. The goal is to maximize their combined strength.</p>
<p>The strength of the selected subarrays is defined as:</p>
<p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p>
<p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p>
<p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p>
<p><strong>Note</strong> that the chosen subarrays <strong>don't</strong> need to cover the entire array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p>
<p> </p>
<p><strong class="example">Example 2:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">64</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p>
<p><strong class="example">Example 3:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li><code>1 <= n * k <= 10<sup>6</sup></code></li>
<li><code>k</code> is odd.</li>
</ul>
|
Array; Dynamic Programming; Prefix Sum
|
C++
|
class Solution {
public:
long long maximumStrength(vector<int>& nums, int k) {
int n = nums.size();
long long f[n + 1][k + 1][2];
memset(f, -0x3f3f3f3f3f3f3f3f, sizeof(f));
f[0][0][0] = 0;
for (int i = 1; i <= n; i++) {
int x = nums[i - 1];
for (int j = 0; j <= k; j++) {
long long sign = (j & 1) == 1 ? 1 : -1;
long long val = sign * x * (k - j + 1);
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1]);
f[i][j][1] = max(f[i][j][1], f[i - 1][j][1] + val);
if (j > 0) {
long long t = max(f[i - 1][j - 1][0], f[i - 1][j - 1][1]) + val;
f[i][j][1] = max(f[i][j][1], t);
}
}
}
return max(f[n][k][0], f[n][k][1]);
}
};
|
3,077
|
Maximum Strength of K Disjoint Subarrays
|
Hard
|
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p>
<p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 <= i <= k-1</code>. The goal is to maximize their combined strength.</p>
<p>The strength of the selected subarrays is defined as:</p>
<p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p>
<p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p>
<p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p>
<p><strong>Note</strong> that the chosen subarrays <strong>don't</strong> need to cover the entire array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p>
<p> </p>
<p><strong class="example">Example 2:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">64</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p>
<p><strong class="example">Example 3:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li><code>1 <= n * k <= 10<sup>6</sup></code></li>
<li><code>k</code> is odd.</li>
</ul>
|
Array; Dynamic Programming; Prefix Sum
|
Go
|
func maximumStrength(nums []int, k int) int64 {
n := len(nums)
f := make([][][]int64, n+1)
const inf int64 = math.MinInt64 / 2
for i := range f {
f[i] = make([][]int64, k+1)
for j := range f[i] {
f[i][j] = []int64{inf, inf}
}
}
f[0][0][0] = 0
for i := 1; i <= n; i++ {
x := nums[i-1]
for j := 0; j <= k; j++ {
sign := int64(-1)
if j&1 == 1 {
sign = 1
}
val := sign * int64(x) * int64(k-j+1)
f[i][j][0] = max(f[i-1][j][0], f[i-1][j][1])
f[i][j][1] = max(f[i][j][1], f[i-1][j][1]+val)
if j > 0 {
t := max(f[i-1][j-1][0], f[i-1][j-1][1]) + val
f[i][j][1] = max(f[i][j][1], t)
}
}
}
return max(f[n][k][0], f[n][k][1])
}
|
3,077
|
Maximum Strength of K Disjoint Subarrays
|
Hard
|
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p>
<p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 <= i <= k-1</code>. The goal is to maximize their combined strength.</p>
<p>The strength of the selected subarrays is defined as:</p>
<p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p>
<p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p>
<p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p>
<p><strong>Note</strong> that the chosen subarrays <strong>don't</strong> need to cover the entire array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p>
<p> </p>
<p><strong class="example">Example 2:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">64</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p>
<p><strong class="example">Example 3:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li><code>1 <= n * k <= 10<sup>6</sup></code></li>
<li><code>k</code> is odd.</li>
</ul>
|
Array; Dynamic Programming; Prefix Sum
|
Java
|
class Solution {
public long maximumStrength(int[] nums, int k) {
int n = nums.length;
long[][][] f = new long[n + 1][k + 1][2];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= k; j++) {
Arrays.fill(f[i][j], Long.MIN_VALUE / 2);
}
}
f[0][0][0] = 0;
for (int i = 1; i <= n; i++) {
int x = nums[i - 1];
for (int j = 0; j <= k; j++) {
long sign = (j & 1) == 1 ? 1 : -1;
long val = sign * x * (k - j + 1);
f[i][j][0] = Math.max(f[i - 1][j][0], f[i - 1][j][1]);
f[i][j][1] = Math.max(f[i][j][1], f[i - 1][j][1] + val);
if (j > 0) {
long t = Math.max(f[i - 1][j - 1][0], f[i - 1][j - 1][1]) + val;
f[i][j][1] = Math.max(f[i][j][1], t);
}
}
}
return Math.max(f[n][k][0], f[n][k][1]);
}
}
|
3,077
|
Maximum Strength of K Disjoint Subarrays
|
Hard
|
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p>
<p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 <= i <= k-1</code>. The goal is to maximize their combined strength.</p>
<p>The strength of the selected subarrays is defined as:</p>
<p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p>
<p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p>
<p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p>
<p><strong>Note</strong> that the chosen subarrays <strong>don't</strong> need to cover the entire array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p>
<p> </p>
<p><strong class="example">Example 2:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">64</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p>
<p><strong class="example">Example 3:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li><code>1 <= n * k <= 10<sup>6</sup></code></li>
<li><code>k</code> is odd.</li>
</ul>
|
Array; Dynamic Programming; Prefix Sum
|
Python
|
class Solution:
def maximumStrength(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [[[-inf, -inf] for _ in range(k + 1)] for _ in range(n + 1)]
f[0][0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(k + 1):
sign = 1 if j & 1 else -1
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1])
f[i][j][1] = max(f[i][j][1], f[i - 1][j][1] + sign * x * (k - j + 1))
if j:
f[i][j][1] = max(
f[i][j][1], max(f[i - 1][j - 1]) + sign * x * (k - j + 1)
)
return max(f[n][k])
|
3,077
|
Maximum Strength of K Disjoint Subarrays
|
Hard
|
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p>
<p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 <= i <= k-1</code>. The goal is to maximize their combined strength.</p>
<p>The strength of the selected subarrays is defined as:</p>
<p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p>
<p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p>
<p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p>
<p><strong>Note</strong> that the chosen subarrays <strong>don't</strong> need to cover the entire array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p>
<p> </p>
<p><strong class="example">Example 2:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">64</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p>
<p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p>
<p><strong class="example">Example 3:</strong></p>
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li><code>1 <= n * k <= 10<sup>6</sup></code></li>
<li><code>k</code> is odd.</li>
</ul>
|
Array; Dynamic Programming; Prefix Sum
|
TypeScript
|
function maximumStrength(nums: number[], k: number): number {
const n: number = nums.length;
const f: number[][][] = Array.from({ length: n + 1 }, () =>
Array.from({ length: k + 1 }, () => [-Infinity, -Infinity]),
);
f[0][0][0] = 0;
for (let i = 1; i <= n; i++) {
const x: number = nums[i - 1];
for (let j = 0; j <= k; j++) {
const sign: number = (j & 1) === 1 ? 1 : -1;
const val: number = sign * x * (k - j + 1);
f[i][j][0] = Math.max(f[i - 1][j][0], f[i - 1][j][1]);
f[i][j][1] = Math.max(f[i][j][1], f[i - 1][j][1] + val);
if (j > 0) {
f[i][j][1] = Math.max(f[i][j][1], Math.max(...f[i - 1][j - 1]) + val);
}
}
}
return Math.max(...f[n][k]);
}
|
3,078
|
Match Alphanumerical Pattern in Matrix I
|
Medium
|
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 <= board[r][c] <= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p>
<p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p>
<p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p>
<ul>
<li>The matrices have identical dimensions.</li>
<li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li>
<li>If <code>pattern[r][c]</code> is a letter <code>x</code>:
<ul>
<li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li>
<li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li>
</ul>
</li>
</ul>
<p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 1</code> and <code>"b" -> 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p>
<p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 3</code> and <code>"b" -> 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p>
<p>Note that since the corresponding values of <code>"a"</code> and <code>"b"</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = ["xx"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
<p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 50</code></li>
<li><code>1 <= board[i].length <= 50</code></li>
<li><code>0 <= board[i][j] <= 9</code></li>
<li><code>1 <= pattern.length <= 50</code></li>
<li><code>1 <= pattern[i].length <= 50</code></li>
<li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li>
</ul>
|
Array; Hash Table; String; Matrix
|
C++
|
class Solution {
public:
vector<int> findPattern(vector<vector<int>>& board, vector<string>& pattern) {
int m = board.size(), n = board[0].size();
int r = pattern.size(), c = pattern[0].size();
auto check = [&](int i, int j) {
vector<int> d1(26, -1);
vector<int> d2(10, -1);
for (int a = 0; a < r; ++a) {
for (int b = 0; b < c; ++b) {
int x = i + a, y = j + b;
if (isdigit(pattern[a][b])) {
int v = pattern[a][b] - '0';
if (v != board[x][y]) {
return false;
}
} else {
int v = pattern[a][b] - 'a';
if (d1[v] != -1 && d1[v] != board[x][y]) {
return false;
}
if (d2[board[x][y]] != -1 && d2[board[x][y]] != v) {
return false;
}
d1[v] = board[x][y];
d2[board[x][y]] = v;
}
}
}
return true;
};
for (int i = 0; i < m - r + 1; ++i) {
for (int j = 0; j < n - c + 1; ++j) {
if (check(i, j)) {
return {i, j};
}
}
}
return {-1, -1};
}
};
|
3,078
|
Match Alphanumerical Pattern in Matrix I
|
Medium
|
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 <= board[r][c] <= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p>
<p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p>
<p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p>
<ul>
<li>The matrices have identical dimensions.</li>
<li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li>
<li>If <code>pattern[r][c]</code> is a letter <code>x</code>:
<ul>
<li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li>
<li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li>
</ul>
</li>
</ul>
<p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 1</code> and <code>"b" -> 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p>
<p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td>
<td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 3</code> and <code>"b" -> 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p>
<p>Note that since the corresponding values of <code>"a"</code> and <code>"b"</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td>
<td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = ["xx"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
<p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 50</code></li>
<li><code>1 <= board[i].length <= 50</code></li>
<li><code>0 <= board[i][j] <= 9</code></li>
<li><code>1 <= pattern.length <= 50</code></li>
<li><code>1 <= pattern[i].length <= 50</code></li>
<li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li>
</ul>
|
Array; Hash Table; String; Matrix
|
Go
|
func findPattern(board [][]int, pattern []string) []int {
m, n := len(board), len(board[0])
r, c := len(pattern), len(pattern[0])
check := func(i, j int) bool {
d1 := [26]int{}
d2 := [10]int{}
for a := 0; a < r; a++ {
for b := 0; b < c; b++ {
x, y := i+a, j+b
if pattern[a][b] >= '0' && pattern[a][b] <= '9' {
v := int(pattern[a][b] - '0')
if v != board[x][y] {
return false
}
} else {
v := int(pattern[a][b] - 'a')
if d1[v] > 0 && d1[v]-1 != board[x][y] {
return false
}
if d2[board[x][y]] > 0 && d2[board[x][y]]-1 != v {
return false
}
d1[v] = board[x][y] + 1
d2[board[x][y]] = v + 1
}
}
}
return true
}
for i := 0; i < m-r+1; i++ {
for j := 0; j < n-c+1; j++ {
if check(i, j) {
return []int{i, j}
}
}
}
return []int{-1, -1}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.