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
|
|---|---|---|---|---|---|---|
2,782
|
Number of Unique Categories
|
Medium
|
<p>You are given an integer <code>n</code> and an object <code>categoryHandler</code> of class <code>CategoryHandler</code>.</p>
<p>There are <code>n </code>elements, numbered from <code>0</code> to <code>n - 1</code>. Each element has a category, and your task is to find the number of unique categories.</p>
<p>The class <code>CategoryHandler</code> contains the following function, which may help you:</p>
<ul>
<li><code>boolean haveSameCategory(integer a, integer b)</code>: Returns <code>true</code> if <code>a</code> and <code>b</code> are in the same category and <code>false</code> otherwise. Also, if either <code>a</code> or <code>b</code> is not a valid number (i.e. it's greater than or equal to <code>n</code>or less than <code>0</code>), it returns <code>false</code>.</li>
</ul>
<p>Return <em>the number of unique categories.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 6, categoryHandler = [1,1,2,2,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, categoryHandler = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3, categoryHandler = [1,1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
</ul>
|
Union Find; Counting; Interactive
|
TypeScript
|
/**
* Definition for a category handler.
* class CategoryHandler {
* constructor(categories: number[]);
* public haveSameCategory(a: number, b: number): boolean;
* }
*/
function numberOfCategories(n: number, categoryHandler: CategoryHandler): number {
const p: number[] = new Array(n).fill(0).map((_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
for (let a = 0; a < n; ++a) {
for (let b = a + 1; b < n; ++b) {
if (categoryHandler.haveSameCategory(a, b)) {
p[find(a)] = find(b);
}
}
}
let ans = 0;
for (let i = 0; i < n; ++i) {
if (i === p[i]) {
++ans;
}
}
return ans;
}
|
2,783
|
Flight Occupancy and Waitlist Analysis
|
Medium
|
<p>Table: <code><font face="monospace">Flights</font></code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| flight_id | int |
| capacity | int |
+-------------+------+
<code>flight_id</code> is the column with unique values for this table.
Each row of this table contains flight id and its capacity.
</pre>
<p>Table: <code>Passengers</code></p>
<pre>
+--------------+------+
| Column Name | Type |
+--------------+------+
| passenger_id | int |
| flight_id | int |
+--------------+------+
passenger_id is the column with unique values for this table.
Each row of this table contains passenger id and flight id.
</pre>
<p>Passengers book tickets for flights in advance. If a passenger books a ticket for a flight and there are still empty seats available on the flight, the passenger ticket will be <strong>confirmed</strong>. However, the passenger will be on a <strong>waitlist</strong> if the flight is already at full capacity.</p>
<p>Write a solution to report the number of passengers who successfully booked a flight (got a seat) and the number of passengers who are on the waitlist for each flight.</p>
<p>Return the result table ordered by<em> </em><code>flight_id</code> in <strong>ascending</strong><em><strong> 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>
Flights table:
+-----------+----------+
| flight_id | capacity |
+-----------+----------+
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
+-----------+----------+
Passengers table:
+--------------+-----------+
| passenger_id | flight_id |
+--------------+-----------+
| 101 | 1 |
| 102 | 1 |
| 103 | 1 |
| 104 | 2 |
| 105 | 2 |
| 106 | 3 |
| 107 | 3 |
+--------------+-----------+
<strong>Output:</strong>
+-----------+------------+--------------+
| flight_id | booked_cnt | waitlist_cnt |
+-----------+------------+--------------+
| 1 | 2 | 1 |
| 2 | 2 | 0 |
| 3 | 1 | 1 |
+-----------+------------+--------------+
<strong>Explanation:</strong>
- Flight 1 has a capacity of 2. As there are 3 passengers who have booked tickets, only 2 passengers can get a seat. Therefore, 2 passengers are successfully booked, and 1 passenger is on the waitlist.
- Flight 2 has a capacity of 2. Since there are exactly 2 passengers who booked tickets, everyone can secure a seat. As a result, 2 passengers successfully booked their seats and there are no passengers on the waitlist.
- Flight 3 has a capacity of 1. As there are 2 passengers who have booked tickets, only 1 passenger can get a seat. Therefore, 1 passenger is successfully booked, and 1 passenger is on the waitlist.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
flight_id,
LEAST(COUNT(passenger_id), capacity) AS booked_cnt,
GREATEST(COUNT(passenger_id) - capacity, 0) AS waitlist_cnt
FROM
Flights
LEFT JOIN Passengers USING (flight_id)
GROUP BY 1
ORDER BY 1;
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
C++
|
class Solution {
public:
bool isGood(vector<int>& nums) {
int n = nums.size() - 1;
int cnt[201]{};
for (int x : nums) {
++cnt[x];
}
if (cnt[n] != 2) {
return false;
}
for (int i = 1; i < n; ++i) {
if (cnt[i] != 1) {
return false;
}
}
return true;
}
};
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
C#
|
public class Solution {
public bool IsGood(int[] nums) {
int n = nums.Length - 1;
int[] cnt = new int[201];
foreach (int x in nums) {
++cnt[x];
}
if (cnt[n] != 2) {
return false;
}
for (int i = 1; i < n; ++i) {
if (cnt[i] != 1) {
return false;
}
}
return true;
}
}
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Go
|
func isGood(nums []int) bool {
n := len(nums) - 1
cnt := [201]int{}
for _, x := range nums {
cnt[x]++
}
if cnt[n] != 2 {
return false
}
for i := 1; i < n; i++ {
if cnt[i] != 1 {
return false
}
}
return true
}
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Java
|
class Solution {
public boolean isGood(int[] nums) {
int n = nums.length - 1;
int[] cnt = new int[201];
for (int x : nums) {
++cnt[x];
}
if (cnt[n] != 2) {
return false;
}
for (int i = 1; i < n; ++i) {
if (cnt[i] != 1) {
return false;
}
}
return true;
}
}
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Python
|
class Solution:
def isGood(self, nums: List[int]) -> bool:
cnt = Counter(nums)
n = len(nums) - 1
return cnt[n] == 2 and all(cnt[i] for i in range(1, n))
|
2,784
|
Check if Array is Good
|
Easy
|
<p>You are given an integer array <code>nums</code>. We consider an array <strong>good </strong>if it is a permutation of an array <code>base[n]</code>.</p>
<p><code>base[n] = [1, 2, ..., n - 1, n, n] </code>(in other words, it is an array of length <code>n + 1</code> which contains <code>1</code> to <code>n - 1 </code>exactly once, plus two occurrences of <code>n</code>). For example, <code>base[1] = [1, 1]</code> and<code> base[3] = [1, 2, 3, 3]</code>.</p>
<p>Return <code>true</code> <em>if the given array is good, otherwise return</em><em> </em><code>false</code>.</p>
<p><strong>Note: </strong>A permutation of integers represents an arrangement of these numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2, 1, 3]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 3, 3, 2]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1, 1]
<strong>Output:</strong> true
<strong>Explanation:</strong> Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong> nums = [3, 4, 4, 1, 2, 1]
<strong>Output:</strong> false
<strong>Explanation:</strong> Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= num[i] <= 200</code></li>
</ul>
|
Array; Hash Table; Sorting
|
TypeScript
|
function isGood(nums: number[]): boolean {
const n = nums.length - 1;
const cnt: number[] = Array(201).fill(0);
for (const x of nums) {
++cnt[x];
}
if (cnt[n] !== 2) {
return false;
}
for (let i = 1; i < n; ++i) {
if (cnt[i] !== 1) {
return false;
}
}
return true;
}
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
C++
|
class Solution {
public:
string sortVowels(string s) {
string vs;
for (auto c : s) {
char d = tolower(c);
if (d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u') {
vs.push_back(c);
}
}
ranges::sort(vs);
for (int i = 0, j = 0; i < s.size(); ++i) {
char d = tolower(s[i]);
if (d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u') {
s[i] = vs[j++];
}
}
return s;
}
};
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
C#
|
public class Solution {
public string SortVowels(string s) {
List<char> vs = new List<char>();
char[] cs = s.ToCharArray();
foreach (char c in cs) {
if (IsVowel(c)) {
vs.Add(c);
}
}
vs.Sort();
for (int i = 0, j = 0; i < cs.Length; ++i) {
if (IsVowel(cs[i])) {
cs[i] = vs[j++];
}
}
return new string(cs);
}
public bool IsVowel(char c) {
c = char.ToLower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
Go
|
func sortVowels(s string) string {
cs := []byte(s)
vs := []byte{}
for _, c := range cs {
d := c | 32
if d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u' {
vs = append(vs, c)
}
}
sort.Slice(vs, func(i, j int) bool { return vs[i] < vs[j] })
j := 0
for i, c := range cs {
d := c | 32
if d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u' {
cs[i] = vs[j]
j++
}
}
return string(cs)
}
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
Java
|
class Solution {
public String sortVowels(String s) {
List<Character> vs = new ArrayList<>();
char[] cs = s.toCharArray();
for (char c : cs) {
char d = Character.toLowerCase(c);
if (d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u') {
vs.add(c);
}
}
Collections.sort(vs);
for (int i = 0, j = 0; i < cs.length; ++i) {
char d = Character.toLowerCase(cs[i]);
if (d == 'a' || d == 'e' || d == 'i' || d == 'o' || d == 'u') {
cs[i] = vs.get(j++);
}
}
return String.valueOf(cs);
}
}
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
Python
|
class Solution:
def sortVowels(self, s: str) -> str:
vs = [c for c in s if c.lower() in "aeiou"]
vs.sort()
cs = list(s)
j = 0
for i, c in enumerate(cs):
if c.lower() in "aeiou":
cs[i] = vs[j]
j += 1
return "".join(cs)
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
Rust
|
impl Solution {
pub fn sort_vowels(s: String) -> String {
fn is_vowel(c: char) -> bool {
matches!(c.to_ascii_lowercase(), 'a' | 'e' | 'i' | 'o' | 'u')
}
let mut vs: Vec<char> = s.chars().filter(|&c| is_vowel(c)).collect();
vs.sort_unstable();
let mut cs: Vec<char> = s.chars().collect();
let mut j = 0;
for (i, c) in cs.clone().into_iter().enumerate() {
if is_vowel(c) {
cs[i] = vs[j];
j += 1;
}
}
cs.into_iter().collect()
}
}
|
2,785
|
Sort Vowels in a String
|
Medium
|
<p>Given a <strong>0-indexed</strong> string <code>s</code>, <strong>permute</strong> <code>s</code> to get a new string <code>t</code> such that:</p>
<ul>
<li>All consonants remain in their original places. More formally, if there is an index <code>i</code> with <code>0 <= i < s.length</code> such that <code>s[i]</code> is a consonant, then <code>t[i] = s[i]</code>.</li>
<li>The vowels must be sorted in the <strong>nondecreasing</strong> order of their <strong>ASCII</strong> values. More formally, for pairs of indices <code>i</code>, <code>j</code> with <code>0 <= i < j < s.length</code> such that <code>s[i]</code> and <code>s[j]</code> are vowels, then <code>t[i]</code> must not have a higher ASCII value than <code>t[j]</code>.</li>
</ul>
<p>Return <em>the resulting string</em>.</p>
<p>The vowels are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "lEetcOde"
<strong>Output:</strong> "lEOtcede"
<strong>Explanation:</strong> 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "lYmpH"
<strong>Output:</strong> "lYmpH"
<strong>Explanation:</strong> There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of letters of the English alphabet in <strong>uppercase and lowercase</strong>.</li>
</ul>
|
String; Sorting
|
TypeScript
|
function sortVowels(s: string): string {
const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
const vs = s
.split('')
.filter(c => vowels.includes(c))
.sort();
const ans: string[] = [];
let j = 0;
for (const c of s) {
ans.push(vowels.includes(c) ? vs[j++] : c);
}
return ans.join('');
}
|
2,786
|
Visit Array Positions to Maximize Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>x</code>.</p>
<p>You are <strong>initially</strong> at position <code>0</code> in the array and you can visit other positions according to the following rules:</p>
<ul>
<li>If you are currently in position <code>i</code>, then you can move to <strong>any</strong> position <code>j</code> such that <code>i < j</code>.</li>
<li>For each position <code>i</code> that you visit, you get a score of <code>nums[i]</code>.</li>
<li>If you move from a position <code>i</code> to a position <code>j</code> and the <strong>parities</strong> of <code>nums[i]</code> and <code>nums[j]</code> differ, then you lose a score of <code>x</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> total score you can get</em>.</p>
<p><strong>Note</strong> that initially you have <code>nums[0]</code> points.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6,1,9,2], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.
The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.
The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6,8], x = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> All the integers in the array have the same parities, so we can visit all of them without losing any score.
The total score is: 2 + 4 + 6 + 8 = 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
long long maxScore(vector<int>& nums, int x) {
const long long inf = 1LL << 60;
vector<long long> f(2, -inf);
f[nums[0] & 1] = nums[0];
int n = nums.size();
for (int i = 1; i < n; ++i) {
int v = nums[i];
f[v & 1] = max(f[v & 1], f[v & 1 ^ 1] - x) + v;
}
return max(f[0], f[1]);
}
};
|
2,786
|
Visit Array Positions to Maximize Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>x</code>.</p>
<p>You are <strong>initially</strong> at position <code>0</code> in the array and you can visit other positions according to the following rules:</p>
<ul>
<li>If you are currently in position <code>i</code>, then you can move to <strong>any</strong> position <code>j</code> such that <code>i < j</code>.</li>
<li>For each position <code>i</code> that you visit, you get a score of <code>nums[i]</code>.</li>
<li>If you move from a position <code>i</code> to a position <code>j</code> and the <strong>parities</strong> of <code>nums[i]</code> and <code>nums[j]</code> differ, then you lose a score of <code>x</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> total score you can get</em>.</p>
<p><strong>Note</strong> that initially you have <code>nums[0]</code> points.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6,1,9,2], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.
The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.
The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6,8], x = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> All the integers in the array have the same parities, so we can visit all of them without losing any score.
The total score is: 2 + 4 + 6 + 8 = 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func maxScore(nums []int, x int) int64 {
const inf int = 1 << 40
f := [2]int{-inf, -inf}
f[nums[0]&1] = nums[0]
for _, v := range nums[1:] {
f[v&1] = max(f[v&1], f[v&1^1]-x) + v
}
return int64(max(f[0], f[1]))
}
|
2,786
|
Visit Array Positions to Maximize Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>x</code>.</p>
<p>You are <strong>initially</strong> at position <code>0</code> in the array and you can visit other positions according to the following rules:</p>
<ul>
<li>If you are currently in position <code>i</code>, then you can move to <strong>any</strong> position <code>j</code> such that <code>i < j</code>.</li>
<li>For each position <code>i</code> that you visit, you get a score of <code>nums[i]</code>.</li>
<li>If you move from a position <code>i</code> to a position <code>j</code> and the <strong>parities</strong> of <code>nums[i]</code> and <code>nums[j]</code> differ, then you lose a score of <code>x</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> total score you can get</em>.</p>
<p><strong>Note</strong> that initially you have <code>nums[0]</code> points.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6,1,9,2], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.
The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.
The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6,8], x = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> All the integers in the array have the same parities, so we can visit all of them without losing any score.
The total score is: 2 + 4 + 6 + 8 = 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public long maxScore(int[] nums, int x) {
long[] f = new long[2];
Arrays.fill(f, -(1L << 60));
f[nums[0] & 1] = nums[0];
for (int i = 1; i < nums.length; ++i) {
int v = nums[i];
f[v & 1] = Math.max(f[v & 1], f[v & 1 ^ 1] - x) + v;
}
return Math.max(f[0], f[1]);
}
}
|
2,786
|
Visit Array Positions to Maximize Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>x</code>.</p>
<p>You are <strong>initially</strong> at position <code>0</code> in the array and you can visit other positions according to the following rules:</p>
<ul>
<li>If you are currently in position <code>i</code>, then you can move to <strong>any</strong> position <code>j</code> such that <code>i < j</code>.</li>
<li>For each position <code>i</code> that you visit, you get a score of <code>nums[i]</code>.</li>
<li>If you move from a position <code>i</code> to a position <code>j</code> and the <strong>parities</strong> of <code>nums[i]</code> and <code>nums[j]</code> differ, then you lose a score of <code>x</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> total score you can get</em>.</p>
<p><strong>Note</strong> that initially you have <code>nums[0]</code> points.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6,1,9,2], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.
The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.
The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6,8], x = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> All the integers in the array have the same parities, so we can visit all of them without losing any score.
The total score is: 2 + 4 + 6 + 8 = 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def maxScore(self, nums: List[int], x: int) -> int:
f = [-inf] * 2
f[nums[0] & 1] = nums[0]
for v in nums[1:]:
f[v & 1] = max(f[v & 1], f[v & 1 ^ 1] - x) + v
return max(f)
|
2,786
|
Visit Array Positions to Maximize Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>x</code>.</p>
<p>You are <strong>initially</strong> at position <code>0</code> in the array and you can visit other positions according to the following rules:</p>
<ul>
<li>If you are currently in position <code>i</code>, then you can move to <strong>any</strong> position <code>j</code> such that <code>i < j</code>.</li>
<li>For each position <code>i</code> that you visit, you get a score of <code>nums[i]</code>.</li>
<li>If you move from a position <code>i</code> to a position <code>j</code> and the <strong>parities</strong> of <code>nums[i]</code> and <code>nums[j]</code> differ, then you lose a score of <code>x</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> total score you can get</em>.</p>
<p><strong>Note</strong> that initially you have <code>nums[0]</code> points.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6,1,9,2], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.
The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.
The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6,8], x = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> All the integers in the array have the same parities, so we can visit all of them without losing any score.
The total score is: 2 + 4 + 6 + 8 = 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function maxScore(nums: number[], x: number): number {
const f: number[] = Array(2).fill(-Infinity);
f[nums[0] & 1] = nums[0];
for (let i = 1; i < nums.length; ++i) {
const v = nums[i];
f[v & 1] = Math.max(f[v & 1], f[(v & 1) ^ 1] - x) + v;
}
return Math.max(...f);
}
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
C++
|
class Solution {
public:
int numberOfWays(int n, int x) {
const int mod = 1e9 + 7;
int f[n + 1][n + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
long long k = (long long) pow(i, x);
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (k <= j) {
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod;
}
}
}
return f[n][n];
}
};
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
C#
|
public class Solution {
public int NumberOfWays(int n, int x) {
const int mod = 1000000007;
int[,] f = new int[n + 1, n + 1];
f[0, 0] = 1;
for (int i = 1; i <= n; ++i) {
long k = (long)Math.Pow(i, x);
for (int j = 0; j <= n; ++j) {
f[i, j] = f[i - 1, j];
if (k <= j) {
f[i, j] = (f[i, j] + f[i - 1, j - (int)k]) % mod;
}
}
}
return f[n, n];
}
}
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
Go
|
func numberOfWays(n int, x int) int {
const mod int = 1e9 + 7
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, n+1)
}
f[0][0] = 1
for i := 1; i <= n; i++ {
k := int(math.Pow(float64(i), float64(x)))
for j := 0; j <= n; j++ {
f[i][j] = f[i-1][j]
if k <= j {
f[i][j] = (f[i][j] + f[i-1][j-k]) % mod
}
}
}
return f[n][n]
}
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
Java
|
class Solution {
public int numberOfWays(int n, int x) {
final int mod = (int) 1e9 + 7;
int[][] f = new int[n + 1][n + 1];
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
long k = (long) Math.pow(i, x);
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (k <= j) {
f[i][j] = (f[i][j] + f[i - 1][j - (int) k]) % mod;
}
}
}
return f[n][n];
}
}
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
JavaScript
|
/**
* @param {number} n
* @param {number} x
* @return {number}
*/
var numberOfWays = function (n, x) {
const mod = 10 ** 9 + 7;
const f = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= n; ++i) {
const k = Math.pow(i, x);
for (let j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (k <= j) {
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod;
}
}
}
return f[n][n];
};
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
Python
|
class Solution:
def numberOfWays(self, n: int, x: int) -> int:
mod = 10**9 + 7
f = [[0] * (n + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
k = pow(i, x)
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if k <= j:
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod
return f[n][n]
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
Rust
|
impl Solution {
pub fn number_of_ways(n: i32, x: i32) -> i32 {
const MOD: i64 = 1_000_000_007;
let n = n as usize;
let x = x as u32;
let mut f = vec![vec![0; n + 1]; n + 1];
f[0][0] = 1;
for i in 1..=n {
let k = (i as i64).pow(x);
for j in 0..=n {
f[i][j] = f[i - 1][j];
if j >= k as usize {
f[i][j] = (f[i][j] + f[i - 1][j - k as usize]) % MOD;
}
}
}
f[n][n] as i32
}
}
|
2,787
|
Ways to Express an Integer as Sum of Powers
|
Medium
|
<p>Given two <strong>positive</strong> integers <code>n</code> and <code>x</code>.</p>
<p>Return <em>the number of ways </em><code>n</code><em> can be expressed as the sum of the </em><code>x<sup>th</sup></code><em> power of <strong>unique</strong> positive integers, in other words, the number of sets of unique integers </em><code>[n<sub>1</sub>, n<sub>2</sub>, ..., n<sub>k</sub>]</code><em> where </em><code>n = n<sub>1</sub><sup>x</sup> + n<sub>2</sub><sup>x</sup> + ... + n<sub>k</sub><sup>x</sup></code><em>.</em></p>
<p>Since the result can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>For example, if <code>n = 160</code> and <code>x = 3</code>, one way to express <code>n</code> is <code>n = 2<sup>3</sup> + 3<sup>3</sup> + 5<sup>3</sup></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 10, x = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can express n as the following: n = 3<sup>2</sup> + 1<sup>2</sup> = 10.
It can be shown that it is the only way to express 10 as the sum of the 2<sup>nd</sup> power of unique integers.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 4, x = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can express n in the following ways:
- n = 4<sup>1</sup> = 4.
- n = 3<sup>1</sup> + 1<sup>1</sup> = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 300</code></li>
<li><code>1 <= x <= 5</code></li>
</ul>
|
Dynamic Programming
|
TypeScript
|
function numberOfWays(n: number, x: number): number {
const mod = 10 ** 9 + 7;
const f = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= n; ++i) {
const k = Math.pow(i, x);
for (let j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (k <= j) {
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod;
}
}
}
return f[n][n];
}
|
2,788
|
Split Strings by Separator
|
Easy
|
<p>Given an array of strings <code>words</code> and a character <code>separator</code>, <strong>split</strong> each string in <code>words</code> by <code>separator</code>.</p>
<p>Return <em>an array of strings containing the new strings formed after the splits, <strong>excluding empty strings</strong>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li><code>separator</code> is used to determine where the split should occur, but it is not included as part of the resulting strings.</li>
<li>A split may result in more than two strings.</li>
<li>The resulting strings must maintain the same order as they were initially given.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["one.two.three","four.five","six"], separator = "."
<strong>Output:</strong> ["one","two","three","four","five","six"]
<strong>Explanation: </strong>In this example we split as follows:
"one.two.three" splits into "one", "two", "three"
"four.five" splits into "four", "five"
"six" splits into "six"
Hence, the resulting array is ["one","two","three","four","five","six"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["$easy$","$problem$"], separator = "$"
<strong>Output:</strong> ["easy","problem"]
<strong>Explanation:</strong> In this example we split as follows:
"$easy$" splits into "easy" (excluding empty strings)
"$problem$" splits into "problem" (excluding empty strings)
Hence, the resulting array is ["easy","problem"].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["|||"], separator = "|"
<strong>Output:</strong> []
<strong>Explanation:</strong> In this example the resulting split of "|||" will contain only empty strings, so we return an empty array []. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li>characters in <code>words[i]</code> are either lowercase English letters or characters from the string <code>".,|$#@"</code> (excluding the quotes)</li>
<li><code>separator</code> is a character from the string <code>".,|$#@"</code> (excluding the quotes)</li>
</ul>
|
Array; String
|
C++
|
class Solution {
public:
vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
vector<string> ans;
for (const auto& w : words) {
istringstream ss(w);
string s;
while (getline(ss, s, separator)) {
if (!s.empty()) {
ans.push_back(s);
}
}
}
return ans;
}
};
|
2,788
|
Split Strings by Separator
|
Easy
|
<p>Given an array of strings <code>words</code> and a character <code>separator</code>, <strong>split</strong> each string in <code>words</code> by <code>separator</code>.</p>
<p>Return <em>an array of strings containing the new strings formed after the splits, <strong>excluding empty strings</strong>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li><code>separator</code> is used to determine where the split should occur, but it is not included as part of the resulting strings.</li>
<li>A split may result in more than two strings.</li>
<li>The resulting strings must maintain the same order as they were initially given.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["one.two.three","four.five","six"], separator = "."
<strong>Output:</strong> ["one","two","three","four","five","six"]
<strong>Explanation: </strong>In this example we split as follows:
"one.two.three" splits into "one", "two", "three"
"four.five" splits into "four", "five"
"six" splits into "six"
Hence, the resulting array is ["one","two","three","four","five","six"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["$easy$","$problem$"], separator = "$"
<strong>Output:</strong> ["easy","problem"]
<strong>Explanation:</strong> In this example we split as follows:
"$easy$" splits into "easy" (excluding empty strings)
"$problem$" splits into "problem" (excluding empty strings)
Hence, the resulting array is ["easy","problem"].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["|||"], separator = "|"
<strong>Output:</strong> []
<strong>Explanation:</strong> In this example the resulting split of "|||" will contain only empty strings, so we return an empty array []. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li>characters in <code>words[i]</code> are either lowercase English letters or characters from the string <code>".,|$#@"</code> (excluding the quotes)</li>
<li><code>separator</code> is a character from the string <code>".,|$#@"</code> (excluding the quotes)</li>
</ul>
|
Array; String
|
Go
|
func splitWordsBySeparator(words []string, separator byte) (ans []string) {
for _, w := range words {
for _, s := range strings.Split(w, string(separator)) {
if s != "" {
ans = append(ans, s)
}
}
}
return
}
|
2,788
|
Split Strings by Separator
|
Easy
|
<p>Given an array of strings <code>words</code> and a character <code>separator</code>, <strong>split</strong> each string in <code>words</code> by <code>separator</code>.</p>
<p>Return <em>an array of strings containing the new strings formed after the splits, <strong>excluding empty strings</strong>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li><code>separator</code> is used to determine where the split should occur, but it is not included as part of the resulting strings.</li>
<li>A split may result in more than two strings.</li>
<li>The resulting strings must maintain the same order as they were initially given.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["one.two.three","four.five","six"], separator = "."
<strong>Output:</strong> ["one","two","three","four","five","six"]
<strong>Explanation: </strong>In this example we split as follows:
"one.two.three" splits into "one", "two", "three"
"four.five" splits into "four", "five"
"six" splits into "six"
Hence, the resulting array is ["one","two","three","four","five","six"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["$easy$","$problem$"], separator = "$"
<strong>Output:</strong> ["easy","problem"]
<strong>Explanation:</strong> In this example we split as follows:
"$easy$" splits into "easy" (excluding empty strings)
"$problem$" splits into "problem" (excluding empty strings)
Hence, the resulting array is ["easy","problem"].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["|||"], separator = "|"
<strong>Output:</strong> []
<strong>Explanation:</strong> In this example the resulting split of "|||" will contain only empty strings, so we return an empty array []. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li>characters in <code>words[i]</code> are either lowercase English letters or characters from the string <code>".,|$#@"</code> (excluding the quotes)</li>
<li><code>separator</code> is a character from the string <code>".,|$#@"</code> (excluding the quotes)</li>
</ul>
|
Array; String
|
Java
|
import java.util.regex.Pattern;
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> ans = new ArrayList<>();
for (var w : words) {
for (var s : w.split(Pattern.quote(String.valueOf(separator)))) {
if (s.length() > 0) {
ans.add(s);
}
}
}
return ans;
}
}
|
2,788
|
Split Strings by Separator
|
Easy
|
<p>Given an array of strings <code>words</code> and a character <code>separator</code>, <strong>split</strong> each string in <code>words</code> by <code>separator</code>.</p>
<p>Return <em>an array of strings containing the new strings formed after the splits, <strong>excluding empty strings</strong>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li><code>separator</code> is used to determine where the split should occur, but it is not included as part of the resulting strings.</li>
<li>A split may result in more than two strings.</li>
<li>The resulting strings must maintain the same order as they were initially given.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["one.two.three","four.five","six"], separator = "."
<strong>Output:</strong> ["one","two","three","four","five","six"]
<strong>Explanation: </strong>In this example we split as follows:
"one.two.three" splits into "one", "two", "three"
"four.five" splits into "four", "five"
"six" splits into "six"
Hence, the resulting array is ["one","two","three","four","five","six"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["$easy$","$problem$"], separator = "$"
<strong>Output:</strong> ["easy","problem"]
<strong>Explanation:</strong> In this example we split as follows:
"$easy$" splits into "easy" (excluding empty strings)
"$problem$" splits into "problem" (excluding empty strings)
Hence, the resulting array is ["easy","problem"].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["|||"], separator = "|"
<strong>Output:</strong> []
<strong>Explanation:</strong> In this example the resulting split of "|||" will contain only empty strings, so we return an empty array []. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li>characters in <code>words[i]</code> are either lowercase English letters or characters from the string <code>".,|$#@"</code> (excluding the quotes)</li>
<li><code>separator</code> is a character from the string <code>".,|$#@"</code> (excluding the quotes)</li>
</ul>
|
Array; String
|
Python
|
class Solution:
def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
return [s for w in words for s in w.split(separator) if s]
|
2,788
|
Split Strings by Separator
|
Easy
|
<p>Given an array of strings <code>words</code> and a character <code>separator</code>, <strong>split</strong> each string in <code>words</code> by <code>separator</code>.</p>
<p>Return <em>an array of strings containing the new strings formed after the splits, <strong>excluding empty strings</strong>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li><code>separator</code> is used to determine where the split should occur, but it is not included as part of the resulting strings.</li>
<li>A split may result in more than two strings.</li>
<li>The resulting strings must maintain the same order as they were initially given.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["one.two.three","four.five","six"], separator = "."
<strong>Output:</strong> ["one","two","three","four","five","six"]
<strong>Explanation: </strong>In this example we split as follows:
"one.two.three" splits into "one", "two", "three"
"four.five" splits into "four", "five"
"six" splits into "six"
Hence, the resulting array is ["one","two","three","four","five","six"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["$easy$","$problem$"], separator = "$"
<strong>Output:</strong> ["easy","problem"]
<strong>Explanation:</strong> In this example we split as follows:
"$easy$" splits into "easy" (excluding empty strings)
"$problem$" splits into "problem" (excluding empty strings)
Hence, the resulting array is ["easy","problem"].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["|||"], separator = "|"
<strong>Output:</strong> []
<strong>Explanation:</strong> In this example the resulting split of "|||" will contain only empty strings, so we return an empty array []. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 20</code></li>
<li>characters in <code>words[i]</code> are either lowercase English letters or characters from the string <code>".,|$#@"</code> (excluding the quotes)</li>
<li><code>separator</code> is a character from the string <code>".,|$#@"</code> (excluding the quotes)</li>
</ul>
|
Array; String
|
TypeScript
|
function splitWordsBySeparator(words: string[], separator: string): string[] {
return words.flatMap(w => w.split(separator).filter(s => s.length > 0));
}
|
2,789
|
Largest Element in an Array after Merge Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p>
<p>You can do the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> such that <code>0 <= i < nums.length - 1</code> and <code>nums[i] <= nums[i + 1]</code>. Replace the element <code>nums[i + 1]</code> with <code>nums[i] + nums[i + 1]</code> and delete the element <code>nums[i]</code> from the array.</li>
</ul>
<p>Return <em>the value of the <b>largest</b> element that you can possibly obtain in the final array.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,7,9,3]
<strong>Output:</strong> 21
<strong>Explanation:</strong> We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [<u>5</u>,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,<u>16</u>,3].
- Choose i = 0. The resulting array will be nums = [<u>21</u>,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,3]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,<u>6</u>].
- Choose i = 0. The resulting array will be nums = [<u>11</u>].
There is only one element in the final array, which is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
long long maxArrayValue(vector<int>& nums) {
int n = nums.size();
long long ans = nums[n - 1], t = nums[n - 1];
for (int i = n - 2; ~i; --i) {
if (nums[i] <= t) {
t += nums[i];
} else {
t = nums[i];
}
ans = max(ans, t);
}
return ans;
}
};
|
2,789
|
Largest Element in an Array after Merge Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p>
<p>You can do the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> such that <code>0 <= i < nums.length - 1</code> and <code>nums[i] <= nums[i + 1]</code>. Replace the element <code>nums[i + 1]</code> with <code>nums[i] + nums[i + 1]</code> and delete the element <code>nums[i]</code> from the array.</li>
</ul>
<p>Return <em>the value of the <b>largest</b> element that you can possibly obtain in the final array.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,7,9,3]
<strong>Output:</strong> 21
<strong>Explanation:</strong> We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [<u>5</u>,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,<u>16</u>,3].
- Choose i = 0. The resulting array will be nums = [<u>21</u>,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,3]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,<u>6</u>].
- Choose i = 0. The resulting array will be nums = [<u>11</u>].
There is only one element in the final array, which is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Go
|
func maxArrayValue(nums []int) int64 {
n := len(nums)
ans, t := nums[n-1], nums[n-1]
for i := n - 2; i >= 0; i-- {
if nums[i] <= t {
t += nums[i]
} else {
t = nums[i]
}
ans = max(ans, t)
}
return int64(ans)
}
|
2,789
|
Largest Element in an Array after Merge Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p>
<p>You can do the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> such that <code>0 <= i < nums.length - 1</code> and <code>nums[i] <= nums[i + 1]</code>. Replace the element <code>nums[i + 1]</code> with <code>nums[i] + nums[i + 1]</code> and delete the element <code>nums[i]</code> from the array.</li>
</ul>
<p>Return <em>the value of the <b>largest</b> element that you can possibly obtain in the final array.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,7,9,3]
<strong>Output:</strong> 21
<strong>Explanation:</strong> We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [<u>5</u>,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,<u>16</u>,3].
- Choose i = 0. The resulting array will be nums = [<u>21</u>,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,3]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,<u>6</u>].
- Choose i = 0. The resulting array will be nums = [<u>11</u>].
There is only one element in the final array, which is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public long maxArrayValue(int[] nums) {
int n = nums.length;
long ans = nums[n - 1], t = nums[n - 1];
for (int i = n - 2; i >= 0; --i) {
if (nums[i] <= t) {
t += nums[i];
} else {
t = nums[i];
}
ans = Math.max(ans, t);
}
return ans;
}
}
|
2,789
|
Largest Element in an Array after Merge Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p>
<p>You can do the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> such that <code>0 <= i < nums.length - 1</code> and <code>nums[i] <= nums[i + 1]</code>. Replace the element <code>nums[i + 1]</code> with <code>nums[i] + nums[i + 1]</code> and delete the element <code>nums[i]</code> from the array.</li>
</ul>
<p>Return <em>the value of the <b>largest</b> element that you can possibly obtain in the final array.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,7,9,3]
<strong>Output:</strong> 21
<strong>Explanation:</strong> We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [<u>5</u>,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,<u>16</u>,3].
- Choose i = 0. The resulting array will be nums = [<u>21</u>,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,3]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,<u>6</u>].
- Choose i = 0. The resulting array will be nums = [<u>11</u>].
There is only one element in the final array, which is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def maxArrayValue(self, nums: List[int]) -> int:
for i in range(len(nums) - 2, -1, -1):
if nums[i] <= nums[i + 1]:
nums[i] += nums[i + 1]
return max(nums)
|
2,789
|
Largest Element in an Array after Merge Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p>
<p>You can do the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> such that <code>0 <= i < nums.length - 1</code> and <code>nums[i] <= nums[i + 1]</code>. Replace the element <code>nums[i + 1]</code> with <code>nums[i] + nums[i + 1]</code> and delete the element <code>nums[i]</code> from the array.</li>
</ul>
<p>Return <em>the value of the <b>largest</b> element that you can possibly obtain in the final array.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,7,9,3]
<strong>Output:</strong> 21
<strong>Explanation:</strong> We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [<u>5</u>,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,<u>16</u>,3].
- Choose i = 0. The resulting array will be nums = [<u>21</u>,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,3]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,<u>6</u>].
- Choose i = 0. The resulting array will be nums = [<u>11</u>].
There is only one element in the final array, which is 11.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
TypeScript
|
function maxArrayValue(nums: number[]): number {
for (let i = nums.length - 2; i >= 0; --i) {
if (nums[i] <= nums[i + 1]) {
nums[i] += nums[i + 1];
}
}
return Math.max(...nums);
}
|
2,790
|
Maximum Number of Groups With Increasing Length
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>usageLimits</code> of length <code>n</code>.</p>
<p>Your task is to create <strong>groups</strong> using numbers from <code>0</code> to <code>n - 1</code>, ensuring that each number, <code>i</code>, is used no more than <code>usageLimits[i]</code> times in total <strong>across all groups</strong>. You must also satisfy the following conditions:</p>
<ul>
<li>Each group must consist of <strong>distinct </strong>numbers, meaning that no duplicate numbers are allowed within a single group.</li>
<li>Each group (except the first one) must have a length <strong>strictly greater</strong> than the previous group.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of groups you can create while satisfying these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,2,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [2].
Group 2 contains the numbers [1,2].
Group 3 contains the numbers [0,1,2].
It can be shown that the maximum number of groups is 3.
So, the output is 3. </pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [2,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
Group 2 contains the numbers [1,2].
It can be shown that the maximum number of groups is 2.
So, the output is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can use both 0 and 1 at most once.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
It can be shown that the maximum number of groups is 1.
So, the output is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= usageLimits.length <= 10<sup>5</sup></code></li>
<li><code>1 <= usageLimits[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Binary Search; Sorting
|
C++
|
class Solution {
public:
int maxIncreasingGroups(vector<int>& usageLimits) {
sort(usageLimits.begin(), usageLimits.end());
int k = 0;
long long s = 0;
for (int x : usageLimits) {
s += x;
if (s > k) {
++k;
s -= k;
}
}
return k;
}
};
|
2,790
|
Maximum Number of Groups With Increasing Length
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>usageLimits</code> of length <code>n</code>.</p>
<p>Your task is to create <strong>groups</strong> using numbers from <code>0</code> to <code>n - 1</code>, ensuring that each number, <code>i</code>, is used no more than <code>usageLimits[i]</code> times in total <strong>across all groups</strong>. You must also satisfy the following conditions:</p>
<ul>
<li>Each group must consist of <strong>distinct </strong>numbers, meaning that no duplicate numbers are allowed within a single group.</li>
<li>Each group (except the first one) must have a length <strong>strictly greater</strong> than the previous group.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of groups you can create while satisfying these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,2,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [2].
Group 2 contains the numbers [1,2].
Group 3 contains the numbers [0,1,2].
It can be shown that the maximum number of groups is 3.
So, the output is 3. </pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [2,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
Group 2 contains the numbers [1,2].
It can be shown that the maximum number of groups is 2.
So, the output is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can use both 0 and 1 at most once.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
It can be shown that the maximum number of groups is 1.
So, the output is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= usageLimits.length <= 10<sup>5</sup></code></li>
<li><code>1 <= usageLimits[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Binary Search; Sorting
|
Go
|
func maxIncreasingGroups(usageLimits []int) int {
sort.Ints(usageLimits)
s, k := 0, 0
for _, x := range usageLimits {
s += x
if s > k {
k++
s -= k
}
}
return k
}
|
2,790
|
Maximum Number of Groups With Increasing Length
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>usageLimits</code> of length <code>n</code>.</p>
<p>Your task is to create <strong>groups</strong> using numbers from <code>0</code> to <code>n - 1</code>, ensuring that each number, <code>i</code>, is used no more than <code>usageLimits[i]</code> times in total <strong>across all groups</strong>. You must also satisfy the following conditions:</p>
<ul>
<li>Each group must consist of <strong>distinct </strong>numbers, meaning that no duplicate numbers are allowed within a single group.</li>
<li>Each group (except the first one) must have a length <strong>strictly greater</strong> than the previous group.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of groups you can create while satisfying these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,2,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [2].
Group 2 contains the numbers [1,2].
Group 3 contains the numbers [0,1,2].
It can be shown that the maximum number of groups is 3.
So, the output is 3. </pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [2,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
Group 2 contains the numbers [1,2].
It can be shown that the maximum number of groups is 2.
So, the output is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can use both 0 and 1 at most once.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
It can be shown that the maximum number of groups is 1.
So, the output is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= usageLimits.length <= 10<sup>5</sup></code></li>
<li><code>1 <= usageLimits[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Binary Search; Sorting
|
Java
|
class Solution {
public int maxIncreasingGroups(List<Integer> usageLimits) {
Collections.sort(usageLimits);
int k = 0;
long s = 0;
for (int x : usageLimits) {
s += x;
if (s > k) {
++k;
s -= k;
}
}
return k;
}
}
|
2,790
|
Maximum Number of Groups With Increasing Length
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>usageLimits</code> of length <code>n</code>.</p>
<p>Your task is to create <strong>groups</strong> using numbers from <code>0</code> to <code>n - 1</code>, ensuring that each number, <code>i</code>, is used no more than <code>usageLimits[i]</code> times in total <strong>across all groups</strong>. You must also satisfy the following conditions:</p>
<ul>
<li>Each group must consist of <strong>distinct </strong>numbers, meaning that no duplicate numbers are allowed within a single group.</li>
<li>Each group (except the first one) must have a length <strong>strictly greater</strong> than the previous group.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of groups you can create while satisfying these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,2,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [2].
Group 2 contains the numbers [1,2].
Group 3 contains the numbers [0,1,2].
It can be shown that the maximum number of groups is 3.
So, the output is 3. </pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [2,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
Group 2 contains the numbers [1,2].
It can be shown that the maximum number of groups is 2.
So, the output is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can use both 0 and 1 at most once.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
It can be shown that the maximum number of groups is 1.
So, the output is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= usageLimits.length <= 10<sup>5</sup></code></li>
<li><code>1 <= usageLimits[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Binary Search; Sorting
|
Python
|
class Solution:
def maxIncreasingGroups(self, usageLimits: List[int]) -> int:
usageLimits.sort()
k, n = 0, len(usageLimits)
for i in range(n):
if usageLimits[i] > k:
k += 1
usageLimits[i] -= k
if i + 1 < n:
usageLimits[i + 1] += usageLimits[i]
return k
|
2,790
|
Maximum Number of Groups With Increasing Length
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>usageLimits</code> of length <code>n</code>.</p>
<p>Your task is to create <strong>groups</strong> using numbers from <code>0</code> to <code>n - 1</code>, ensuring that each number, <code>i</code>, is used no more than <code>usageLimits[i]</code> times in total <strong>across all groups</strong>. You must also satisfy the following conditions:</p>
<ul>
<li>Each group must consist of <strong>distinct </strong>numbers, meaning that no duplicate numbers are allowed within a single group.</li>
<li>Each group (except the first one) must have a length <strong>strictly greater</strong> than the previous group.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of groups you can create while satisfying these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,2,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [2].
Group 2 contains the numbers [1,2].
Group 3 contains the numbers [0,1,2].
It can be shown that the maximum number of groups is 3.
So, the output is 3. </pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [2,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
Group 2 contains the numbers [1,2].
It can be shown that the maximum number of groups is 2.
So, the output is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> <code>usageLimits</code> = [1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can use both 0 and 1 at most once.
One way of creating the maximum number of groups while satisfying the conditions is:
Group 1 contains the number [0].
It can be shown that the maximum number of groups is 1.
So, the output is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= usageLimits.length <= 10<sup>5</sup></code></li>
<li><code>1 <= usageLimits[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Binary Search; Sorting
|
TypeScript
|
function maxIncreasingGroups(usageLimits: number[]): number {
usageLimits.sort((a, b) => a - b);
let k = 0;
let s = 0;
for (const x of usageLimits) {
s += x;
if (s > k) {
++k;
s -= k;
}
}
return k;
}
|
2,791
|
Count Paths That Can Form a Palindrome in a Tree
|
Hard
|
<p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>
<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to the edge between <code>i</code> and <code>parent[i]</code>. <code>s[0]</code> can be ignored.</p>
<p>Return <em>the number of pairs of nodes </em><code>(u, v)</code><em> such that </em><code>u < v</code><em> and the characters assigned to edges on the path from </em><code>u</code><em> to </em><code>v</code><em> can be <strong>rearranged</strong> to form a <strong>palindrome</strong></em>.</p>
<p>A string is a <strong>palindrome</strong> when it reads the same backwards as forwards.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2791.Count%20Paths%20That%20Can%20Form%20a%20Palindrome%20in%20a%20Tree/images/treedrawio-8drawio.png" style="width: 281px; height: 181px;" /></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,1,1,2], s = "acaabc"
<strong>Output:</strong> 8
<strong>Explanation:</strong> The valid pairs are:
- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.
- The pair (2,3) result in the string "aca" which is a palindrome.
- The pair (1,5) result in the string "cac" which is a palindrome.
- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,0,0], s = "aaaaa"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Any pair of nodes (u,v) where u < v is valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == parent.length == s.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= parent[i] <= n - 1</code> for all <code>i >= 1</code></li>
<li><code>parent[0] == -1</code></li>
<li><code>parent</code> represents a valid tree.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Dynamic Programming; Bitmask
|
C++
|
class Solution {
public:
long long countPalindromePaths(vector<int>& parent, string s) {
int n = parent.size();
vector<vector<pair<int, int>>> g(n);
unordered_map<int, int> cnt;
cnt[0] = 1;
for (int i = 1; i < n; ++i) {
int p = parent[i];
g[p].emplace_back(i, 1 << (s[i] - 'a'));
}
long long ans = 0;
function<void(int, int)> dfs = [&](int i, int xo) {
for (auto [j, v] : g[i]) {
int x = xo ^ v;
ans += cnt[x];
for (int k = 0; k < 26; ++k) {
ans += cnt[x ^ (1 << k)];
}
++cnt[x];
dfs(j, x);
}
};
dfs(0, 0);
return ans;
}
};
|
2,791
|
Count Paths That Can Form a Palindrome in a Tree
|
Hard
|
<p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>
<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to the edge between <code>i</code> and <code>parent[i]</code>. <code>s[0]</code> can be ignored.</p>
<p>Return <em>the number of pairs of nodes </em><code>(u, v)</code><em> such that </em><code>u < v</code><em> and the characters assigned to edges on the path from </em><code>u</code><em> to </em><code>v</code><em> can be <strong>rearranged</strong> to form a <strong>palindrome</strong></em>.</p>
<p>A string is a <strong>palindrome</strong> when it reads the same backwards as forwards.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2791.Count%20Paths%20That%20Can%20Form%20a%20Palindrome%20in%20a%20Tree/images/treedrawio-8drawio.png" style="width: 281px; height: 181px;" /></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,1,1,2], s = "acaabc"
<strong>Output:</strong> 8
<strong>Explanation:</strong> The valid pairs are:
- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.
- The pair (2,3) result in the string "aca" which is a palindrome.
- The pair (1,5) result in the string "cac" which is a palindrome.
- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,0,0], s = "aaaaa"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Any pair of nodes (u,v) where u < v is valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == parent.length == s.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= parent[i] <= n - 1</code> for all <code>i >= 1</code></li>
<li><code>parent[0] == -1</code></li>
<li><code>parent</code> represents a valid tree.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Dynamic Programming; Bitmask
|
Go
|
func countPalindromePaths(parent []int, s string) (ans int64) {
type pair struct{ i, v int }
n := len(parent)
g := make([][]pair, n)
for i := 1; i < n; i++ {
p := parent[i]
g[p] = append(g[p], pair{i, 1 << (s[i] - 'a')})
}
cnt := map[int]int{0: 1}
var dfs func(i, xor int)
dfs = func(i, xor int) {
for _, e := range g[i] {
x := xor ^ e.v
ans += int64(cnt[x])
for k := 0; k < 26; k++ {
ans += int64(cnt[x^(1<<k)])
}
cnt[x]++
dfs(e.i, x)
}
}
dfs(0, 0)
return
}
|
2,791
|
Count Paths That Can Form a Palindrome in a Tree
|
Hard
|
<p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>
<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to the edge between <code>i</code> and <code>parent[i]</code>. <code>s[0]</code> can be ignored.</p>
<p>Return <em>the number of pairs of nodes </em><code>(u, v)</code><em> such that </em><code>u < v</code><em> and the characters assigned to edges on the path from </em><code>u</code><em> to </em><code>v</code><em> can be <strong>rearranged</strong> to form a <strong>palindrome</strong></em>.</p>
<p>A string is a <strong>palindrome</strong> when it reads the same backwards as forwards.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2791.Count%20Paths%20That%20Can%20Form%20a%20Palindrome%20in%20a%20Tree/images/treedrawio-8drawio.png" style="width: 281px; height: 181px;" /></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,1,1,2], s = "acaabc"
<strong>Output:</strong> 8
<strong>Explanation:</strong> The valid pairs are:
- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.
- The pair (2,3) result in the string "aca" which is a palindrome.
- The pair (1,5) result in the string "cac" which is a palindrome.
- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,0,0], s = "aaaaa"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Any pair of nodes (u,v) where u < v is valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == parent.length == s.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= parent[i] <= n - 1</code> for all <code>i >= 1</code></li>
<li><code>parent[0] == -1</code></li>
<li><code>parent</code> represents a valid tree.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Dynamic Programming; Bitmask
|
Java
|
class Solution {
private List<int[]>[] g;
private Map<Integer, Integer> cnt = new HashMap<>();
private long ans;
public long countPalindromePaths(List<Integer> parent, String s) {
int n = parent.size();
g = new List[n];
cnt.put(0, 1);
Arrays.setAll(g, k -> new ArrayList<>());
for (int i = 1; i < n; ++i) {
int p = parent.get(i);
g[p].add(new int[] {i, 1 << (s.charAt(i) - 'a')});
}
dfs(0, 0);
return ans;
}
private void dfs(int i, int xor) {
for (int[] e : g[i]) {
int j = e[0], v = e[1];
int x = xor ^ v;
ans += cnt.getOrDefault(x, 0);
for (int k = 0; k < 26; ++k) {
ans += cnt.getOrDefault(x ^ (1 << k), 0);
}
cnt.merge(x, 1, Integer::sum);
dfs(j, x);
}
}
}
|
2,791
|
Count Paths That Can Form a Palindrome in a Tree
|
Hard
|
<p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>
<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to the edge between <code>i</code> and <code>parent[i]</code>. <code>s[0]</code> can be ignored.</p>
<p>Return <em>the number of pairs of nodes </em><code>(u, v)</code><em> such that </em><code>u < v</code><em> and the characters assigned to edges on the path from </em><code>u</code><em> to </em><code>v</code><em> can be <strong>rearranged</strong> to form a <strong>palindrome</strong></em>.</p>
<p>A string is a <strong>palindrome</strong> when it reads the same backwards as forwards.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2791.Count%20Paths%20That%20Can%20Form%20a%20Palindrome%20in%20a%20Tree/images/treedrawio-8drawio.png" style="width: 281px; height: 181px;" /></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,1,1,2], s = "acaabc"
<strong>Output:</strong> 8
<strong>Explanation:</strong> The valid pairs are:
- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.
- The pair (2,3) result in the string "aca" which is a palindrome.
- The pair (1,5) result in the string "cac" which is a palindrome.
- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,0,0], s = "aaaaa"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Any pair of nodes (u,v) where u < v is valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == parent.length == s.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= parent[i] <= n - 1</code> for all <code>i >= 1</code></li>
<li><code>parent[0] == -1</code></li>
<li><code>parent</code> represents a valid tree.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Dynamic Programming; Bitmask
|
Python
|
class Solution:
def countPalindromePaths(self, parent: List[int], s: str) -> int:
def dfs(i: int, xor: int):
nonlocal ans
for j, v in g[i]:
x = xor ^ v
ans += cnt[x]
for k in range(26):
ans += cnt[x ^ (1 << k)]
cnt[x] += 1
dfs(j, x)
n = len(parent)
g = defaultdict(list)
for i in range(1, n):
p = parent[i]
g[p].append((i, 1 << (ord(s[i]) - ord('a'))))
ans = 0
cnt = Counter({0: 1})
dfs(0, 0)
return ans
|
2,791
|
Count Paths That Can Form a Palindrome in a Tree
|
Hard
|
<p>You are given a <strong>tree</strong> (i.e. a connected, undirected graph that has no cycles) <strong>rooted</strong> at node <code>0</code> consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by a <strong>0-indexed</strong> array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node <code>0</code> is the root, <code>parent[0] == -1</code>.</p>
<p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to the edge between <code>i</code> and <code>parent[i]</code>. <code>s[0]</code> can be ignored.</p>
<p>Return <em>the number of pairs of nodes </em><code>(u, v)</code><em> such that </em><code>u < v</code><em> and the characters assigned to edges on the path from </em><code>u</code><em> to </em><code>v</code><em> can be <strong>rearranged</strong> to form a <strong>palindrome</strong></em>.</p>
<p>A string is a <strong>palindrome</strong> when it reads the same backwards as forwards.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2791.Count%20Paths%20That%20Can%20Form%20a%20Palindrome%20in%20a%20Tree/images/treedrawio-8drawio.png" style="width: 281px; height: 181px;" /></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,1,1,2], s = "acaabc"
<strong>Output:</strong> 8
<strong>Explanation:</strong> The valid pairs are:
- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.
- The pair (2,3) result in the string "aca" which is a palindrome.
- The pair (1,5) result in the string "cac" which is a palindrome.
- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> parent = [-1,0,0,0,0], s = "aaaaa"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Any pair of nodes (u,v) where u < v is valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == parent.length == s.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= parent[i] <= n - 1</code> for all <code>i >= 1</code></li>
<li><code>parent[0] == -1</code></li>
<li><code>parent</code> represents a valid tree.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Dynamic Programming; Bitmask
|
TypeScript
|
function countPalindromePaths(parent: number[], s: string): number {
const n = parent.length;
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (let i = 1; i < n; ++i) {
g[parent[i]].push([i, 1 << (s.charCodeAt(i) - 97)]);
}
const cnt: Map<number, number> = new Map();
cnt.set(0, 1);
let ans = 0;
const dfs = (i: number, xor: number): void => {
for (const [j, v] of g[i]) {
const x = xor ^ v;
ans += cnt.get(x) || 0;
for (let k = 0; k < 26; ++k) {
ans += cnt.get(x ^ (1 << k)) || 0;
}
cnt.set(x, (cnt.get(x) || 0) + 1);
dfs(j, x);
}
};
dfs(0, 0);
return ans;
}
|
2,792
|
Count Nodes That Are Great Enough
|
Hard
|
<p>You are given a <code>root</code> to a binary tree and an integer <code>k</code>. A node of this tree is called <strong>great enough</strong> if the followings hold:</p>
<ul>
<li>Its subtree has <strong>at least</strong> <code>k</code> nodes.</li>
<li>Its value is <b>greater</b> than the value of <strong>at least</strong> <code>k</code> nodes in its subtree.</li>
</ul>
<p>Return<em> the number of nodes in this tree that are great enough.</em></p>
<p>The node <code>u</code> is in the <strong>subtree</strong> of the node <code>v</code>, if <code><font face="monospace">u == v</font></code> or <code>v</code> is an ancestor of <code>u</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> root = [7,6,5,4,3,2,1], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Number the nodes from 1 to 7.
The values in the subtree of node 1: {1,2,3,4,5,6,7}. Since node.val == 7, there are 6 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {3,4,6}. Since node.val == 6, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 3: {1,2,5}. Since node.val == 5, there are 2 nodes having a smaller value than its value. So it's great enough.
It can be shown that other nodes are not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 167px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3], k = 1
<strong>Output:</strong> 0
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {1,2,3}. Since node.val == 1, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {3}. Since node.val == 3, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> root = [3,2,2], k = 2
<strong>Output:</strong> 1
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {2,2,3}. Since node.val == 3, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.<span style="display: none;"> </span></li>
<li><code>1 <= Node.val <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10</code></li>
</ul>
|
Tree; Depth-First Search; Divide and Conquer; Binary Tree
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countGreatEnoughNodes(TreeNode* root, int k) {
int ans = 0;
function<priority_queue<int>(TreeNode*)> dfs = [&](TreeNode* root) {
if (!root) {
return priority_queue<int>();
}
auto left = dfs(root->left);
auto right = dfs(root->right);
while (right.size()) {
left.push(right.top());
right.pop();
if (left.size() > k) {
left.pop();
}
}
if (left.size() == k && left.top() < root->val) {
++ans;
}
left.push(root->val);
if (left.size() > k) {
left.pop();
}
return left;
};
dfs(root);
return ans;
}
};
|
2,792
|
Count Nodes That Are Great Enough
|
Hard
|
<p>You are given a <code>root</code> to a binary tree and an integer <code>k</code>. A node of this tree is called <strong>great enough</strong> if the followings hold:</p>
<ul>
<li>Its subtree has <strong>at least</strong> <code>k</code> nodes.</li>
<li>Its value is <b>greater</b> than the value of <strong>at least</strong> <code>k</code> nodes in its subtree.</li>
</ul>
<p>Return<em> the number of nodes in this tree that are great enough.</em></p>
<p>The node <code>u</code> is in the <strong>subtree</strong> of the node <code>v</code>, if <code><font face="monospace">u == v</font></code> or <code>v</code> is an ancestor of <code>u</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> root = [7,6,5,4,3,2,1], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Number the nodes from 1 to 7.
The values in the subtree of node 1: {1,2,3,4,5,6,7}. Since node.val == 7, there are 6 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {3,4,6}. Since node.val == 6, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 3: {1,2,5}. Since node.val == 5, there are 2 nodes having a smaller value than its value. So it's great enough.
It can be shown that other nodes are not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 167px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3], k = 1
<strong>Output:</strong> 0
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {1,2,3}. Since node.val == 1, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {3}. Since node.val == 3, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> root = [3,2,2], k = 2
<strong>Output:</strong> 1
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {2,2,3}. Since node.val == 3, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.<span style="display: none;"> </span></li>
<li><code>1 <= Node.val <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10</code></li>
</ul>
|
Tree; Depth-First Search; Divide and Conquer; Binary Tree
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func countGreatEnoughNodes(root *TreeNode, k int) (ans int) {
var dfs func(*TreeNode) hp
dfs = func(root *TreeNode) hp {
if root == nil {
return hp{}
}
l, r := dfs(root.Left), dfs(root.Right)
for _, x := range r.IntSlice {
l.push(x)
if l.Len() > k {
l.pop()
}
}
if l.Len() == k && root.Val > l.IntSlice[0] {
ans++
}
l.push(root.Val)
if l.Len() > k {
l.pop()
}
return l
}
dfs(root)
return
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
|
2,792
|
Count Nodes That Are Great Enough
|
Hard
|
<p>You are given a <code>root</code> to a binary tree and an integer <code>k</code>. A node of this tree is called <strong>great enough</strong> if the followings hold:</p>
<ul>
<li>Its subtree has <strong>at least</strong> <code>k</code> nodes.</li>
<li>Its value is <b>greater</b> than the value of <strong>at least</strong> <code>k</code> nodes in its subtree.</li>
</ul>
<p>Return<em> the number of nodes in this tree that are great enough.</em></p>
<p>The node <code>u</code> is in the <strong>subtree</strong> of the node <code>v</code>, if <code><font face="monospace">u == v</font></code> or <code>v</code> is an ancestor of <code>u</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> root = [7,6,5,4,3,2,1], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Number the nodes from 1 to 7.
The values in the subtree of node 1: {1,2,3,4,5,6,7}. Since node.val == 7, there are 6 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {3,4,6}. Since node.val == 6, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 3: {1,2,5}. Since node.val == 5, there are 2 nodes having a smaller value than its value. So it's great enough.
It can be shown that other nodes are not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 167px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3], k = 1
<strong>Output:</strong> 0
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {1,2,3}. Since node.val == 1, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {3}. Since node.val == 3, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> root = [3,2,2], k = 2
<strong>Output:</strong> 1
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {2,2,3}. Since node.val == 3, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.<span style="display: none;"> </span></li>
<li><code>1 <= Node.val <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10</code></li>
</ul>
|
Tree; Depth-First Search; Divide and Conquer; Binary Tree
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans;
private int k;
public int countGreatEnoughNodes(TreeNode root, int k) {
this.k = k;
dfs(root);
return ans;
}
private PriorityQueue<Integer> dfs(TreeNode root) {
if (root == null) {
return new PriorityQueue<>(Comparator.reverseOrder());
}
var l = dfs(root.left);
var r = dfs(root.right);
for (int x : r) {
l.offer(x);
if (l.size() > k) {
l.poll();
}
}
if (l.size() == k && l.peek() < root.val) {
++ans;
}
l.offer(root.val);
if (l.size() > k) {
l.poll();
}
return l;
}
}
|
2,792
|
Count Nodes That Are Great Enough
|
Hard
|
<p>You are given a <code>root</code> to a binary tree and an integer <code>k</code>. A node of this tree is called <strong>great enough</strong> if the followings hold:</p>
<ul>
<li>Its subtree has <strong>at least</strong> <code>k</code> nodes.</li>
<li>Its value is <b>greater</b> than the value of <strong>at least</strong> <code>k</code> nodes in its subtree.</li>
</ul>
<p>Return<em> the number of nodes in this tree that are great enough.</em></p>
<p>The node <code>u</code> is in the <strong>subtree</strong> of the node <code>v</code>, if <code><font face="monospace">u == v</font></code> or <code>v</code> is an ancestor of <code>u</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> root = [7,6,5,4,3,2,1], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Number the nodes from 1 to 7.
The values in the subtree of node 1: {1,2,3,4,5,6,7}. Since node.val == 7, there are 6 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {3,4,6}. Since node.val == 6, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 3: {1,2,5}. Since node.val == 5, there are 2 nodes having a smaller value than its value. So it's great enough.
It can be shown that other nodes are not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 167px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3], k = 1
<strong>Output:</strong> 0
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {1,2,3}. Since node.val == 1, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {3}. Since node.val == 3, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> root = [3,2,2], k = 2
<strong>Output:</strong> 1
<strong>Explanation: </strong>Number the nodes from 1 to 3.
The values in the subtree of node 1: {2,2,3}. Since node.val == 3, there are 2 nodes having a smaller value than its value. So it's great enough.
The values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
The values in the subtree of node 3: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.
See the picture below for a better understanding.</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2792.Count%20Nodes%20That%20Are%20Great%20Enough/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 123px; height: 101px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.<span style="display: none;"> </span></li>
<li><code>1 <= Node.val <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10</code></li>
</ul>
|
Tree; Depth-First Search; Divide and Conquer; Binary Tree
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countGreatEnoughNodes(self, root: Optional[TreeNode], k: int) -> int:
def push(pq, x):
heappush(pq, x)
if len(pq) > k:
heappop(pq)
def dfs(root):
if root is None:
return []
l, r = dfs(root.left), dfs(root.right)
for x in r:
push(l, x)
if len(l) == k and -l[0] < root.val:
nonlocal ans
ans += 1
push(l, -root.val)
return l
ans = 0
dfs(root)
return ans
|
2,793
|
Status of Flight Tickets
|
Hard
|
<p>Table: <code><font face="monospace">Flights</font></code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| flight_id | int |
| capacity | int |
+-------------+------+
<code>flight_id</code> column contains distinct values.
Each row of this table contains flight id and capacity.
</pre>
<p>Table: <code>Passengers</code></p>
<pre>
+--------------+----------+
| Column Name | Type |
+--------------+----------+
| passenger_id | int |
| flight_id | int |
| booking_time | datetime |
+--------------+----------+
passenger_id column contains distinct values.
booking_time column contains distinct values.
Each row of this table contains passenger id, booking time, and their flight id.
</pre>
<p>Passengers book tickets for flights in advance. If a passenger books a ticket for a flight and there are still empty seats available on the flight, the passenger's ticket will be <strong>confirmed</strong>. However, the passenger will be on a <strong>waitlist</strong> if the flight is already at full capacity.</p>
<p>Write a solution to determine the current status of flight tickets for each passenger.</p>
<p>Return the result table ordered by <code>passenger_id</code> <em>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>
Flights table:
+-----------+----------+
| flight_id | capacity |
+-----------+----------+
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
+-----------+----------+
Passengers table:
+--------------+-----------+---------------------+
| passenger_id | flight_id | booking_time |
+--------------+-----------+---------------------+
| 101 | 1 | 2023-07-10 16:30:00 |
| 102 | 1 | 2023-07-10 17:45:00 |
| 103 | 1 | 2023-07-10 12:00:00 |
| 104 | 2 | 2023-07-05 13:23:00 |
| 105 | 2 | 2023-07-05 09:00:00 |
| 106 | 3 | 2023-07-08 11:10:00 |
| 107 | 3 | 2023-07-08 09:10:00 |
+--------------+-----------+---------------------+
<strong>Output:</strong>
+--------------+-----------+
| passenger_id | Status |
+--------------+-----------+
| 101 | Confirmed |
| 102 | Waitlist |
| 103 | Confirmed |
| 104 | Confirmed |
| 105 | Confirmed |
| 106 | Waitlist |
| 107 | Confirmed |
+--------------+-----------+
<strong>Explanation:</strong>
- Flight 1 has a capacity of 2 passengers. Passenger 101 and Passenger 103 were the first to book tickets, securing the available seats. Therefore, their bookings are confirmed. However, Passenger 102 was the third person to book a ticket for this flight, which means there are no more available seats. Passenger 102 is now placed on the waitlist,
- Flight 2 has a capacity of 2 passengers, Flight 2 has exactly two passengers who booked tickets, Passenger 104 and Passenger 105. Since the number of passengers who booked tickets matches the available seats, both bookings are confirmed.
- Flight 3 has a capacity of 1 passenger. Passenger 107 booked earlier and secured the only available seat, confirming their booking. Passenger 106, who booked after Passenger 107, is on the waitlist.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
passenger_id,
IF(
(
RANK() OVER (
PARTITION BY flight_id
ORDER BY booking_time
)
) <= capacity,
'Confirmed',
'Waitlist'
) AS Status
FROM
Passengers
JOIN Flights USING (flight_id)
ORDER BY passenger_id;
|
2,794
|
Create Object from Two Arrays
|
Easy
|
<p>Given two arrays <code>keysArr</code> and <code>valuesArr</code>, return a new object <code>obj</code>. Each key-value pair in <code>obj</code> should come from <code>keysArr[i]</code> and <code>valuesArr[i]</code>.</p>
<p>If a duplicate key exists at a previous index, that key-value should be excluded. In other words, only the first key should be added to the object.</p>
<p>If the key is not a string, it should be converted into a string by calling <code>String()</code> on it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
<strong>Output:</strong> {"a": 1, "b": 2, "c": 3}
<strong>Explanation:</strong> The keys "a", "b", and "c" are paired with the values 1, 2, and 3 respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> keysArr = ["1", 1, false], valuesArr = [4, 5, 6]
<strong>Output:</strong> {"1": 4, "false": 6}
<strong>Explanation:</strong> First, all the elements in keysArr are converted into strings. We can see there are two occurrences of "1". The value associated with the first occurrence of "1" is used: 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> keysArr = [], valuesArr = []
<strong>Output:</strong> {}
<strong>Explanation:</strong> There are no keys so an empty object is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>keysArr</code> and <code>valuesArr</code> are valid JSON arrays</li>
<li><code>2 <= JSON.stringify(keysArr).length, JSON.stringify(valuesArr).length <= 5 * 10<sup>5</sup></code></li>
<li><code>keysArr.length === valuesArr.length</code></li>
</ul>
|
JavaScript
|
JavaScript
|
/**
* @param {Array} keysArr
* @param {Array} valuesArr
* @return {Object}
*/
var createObject = function (keysArr, valuesArr) {
const ans = {};
for (let i = 0; i < keysArr.length; ++i) {
const k = keysArr[i] + '';
if (ans[k] === undefined) {
ans[k] = valuesArr[i];
}
}
return ans;
};
|
2,794
|
Create Object from Two Arrays
|
Easy
|
<p>Given two arrays <code>keysArr</code> and <code>valuesArr</code>, return a new object <code>obj</code>. Each key-value pair in <code>obj</code> should come from <code>keysArr[i]</code> and <code>valuesArr[i]</code>.</p>
<p>If a duplicate key exists at a previous index, that key-value should be excluded. In other words, only the first key should be added to the object.</p>
<p>If the key is not a string, it should be converted into a string by calling <code>String()</code> on it.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> keysArr = ["a", "b", "c"], valuesArr = [1, 2, 3]
<strong>Output:</strong> {"a": 1, "b": 2, "c": 3}
<strong>Explanation:</strong> The keys "a", "b", and "c" are paired with the values 1, 2, and 3 respectively.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> keysArr = ["1", 1, false], valuesArr = [4, 5, 6]
<strong>Output:</strong> {"1": 4, "false": 6}
<strong>Explanation:</strong> First, all the elements in keysArr are converted into strings. We can see there are two occurrences of "1". The value associated with the first occurrence of "1" is used: 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> keysArr = [], valuesArr = []
<strong>Output:</strong> {}
<strong>Explanation:</strong> There are no keys so an empty object is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>keysArr</code> and <code>valuesArr</code> are valid JSON arrays</li>
<li><code>2 <= JSON.stringify(keysArr).length, JSON.stringify(valuesArr).length <= 5 * 10<sup>5</sup></code></li>
<li><code>keysArr.length === valuesArr.length</code></li>
</ul>
|
JavaScript
|
TypeScript
|
function createObject(keysArr: any[], valuesArr: any[]): Record<string, any> {
const ans: Record<string, any> = {};
for (let i = 0; i < keysArr.length; ++i) {
const k = String(keysArr[i]);
if (ans[k] === undefined) {
ans[k] = valuesArr[i];
}
}
return ans;
}
|
2,795
|
Parallel Execution of Promises for Individual Results Retrieval
|
Medium
|
<p>Given an array <code>functions</code>, return a promise <code>promise</code>. <code>functions</code> is an array of functions that return promises <code>fnPromise.</code> Each <code>fnPromise</code> can be resolved or rejected. </p>
<p>If <code>fnPromise</code> is resolved:</p>
<p> <code>obj = { status: "fulfilled", value: <em>resolved value</em>}</code></p>
<p>If <code>fnPromise</code> is rejected:</p>
<p> <code>obj = { status: "rejected", reason: <em>reason of rejection (catched error message)</em>}</code></p>
<p>The <code>promise</code> should resolve with an array of these objects <code>obj</code>. Each <code>obj</code> in the array should correspond to the promises in the original array function, <strong>maintaining the same order</strong>.</p>
<p>Try to implement it without using the built-in method <code>Promise.allSettled()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
<strong>Output: </strong>{"t":100,"values":[{"status":"fulfilled","value":15}]}
<strong>Explanation:</strong>
const time = performance.now()
const promise = promiseAllSettled(functions);
promise.then(res => {
const out = {t: Math.floor(performance.now() - time), values: res}
console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
})
The returned promise resolves within 100 milliseconds. Since promise from the array functions is fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":15}].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(20), 100)),
() => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
<strong>Output:
</strong>{
"t":100,
"values": [
{"status":"fulfilled","value":20},
{"status":"fulfilled","value":15}
]
}
<strong>Explanation:</strong> The returned promise resolves within 100 milliseconds, because the resolution time is determined by the promise that takes the longest time to fulfill. Since promises from the array functions are fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":20},{"status":"fulfilled","value":15}].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(30), 200)),
() => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
]
<strong>Output:</strong>
{
"t":200,
"values": [
{"status":"fulfilled","value":30},
{"status":"rejected","reason":"Error"}
]
}
<strong>Explanation:</strong> The returned promise resolves within 200 milliseconds, as its resolution time is determined by the promise that takes the longest time to fulfill. Since one promise from the array function is fulfilled and another is rejected, the resolved value of the returned promise is set to an array containing objects in the following order: [{"status":"fulfilled","value":30}, {"status":"rejected","reason":"Error"}]. Each object in the array corresponds to the promises in the original array function, maintaining the same order.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= functions.length <= 10</code></li>
</ul>
|
JavaScript
|
JavaScript
|
/**
* @param {Array<Function>} functions
* @return {Promise}
*/
var promiseAllSettled = function (functions) {
return new Promise(resolve => {
const res = [];
let count = 0;
for (let i in functions) {
functions[i]()
.then(value => ({ status: 'fulfilled', value }))
.catch(reason => ({ status: 'rejected', reason }))
.then(obj => {
res[i] = obj;
if (++count === functions.length) {
resolve(res);
}
});
}
});
};
|
2,795
|
Parallel Execution of Promises for Individual Results Retrieval
|
Medium
|
<p>Given an array <code>functions</code>, return a promise <code>promise</code>. <code>functions</code> is an array of functions that return promises <code>fnPromise.</code> Each <code>fnPromise</code> can be resolved or rejected. </p>
<p>If <code>fnPromise</code> is resolved:</p>
<p> <code>obj = { status: "fulfilled", value: <em>resolved value</em>}</code></p>
<p>If <code>fnPromise</code> is rejected:</p>
<p> <code>obj = { status: "rejected", reason: <em>reason of rejection (catched error message)</em>}</code></p>
<p>The <code>promise</code> should resolve with an array of these objects <code>obj</code>. Each <code>obj</code> in the array should correspond to the promises in the original array function, <strong>maintaining the same order</strong>.</p>
<p>Try to implement it without using the built-in method <code>Promise.allSettled()</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
<strong>Output: </strong>{"t":100,"values":[{"status":"fulfilled","value":15}]}
<strong>Explanation:</strong>
const time = performance.now()
const promise = promiseAllSettled(functions);
promise.then(res => {
const out = {t: Math.floor(performance.now() - time), values: res}
console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
})
The returned promise resolves within 100 milliseconds. Since promise from the array functions is fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":15}].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(20), 100)),
() => new Promise(resolve => setTimeout(() => resolve(15), 100))
]
<strong>Output:
</strong>{
"t":100,
"values": [
{"status":"fulfilled","value":20},
{"status":"fulfilled","value":15}
]
}
<strong>Explanation:</strong> The returned promise resolves within 100 milliseconds, because the resolution time is determined by the promise that takes the longest time to fulfill. Since promises from the array functions are fulfilled, the resolved value of the returned promise is set to [{"status":"fulfilled","value":20},{"status":"fulfilled","value":15}].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> functions = [
() => new Promise(resolve => setTimeout(() => resolve(30), 200)),
() => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
]
<strong>Output:</strong>
{
"t":200,
"values": [
{"status":"fulfilled","value":30},
{"status":"rejected","reason":"Error"}
]
}
<strong>Explanation:</strong> The returned promise resolves within 200 milliseconds, as its resolution time is determined by the promise that takes the longest time to fulfill. Since one promise from the array function is fulfilled and another is rejected, the resolved value of the returned promise is set to an array containing objects in the following order: [{"status":"fulfilled","value":30}, {"status":"rejected","reason":"Error"}]. Each object in the array corresponds to the promises in the original array function, maintaining the same order.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= functions.length <= 10</code></li>
</ul>
|
JavaScript
|
TypeScript
|
type FulfilledObj = {
status: 'fulfilled';
value: string;
};
type RejectedObj = {
status: 'rejected';
reason: string;
};
type Obj = FulfilledObj | RejectedObj;
function promiseAllSettled(functions: Function[]): Promise<Obj[]> {
return new Promise(resolve => {
const res: Obj[] = [];
let count = 0;
for (let i in functions) {
functions[i]()
.then(value => ({ status: 'fulfilled', value }))
.catch(reason => ({ status: 'rejected', reason }))
.then(obj => {
res[i] = obj;
if (++count === functions.length) {
resolve(res);
}
});
}
});
}
/**
* const functions = [
* () => new Promise(resolve => setTimeout(() => resolve(15), 100))
* ]
* const time = performance.now()
*
* const promise = promiseAllSettled(functions);
*
* promise.then(res => {
* const out = {t: Math.floor(performance.now() - time), values: res}
* console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
* })
*/
|
2,796
|
Repeat String
|
Easy
|
<p>Write code that enhances all strings such that you can call the <code>string.replicate(x)</code> method on any string and it will return repeated string <code>x</code> times.</p>
<p>Try to implement it without using the built-in method <code>string.repeat</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str = "hello", times = 2
<strong>Output:</strong> "hellohello"
<strong>Explanation:</strong> "hello" is repeated 2 times
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str = "code", times = 3
<strong>Output:</strong> "codecodecode"
<strong>Explanation:</strong> "code" is repeated 3 times
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str = "js", times = 1
<strong>Output:</strong> "js"
<strong>Explanation:</strong> "js" is repeated 1 time
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= times <= 10<sup>5</sup></code></li>
<li><code>1 <= str.length <= 1000</code></li>
</ul>
<p> </p>
<strong>Follow up:</strong> Let's assume, for the sake of simplifying analysis, that concatenating strings is a constant time operation <code>O(1)</code>. With this assumption in mind, can you write an algorithm with a runtime complexity of <code>O(log n)</code>?
|
JavaScript
|
JavaScript
|
String.prototype.replicate = function (times) {
return Array(times).fill(this).join('');
};
|
2,796
|
Repeat String
|
Easy
|
<p>Write code that enhances all strings such that you can call the <code>string.replicate(x)</code> method on any string and it will return repeated string <code>x</code> times.</p>
<p>Try to implement it without using the built-in method <code>string.repeat</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str = "hello", times = 2
<strong>Output:</strong> "hellohello"
<strong>Explanation:</strong> "hello" is repeated 2 times
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str = "code", times = 3
<strong>Output:</strong> "codecodecode"
<strong>Explanation:</strong> "code" is repeated 3 times
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str = "js", times = 1
<strong>Output:</strong> "js"
<strong>Explanation:</strong> "js" is repeated 1 time
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= times <= 10<sup>5</sup></code></li>
<li><code>1 <= str.length <= 1000</code></li>
</ul>
<p> </p>
<strong>Follow up:</strong> Let's assume, for the sake of simplifying analysis, that concatenating strings is a constant time operation <code>O(1)</code>. With this assumption in mind, can you write an algorithm with a runtime complexity of <code>O(log n)</code>?
|
JavaScript
|
TypeScript
|
declare global {
interface String {
replicate(times: number): string;
}
}
String.prototype.replicate = function (times: number) {
return new Array(times).fill(this).join('');
};
|
2,797
|
Partial Function with Placeholders
|
Easy
|
<p>Given a function <code>fn</code> and an array <code>args</code>, return a function <code>partialFn</code>. </p>
<p>Placeholders <code>"_"</code> in the <code>args</code> should be replaced with values from <code>restArgs</code> starting from index <code>0</code>. Any remaining values in the <code>restArgs</code> should be added at the end of the <code>args</code>.</p>
<p><code>partialFn</code> should return a result of <code>fn</code>. <code>fn</code> should be called with the elements of the modified <code>args</code> passed as separate arguments.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> fn = (...args) => args, args = [2,4,6], restArgs = [8,10]
<strong>Output:</strong> [2,4,6,8,10]
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // [2,4,6,8,10]
There are no placeholders "_" in args therefore restArgs is just added at the end of args. Then the elements of the args are passed as separate arguments to fn, which returns passed arguments as an array.
</pre>
<strong class="example">Example 2:</strong>
<pre>
<strong>Input:</strong> fn = (...args) => args, args = [1,2,"_",4,"_",6], restArgs = [3,5]
<strong>Output:</strong> [1,2,3,4,5,6]
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // [1,2,3,4,5,6]
Placeholders "_" are replaced with values from the restArgs. Then the elements of the args are passed as separate arguments to fn, which returns passed arguments as an array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> fn = (a, b, c) => b + a - c, args = ["_", 5], restArgs = [5, 20]
<strong>Output:</strong> -10
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // -10
Placeholder "_" is replaced with 5 and 20 is added at the end of args. Then the elements of the args are passed as separate arguments to fn, which returns -10 (5 + 5 - 20).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>fn</code> is a function</li>
<li><code>args</code> and <code>restArgs</code> are valid JSON arrays</li>
<li><code>1 <= args.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= restArgs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= number of placeholders <= restArgs.length</code></li>
</ul>
|
JavaScript
|
JavaScript
|
/**
* @param {Function} fn
* @param {Array} args
* @return {Function}
*/
var partial = function (fn, args) {
return function (...restArgs) {
let i = 0;
for (let j = 0; j < args.length; ++j) {
if (args[j] === '_') {
args[j] = restArgs[i++];
}
}
while (i < restArgs.length) {
args.push(restArgs[i++]);
}
return fn.apply(this, args);
};
};
|
2,797
|
Partial Function with Placeholders
|
Easy
|
<p>Given a function <code>fn</code> and an array <code>args</code>, return a function <code>partialFn</code>. </p>
<p>Placeholders <code>"_"</code> in the <code>args</code> should be replaced with values from <code>restArgs</code> starting from index <code>0</code>. Any remaining values in the <code>restArgs</code> should be added at the end of the <code>args</code>.</p>
<p><code>partialFn</code> should return a result of <code>fn</code>. <code>fn</code> should be called with the elements of the modified <code>args</code> passed as separate arguments.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> fn = (...args) => args, args = [2,4,6], restArgs = [8,10]
<strong>Output:</strong> [2,4,6,8,10]
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // [2,4,6,8,10]
There are no placeholders "_" in args therefore restArgs is just added at the end of args. Then the elements of the args are passed as separate arguments to fn, which returns passed arguments as an array.
</pre>
<strong class="example">Example 2:</strong>
<pre>
<strong>Input:</strong> fn = (...args) => args, args = [1,2,"_",4,"_",6], restArgs = [3,5]
<strong>Output:</strong> [1,2,3,4,5,6]
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // [1,2,3,4,5,6]
Placeholders "_" are replaced with values from the restArgs. Then the elements of the args are passed as separate arguments to fn, which returns passed arguments as an array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> fn = (a, b, c) => b + a - c, args = ["_", 5], restArgs = [5, 20]
<strong>Output:</strong> -10
<strong>Explanation:</strong>
const partialFn = partial(fn, args)
const result = partialFn(...restArgs)
console.log(result) // -10
Placeholder "_" is replaced with 5 and 20 is added at the end of args. Then the elements of the args are passed as separate arguments to fn, which returns -10 (5 + 5 - 20).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>fn</code> is a function</li>
<li><code>args</code> and <code>restArgs</code> are valid JSON arrays</li>
<li><code>1 <= args.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= restArgs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= number of placeholders <= restArgs.length</code></li>
</ul>
|
JavaScript
|
TypeScript
|
function partial(fn: Function, args: any[]): Function {
return function (...restArgs) {
let i = 0;
for (let j = 0; j < args.length; ++j) {
if (args[j] === '_') {
args[j] = restArgs[i++];
}
}
while (i < restArgs.length) {
args.push(restArgs[i++]);
}
return fn(...args);
};
}
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
return count_if(hours.begin(), hours.end(), [target](int h) { return h >= target; });
}
};
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Go
|
func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) {
for _, x := range hours {
if x >= target {
ans++
}
}
return
}
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int numberOfEmployeesWhoMetTarget(int[] hours, int target) {
int ans = 0;
for (int x : hours) {
if (x >= target) {
++ans;
}
}
return ans;
}
}
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
return sum(x >= target for x in hours)
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn number_of_employees_who_met_target(hours: Vec<i32>, target: i32) -> i32 {
hours.iter().filter(|&x| *x >= target).count() as i32
}
}
|
2,798
|
Number of Employees Who Met the Target
|
Easy
|
<p>There are <code>n</code> employees in a company, numbered from <code>0</code> to <code>n - 1</code>. Each employee <code>i</code> has worked for <code>hours[i]</code> hours in the company.</p>
<p>The company requires each employee to work for <strong>at least</strong> <code>target</code> hours.</p>
<p>You are given a <strong>0-indexed</strong> array of non-negative integers <code>hours</code> of length <code>n</code> and a non-negative integer <code>target</code>.</p>
<p>Return <em>the integer denoting the number of employees who worked at least</em> <code>target</code> <em>hours</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> hours = [0,1,2,3,4], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The company wants each employee to work for at least 2 hours.
- Employee 0 worked for 0 hours and didn't meet the target.
- Employee 1 worked for 1 hours and didn't meet the target.
- Employee 2 worked for 2 hours and met the target.
- Employee 3 worked for 3 hours and met the target.
- Employee 4 worked for 4 hours and met the target.
There are 3 employees who met the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> hours = [5,1,4,2,2], target = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> The company wants each employee to work for at least 6 hours.
There are 0 employees who met the target.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == hours.length <= 50</code></li>
<li><code>0 <= hours[i], target <= 10<sup>5</sup></code></li>
</ul>
|
Array
|
TypeScript
|
function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number {
return hours.filter(x => x >= target).length;
}
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
C++
|
class Solution {
public:
int countCompleteSubarrays(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int cnt = s.size();
int ans = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
s.clear();
for (int j = i; j < n; ++j) {
s.insert(nums[j]);
if (s.size() == cnt) {
++ans;
}
}
}
return ans;
}
};
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Go
|
func countCompleteSubarrays(nums []int) (ans int) {
s := map[int]bool{}
for _, x := range nums {
s[x] = true
}
cnt := len(s)
for i := range nums {
s = map[int]bool{}
for _, x := range nums[i:] {
s[x] = true
if len(s) == cnt {
ans++
}
}
}
return
}
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Java
|
class Solution {
public int countCompleteSubarrays(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
int cnt = s.size();
int ans = 0, n = nums.length;
for (int i = 0; i < n; ++i) {
s.clear();
for (int j = i; j < n; ++j) {
s.add(nums[j]);
if (s.size() == cnt) {
++ans;
}
}
}
return ans;
}
}
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Python
|
class Solution:
def countCompleteSubarrays(self, nums: List[int]) -> int:
cnt = len(set(nums))
ans, n = 0, len(nums)
for i in range(n):
s = set()
for x in nums[i:]:
s.add(x)
if len(s) == cnt:
ans += 1
return ans
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Rust
|
use std::collections::HashSet;
impl Solution {
pub fn count_complete_subarrays(nums: Vec<i32>) -> i32 {
let mut s = HashSet::new();
for &x in &nums {
s.insert(x);
}
let cnt = s.len();
let n = nums.len();
let mut ans = 0;
for i in 0..n {
s.clear();
for j in i..n {
s.insert(nums[j]);
if s.len() == cnt {
ans += 1;
}
}
}
ans
}
}
|
2,799
|
Count Complete Subarrays in an Array
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>We call a subarray of an array <strong>complete</strong> if the following condition is satisfied:</p>
<ul>
<li>The number of <strong>distinct</strong> elements in the subarray is equal to the number of distinct elements in the whole array.</li>
</ul>
<p>Return <em>the number of <strong>complete</strong> subarrays</em>.</p>
<p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
TypeScript
|
function countCompleteSubarrays(nums: number[]): number {
const s: Set<number> = new Set(nums);
const cnt = s.size;
const n = nums.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
s.clear();
for (let j = i; j < n; ++j) {
s.add(nums[j]);
if (s.size === cnt) {
++ans;
}
}
}
return ans;
}
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
C++
|
class Solution {
public:
string minimumString(string a, string b, string c) {
vector<string> s = {a, b, c};
vector<vector<int>> perm = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 1, 0}, {2, 0, 1}};
string ans = "";
for (auto& p : perm) {
int i = p[0], j = p[1], k = p[2];
string t = f(f(s[i], s[j]), s[k]);
if (ans == "" || t.size() < ans.size() || (t.size() == ans.size() && t < ans)) {
ans = t;
}
}
return ans;
}
string f(string s, string t) {
if (s.find(t) != string::npos) {
return s;
}
if (t.find(s) != string::npos) {
return t;
}
int m = s.size(), n = t.size();
for (int i = min(m, n); i; --i) {
if (s.substr(m - i) == t.substr(0, i)) {
return s + t.substr(i);
}
}
return s + t;
};
};
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
Go
|
func minimumString(a string, b string, c string) string {
f := func(s, t string) string {
if strings.Contains(s, t) {
return s
}
if strings.Contains(t, s) {
return t
}
m, n := len(s), len(t)
for i := min(m, n); i > 0; i-- {
if s[m-i:] == t[:i] {
return s + t[i:]
}
}
return s + t
}
s := [3]string{a, b, c}
ans := ""
for _, p := range [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} {
i, j, k := p[0], p[1], p[2]
t := f(f(s[i], s[j]), s[k])
if ans == "" || len(t) < len(ans) || (len(t) == len(ans) && t < ans) {
ans = t
}
}
return ans
}
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
Java
|
class Solution {
public String minimumString(String a, String b, String c) {
String[] s = {a, b, c};
int[][] perm = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 1, 0}, {2, 0, 1}};
String ans = "";
for (var p : perm) {
int i = p[0], j = p[1], k = p[2];
String t = f(f(s[i], s[j]), s[k]);
if ("".equals(ans) || t.length() < ans.length()
|| (t.length() == ans.length() && t.compareTo(ans) < 0)) {
ans = t;
}
}
return ans;
}
private String f(String s, String t) {
if (s.contains(t)) {
return s;
}
if (t.contains(s)) {
return t;
}
int m = s.length(), n = t.length();
for (int i = Math.min(m, n); i > 0; --i) {
if (s.substring(m - i).equals(t.substring(0, i))) {
return s + t.substring(i);
}
}
return s + t;
}
}
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
Python
|
class Solution:
def minimumString(self, a: str, b: str, c: str) -> str:
def f(s: str, t: str) -> str:
if s in t:
return t
if t in s:
return s
m, n = len(s), len(t)
for i in range(min(m, n), 0, -1):
if s[-i:] == t[:i]:
return s + t[i:]
return s + t
ans = ""
for a, b, c in permutations((a, b, c)):
s = f(f(a, b), c)
if ans == "" or len(s) < len(ans) or (len(s) == len(ans) and s < ans):
ans = s
return ans
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
Rust
|
impl Solution {
fn f(s1: String, s2: String) -> String {
if s1.contains(&s2) {
return s1;
}
if s2.contains(&s1) {
return s2;
}
for i in 0..s1.len() {
let s = &s1[i..];
if s2.starts_with(s) {
let n = s.len();
return s1 + &s2[n..];
}
}
s1 + s2.as_str()
}
pub fn minimum_string(a: String, b: String, c: String) -> String {
let s = [&a, &b, &c];
let perm = [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
];
let mut ans = String::new();
for [i, j, k] in perm.iter() {
let r = Self::f(Self::f(s[*i].clone(), s[*j].clone()), s[*k].clone());
if ans == "" || r.len() < ans.len() || (r.len() == ans.len() && r < ans) {
ans = r;
}
}
ans
}
}
|
2,800
|
Shortest String That Contains Three Strings
|
Medium
|
Given three strings <code>a</code>, <code>b</code>, and <code>c</code>, your task is to find a string that has the<strong> minimum</strong> length and contains all three strings as <strong>substrings</strong>.
<p>If there are multiple such strings, return the<em> </em><strong>lexicographically<em> </em>smallest </strong>one.</p>
<p>Return <em>a string denoting the answer to the problem.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears <strong>earlier </strong>in the alphabet than the corresponding letter in <code>b</code>.</li>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = "abc", b = "bca", c = "aaa"
<strong>Output:</strong> "aaabca"
<strong>Explanation:</strong> We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = "ab", b = "ba", c = "aba"
<strong>Output:</strong> "aba"
<strong>Explanation: </strong>We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 100</code></li>
<li><code>a</code>, <code>b</code>, <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Greedy; String; Enumeration
|
TypeScript
|
function minimumString(a: string, b: string, c: string): string {
const f = (s: string, t: string): string => {
if (s.includes(t)) {
return s;
}
if (t.includes(s)) {
return t;
}
const m = s.length;
const n = t.length;
for (let i = Math.min(m, n); i > 0; --i) {
if (s.slice(-i) === t.slice(0, i)) {
return s + t.slice(i);
}
}
return s + t;
};
const s: string[] = [a, b, c];
const perm: number[][] = [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
];
let ans = '';
for (const [i, j, k] of perm) {
const t = f(f(s[i], s[j]), s[k]);
if (ans === '' || t.length < ans.length || (t.length === ans.length && t < ans)) {
ans = t;
}
}
return ans;
}
|
2,801
|
Count Stepping Numbers in Range
|
Hard
|
<p>Given two positive integers <code>low</code> and <code>high</code> represented as strings, find the count of <strong>stepping numbers</strong> in the inclusive range <code>[low, high]</code>.</p>
<p>A <strong>stepping number</strong> is an integer such that all of its adjacent digits have an absolute difference of <strong>exactly</strong> <code>1</code>.</p>
<p>Return <em>an integer denoting the count of stepping numbers in the inclusive range</em> <code>[low, high]</code><em>. </em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note:</strong> A stepping number should not have a leading zero.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = "1", high = "11"
<strong>Output:</strong> 10
<strong>Explanation: </strong>The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = "90", high = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= int(low) <= int(high) < 10<sup>100</sup></code></li>
<li><code>1 <= low.length, high.length <= 100</code></li>
<li><code>low</code> and <code>high</code> consist of only digits.</li>
<li><code>low</code> and <code>high</code> don't have any leading zeros.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int countSteppingNumbers(string low, string high) {
const int mod = 1e9 + 7;
int m = high.size();
int f[m + 1][10];
memset(f, -1, sizeof(f));
string num = high;
function<int(int, int, bool, bool)> dfs = [&](int pos, int pre, bool lead, bool limit) {
if (pos >= num.size()) {
return lead ? 0 : 1;
}
if (!lead && !limit && f[pos][pre] != -1) {
return f[pos][pre];
}
int up = limit ? num[pos] - '0' : 9;
int ans = 0;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead) {
ans += dfs(pos + 1, pre, true, limit && i == up);
} else if (pre == -1 || abs(pre - i) == 1) {
ans += dfs(pos + 1, i, false, limit && i == up);
}
ans %= mod;
}
if (!lead && !limit) {
f[pos][pre] = ans;
}
return ans;
};
int a = dfs(0, -1, true, true);
memset(f, -1, sizeof(f));
for (int i = low.size() - 1; i >= 0; --i) {
if (low[i] == '0') {
low[i] = '9';
} else {
low[i] -= 1;
break;
}
}
num = low;
int b = dfs(0, -1, true, true);
return (a - b + mod) % mod;
}
};
|
2,801
|
Count Stepping Numbers in Range
|
Hard
|
<p>Given two positive integers <code>low</code> and <code>high</code> represented as strings, find the count of <strong>stepping numbers</strong> in the inclusive range <code>[low, high]</code>.</p>
<p>A <strong>stepping number</strong> is an integer such that all of its adjacent digits have an absolute difference of <strong>exactly</strong> <code>1</code>.</p>
<p>Return <em>an integer denoting the count of stepping numbers in the inclusive range</em> <code>[low, high]</code><em>. </em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note:</strong> A stepping number should not have a leading zero.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = "1", high = "11"
<strong>Output:</strong> 10
<strong>Explanation: </strong>The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = "90", high = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= int(low) <= int(high) < 10<sup>100</sup></code></li>
<li><code>1 <= low.length, high.length <= 100</code></li>
<li><code>low</code> and <code>high</code> consist of only digits.</li>
<li><code>low</code> and <code>high</code> don't have any leading zeros.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func countSteppingNumbers(low string, high string) int {
const mod = 1e9 + 7
f := [110][10]int{}
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
num := high
var dfs func(int, int, bool, bool) int
dfs = func(pos, pre int, lead bool, limit bool) int {
if pos >= len(num) {
if lead {
return 0
}
return 1
}
if !lead && !limit && f[pos][pre] != -1 {
return f[pos][pre]
}
var ans int
up := 9
if limit {
up = int(num[pos] - '0')
}
for i := 0; i <= up; i++ {
if i == 0 && lead {
ans += dfs(pos+1, pre, true, limit && i == up)
} else if pre == -1 || abs(pre-i) == 1 {
ans += dfs(pos+1, i, false, limit && i == up)
}
ans %= mod
}
if !lead && !limit {
f[pos][pre] = ans
}
return ans
}
a := dfs(0, -1, true, true)
t := []byte(low)
for i := len(t) - 1; i >= 0; i-- {
if t[i] != '0' {
t[i]--
break
}
t[i] = '9'
}
num = string(t)
f = [110][10]int{}
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
b := dfs(0, -1, true, true)
return (a - b + mod) % mod
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
2,801
|
Count Stepping Numbers in Range
|
Hard
|
<p>Given two positive integers <code>low</code> and <code>high</code> represented as strings, find the count of <strong>stepping numbers</strong> in the inclusive range <code>[low, high]</code>.</p>
<p>A <strong>stepping number</strong> is an integer such that all of its adjacent digits have an absolute difference of <strong>exactly</strong> <code>1</code>.</p>
<p>Return <em>an integer denoting the count of stepping numbers in the inclusive range</em> <code>[low, high]</code><em>. </em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note:</strong> A stepping number should not have a leading zero.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = "1", high = "11"
<strong>Output:</strong> 10
<strong>Explanation: </strong>The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = "90", high = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= int(low) <= int(high) < 10<sup>100</sup></code></li>
<li><code>1 <= low.length, high.length <= 100</code></li>
<li><code>low</code> and <code>high</code> consist of only digits.</li>
<li><code>low</code> and <code>high</code> don't have any leading zeros.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
import java.math.BigInteger;
class Solution {
private final int mod = (int) 1e9 + 7;
private String num;
private Integer[][] f;
public int countSteppingNumbers(String low, String high) {
f = new Integer[high.length() + 1][10];
num = high;
int a = dfs(0, -1, true, true);
f = new Integer[high.length() + 1][10];
num = new BigInteger(low).subtract(BigInteger.ONE).toString();
int b = dfs(0, -1, true, true);
return (a - b + mod) % mod;
}
private int dfs(int pos, int pre, boolean lead, boolean limit) {
if (pos >= num.length()) {
return lead ? 0 : 1;
}
if (!lead && !limit && f[pos][pre] != null) {
return f[pos][pre];
}
int ans = 0;
int up = limit ? num.charAt(pos) - '0' : 9;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead) {
ans += dfs(pos + 1, pre, true, limit && i == up);
} else if (pre == -1 || Math.abs(pre - i) == 1) {
ans += dfs(pos + 1, i, false, limit && i == up);
}
ans %= mod;
}
if (!lead && !limit) {
f[pos][pre] = ans;
}
return ans;
}
}
|
2,801
|
Count Stepping Numbers in Range
|
Hard
|
<p>Given two positive integers <code>low</code> and <code>high</code> represented as strings, find the count of <strong>stepping numbers</strong> in the inclusive range <code>[low, high]</code>.</p>
<p>A <strong>stepping number</strong> is an integer such that all of its adjacent digits have an absolute difference of <strong>exactly</strong> <code>1</code>.</p>
<p>Return <em>an integer denoting the count of stepping numbers in the inclusive range</em> <code>[low, high]</code><em>. </em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note:</strong> A stepping number should not have a leading zero.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = "1", high = "11"
<strong>Output:</strong> 10
<strong>Explanation: </strong>The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = "90", high = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= int(low) <= int(high) < 10<sup>100</sup></code></li>
<li><code>1 <= low.length, high.length <= 100</code></li>
<li><code>low</code> and <code>high</code> consist of only digits.</li>
<li><code>low</code> and <code>high</code> don't have any leading zeros.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def countSteppingNumbers(self, low: str, high: str) -> int:
@cache
def dfs(pos: int, pre: int, lead: bool, limit: bool) -> int:
if pos >= len(num):
return int(not lead)
up = int(num[pos]) if limit else 9
ans = 0
for i in range(up + 1):
if i == 0 and lead:
ans += dfs(pos + 1, pre, True, limit and i == up)
elif pre == -1 or abs(i - pre) == 1:
ans += dfs(pos + 1, i, False, limit and i == up)
return ans % mod
mod = 10**9 + 7
num = high
a = dfs(0, -1, True, True)
dfs.cache_clear()
num = str(int(low) - 1)
b = dfs(0, -1, True, True)
return (a - b) % mod
|
2,801
|
Count Stepping Numbers in Range
|
Hard
|
<p>Given two positive integers <code>low</code> and <code>high</code> represented as strings, find the count of <strong>stepping numbers</strong> in the inclusive range <code>[low, high]</code>.</p>
<p>A <strong>stepping number</strong> is an integer such that all of its adjacent digits have an absolute difference of <strong>exactly</strong> <code>1</code>.</p>
<p>Return <em>an integer denoting the count of stepping numbers in the inclusive range</em> <code>[low, high]</code><em>. </em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note:</strong> A stepping number should not have a leading zero.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = "1", high = "11"
<strong>Output:</strong> 10
<strong>Explanation: </strong>The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = "90", high = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= int(low) <= int(high) < 10<sup>100</sup></code></li>
<li><code>1 <= low.length, high.length <= 100</code></li>
<li><code>low</code> and <code>high</code> consist of only digits.</li>
<li><code>low</code> and <code>high</code> don't have any leading zeros.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function countSteppingNumbers(low: string, high: string): number {
const mod = 1e9 + 7;
const m = high.length;
let f: number[][] = Array(m + 1)
.fill(0)
.map(() => Array(10).fill(-1));
let num = high;
const dfs = (pos: number, pre: number, lead: boolean, limit: boolean): number => {
if (pos >= num.length) {
return lead ? 0 : 1;
}
if (!lead && !limit && f[pos][pre] !== -1) {
return f[pos][pre];
}
let ans = 0;
const up = limit ? +num[pos] : 9;
for (let i = 0; i <= up; i++) {
if (i == 0 && lead) {
ans += dfs(pos + 1, pre, true, limit && i == up);
} else if (pre == -1 || Math.abs(pre - i) == 1) {
ans += dfs(pos + 1, i, false, limit && i == up);
}
ans %= mod;
}
if (!lead && !limit) {
f[pos][pre] = ans;
}
return ans;
};
const a = dfs(0, -1, true, true);
num = (BigInt(low) - 1n).toString();
f = Array(m + 1)
.fill(0)
.map(() => Array(10).fill(-1));
const b = dfs(0, -1, true, true);
return (a - b + mod) % mod;
}
|
2,802
|
Find The K-th Lucky Number
|
Medium
|
<p>We know that <code>4</code> and <code>7</code> are <strong>lucky</strong> digits. Also, a number is called <strong>lucky</strong> if it contains <strong>only</strong> lucky digits.</p>
<p>You are given an integer <code>k</code>, return<em> the </em><code>k<sup>th</sup></code><em> lucky number represented as a <strong>string</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> k = 4
<strong>Output:</strong> "47"
<strong>Explanation:</strong> The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> k = 10
<strong>Output:</strong> "477"
<strong>Explanation:</strong> Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10<sup>th</sup> lucky number is 477.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> k = 1000
<strong>Output:</strong> "777747447"
<strong>Explanation:</strong> It can be shown that the 1000<sup>th</sup> lucky number is 777747447.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Math; String
|
C++
|
class Solution {
public:
string kthLuckyNumber(int k) {
int n = 1;
while (k > 1 << n) {
k -= 1 << n;
++n;
}
string ans;
while (n--) {
if (k <= 1 << n) {
ans.push_back('4');
} else {
ans.push_back('7');
k -= 1 << n;
}
}
return ans;
}
};
|
2,802
|
Find The K-th Lucky Number
|
Medium
|
<p>We know that <code>4</code> and <code>7</code> are <strong>lucky</strong> digits. Also, a number is called <strong>lucky</strong> if it contains <strong>only</strong> lucky digits.</p>
<p>You are given an integer <code>k</code>, return<em> the </em><code>k<sup>th</sup></code><em> lucky number represented as a <strong>string</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> k = 4
<strong>Output:</strong> "47"
<strong>Explanation:</strong> The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> k = 10
<strong>Output:</strong> "477"
<strong>Explanation:</strong> Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10<sup>th</sup> lucky number is 477.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> k = 1000
<strong>Output:</strong> "777747447"
<strong>Explanation:</strong> It can be shown that the 1000<sup>th</sup> lucky number is 777747447.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Math; String
|
Go
|
func kthLuckyNumber(k int) string {
n := 1
for k > 1<<n {
k -= 1 << n
n++
}
ans := []byte{}
for n > 0 {
n--
if k <= 1<<n {
ans = append(ans, '4')
} else {
ans = append(ans, '7')
k -= 1 << n
}
}
return string(ans)
}
|
2,802
|
Find The K-th Lucky Number
|
Medium
|
<p>We know that <code>4</code> and <code>7</code> are <strong>lucky</strong> digits. Also, a number is called <strong>lucky</strong> if it contains <strong>only</strong> lucky digits.</p>
<p>You are given an integer <code>k</code>, return<em> the </em><code>k<sup>th</sup></code><em> lucky number represented as a <strong>string</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> k = 4
<strong>Output:</strong> "47"
<strong>Explanation:</strong> The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> k = 10
<strong>Output:</strong> "477"
<strong>Explanation:</strong> Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10<sup>th</sup> lucky number is 477.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> k = 1000
<strong>Output:</strong> "777747447"
<strong>Explanation:</strong> It can be shown that the 1000<sup>th</sup> lucky number is 777747447.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Math; String
|
Java
|
class Solution {
public String kthLuckyNumber(int k) {
int n = 1;
while (k > 1 << n) {
k -= 1 << n;
++n;
}
StringBuilder ans = new StringBuilder();
while (n-- > 0) {
if (k <= 1 << n) {
ans.append('4');
} else {
ans.append('7');
k -= 1 << n;
}
}
return ans.toString();
}
}
|
2,802
|
Find The K-th Lucky Number
|
Medium
|
<p>We know that <code>4</code> and <code>7</code> are <strong>lucky</strong> digits. Also, a number is called <strong>lucky</strong> if it contains <strong>only</strong> lucky digits.</p>
<p>You are given an integer <code>k</code>, return<em> the </em><code>k<sup>th</sup></code><em> lucky number represented as a <strong>string</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> k = 4
<strong>Output:</strong> "47"
<strong>Explanation:</strong> The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> k = 10
<strong>Output:</strong> "477"
<strong>Explanation:</strong> Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10<sup>th</sup> lucky number is 477.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> k = 1000
<strong>Output:</strong> "777747447"
<strong>Explanation:</strong> It can be shown that the 1000<sup>th</sup> lucky number is 777747447.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Math; String
|
Python
|
class Solution:
def kthLuckyNumber(self, k: int) -> str:
n = 1
while k > 1 << n:
k -= 1 << n
n += 1
ans = []
while n:
n -= 1
if k <= 1 << n:
ans.append("4")
else:
ans.append("7")
k -= 1 << n
return "".join(ans)
|
2,802
|
Find The K-th Lucky Number
|
Medium
|
<p>We know that <code>4</code> and <code>7</code> are <strong>lucky</strong> digits. Also, a number is called <strong>lucky</strong> if it contains <strong>only</strong> lucky digits.</p>
<p>You are given an integer <code>k</code>, return<em> the </em><code>k<sup>th</sup></code><em> lucky number represented as a <strong>string</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> k = 4
<strong>Output:</strong> "47"
<strong>Explanation:</strong> The first lucky number is 4, the second one is 7, the third one is 44 and the fourth one is 47.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> k = 10
<strong>Output:</strong> "477"
<strong>Explanation:</strong> Here are lucky numbers sorted in increasing order:
4, 7, 44, 47, 74, 77, 444, 447, 474, 477. So the 10<sup>th</sup> lucky number is 477.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> k = 1000
<strong>Output:</strong> "777747447"
<strong>Explanation:</strong> It can be shown that the 1000<sup>th</sup> lucky number is 777747447.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Math; String
|
TypeScript
|
function kthLuckyNumber(k: number): string {
let n = 1;
while (k > 1 << n) {
k -= 1 << n;
++n;
}
const ans: string[] = [];
while (n-- > 0) {
if (k <= 1 << n) {
ans.push('4');
} else {
ans.push('7');
k -= 1 << n;
}
}
return ans.join('');
}
|
2,803
|
Factorial Generator
|
Easy
|
<p>Write a generator function that takes an integer <code>n</code> as an argument and returns a generator object which yields the <strong>factorial sequence</strong>.</p>
<p>The <strong>factorial sequence</strong> is defined by the relation <code>n! = n * <span style="font-size: 13px;">(</span>n-1) * (n-2) * ... * 2 * 1.</code></p>
<p>The factorial of 0 is defined as 1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5
<strong>Output:</strong> [1,2,6,24,120]
<strong>Explanation:</strong>
const gen = factorial(5)
gen.next().value // 1
gen.next().value // 2
gen.next().value // 6
gen.next().value // 24
gen.next().value // 120
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
const gen = factorial(2)
gen.next().value // 1
gen.next().value // 2
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> [1]
<strong>Explanation:</strong>
const gen = factorial(0)
gen.next().value // 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 18</code></li>
</ul>
|
JavaScript
|
TypeScript
|
function* factorial(n: number): Generator<number> {
if (n === 0) {
yield 1;
}
let ans = 1;
for (let i = 1; i <= n; ++i) {
ans *= i;
yield ans;
}
}
/**
* const gen = factorial(2);
* gen.next().value; // 1
* gen.next().value; // 2
*/
|
2,804
|
Array Prototype ForEach
|
Easy
|
<p>Write your version of method <code>forEach</code> that enhances all arrays such that you can call the <code>array.forEach(callback, context)</code> method on any array and it will execute <code>callback</code> on each element of the array. Method <code>forEach</code> should not return anything.</p>
<p><code>callback</code> accepts the following arguments:</p>
<ul>
<li><code>currentValue</code> - represents the current element being processed in the array. It is the value of the element in the current iteration.</li>
<li><code>index</code> - represents the index of the current element being processed in the array.</li>
<li><code>array</code> - represents the array itself, allowing access to the entire array within the callback function.</li>
</ul>
<p>The <code>context</code> is the object that should be passed as the function context parameter to the <code>callback</code> function, ensuring that the <code>this</code> keyword within the <code>callback</code> function refers to this <code>context</code> object.</p>
<p>Try to implement it without using the built-in array methods.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
arr = [1,2,3],
callback = (val, i, arr) => arr[i] = val * 2,
context = {"context":true}
<strong>Output:</strong> [2,4,6]
<strong>Explanation:</strong>
arr.forEach(callback, context)
console.log(arr) // [2,4,6]
The callback is executed on each element of the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong>
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = this,
context = {"context": false}
<strong>Output:</strong> [{"context":false},{"context":false},{"context":false},{"context":false}]
<strong>Explanation:</strong>
arr.forEach(callback, context)
console.log(arr) // [{"context":false},{"context":false},{"context":false},{"context":false}]
The callback is executed on each element of the array with the right context.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong>
arr = [true, true, false, false],
callback = (val, i, arr) => arr[i] = !val,
context = {"context": 5}
<strong>Output:</strong> [false,false,true,true]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>arr</code> is a valid JSON array</li>
<li><code>context</code> is a valid JSON object</li>
<li><code>fn</code> is a function</li>
<li><code>0 <= arr.length <= 10<sup>5</sup></code></li>
</ul>
|
JavaScript
|
TypeScript
|
Array.prototype.forEach = function (callback: Function, context: any): void {
for (let i = 0; i < this.length; ++i) {
callback.call(context, this[i], i, this);
}
};
/**
* const arr = [1,2,3];
* const callback = (val, i, arr) => arr[i] = val * 2;
* const context = {"context":true};
*
* arr.forEach(callback, context)
*
* console.log(arr) // [2,4,6]
*/
|
2,805
|
Custom Interval
|
Medium
|
<p><strong>Function </strong><code>customInterval</code></p>
<p>Given a function <code>fn</code>, a number <code>delay</code> and a number <code>period</code>, return a number <code>id</code>.</p>
<p><code>customInterval</code> is a function that should execute the provided function <code>fn</code> at intervals based on a linear pattern defined by the formula <code>delay + period * count</code>. </p>
<p>The <code>count</code> in the formula represents the number of times the interval has been executed starting from an initial value of <code>0</code>.</p>
<p><strong>Function </strong><code>customClearInterval</code> </p>
<p>Given the <code>id</code>. <code>id</code> is the returned value from the function <code>customInterval</code>.</p>
<p><code>customClearInterval</code> should stop executing provided function <code>fn</code> at intervals.</p>
<p><strong>Note:</strong> The <code>setTimeout</code> and <code>setInterval</code> functions in Node.js return an object, not a number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> delay = 50, period = 20, cancelTime = 225
<strong>Output:</strong> [50,120,210]
<strong>Explanation:</strong>
const t = performance.now()
const result = []
const fn = () => {
result.push(Math.floor(performance.now() - t))
}
const id = customInterval(fn, delay, period)
setTimeout(() => {
customClearInterval(id)
}, 225)
50 + 20 * 0 = 50 // 50ms - 1st function call
50 + 20 * 1 = 70 // 50ms + 70ms = 120ms - 2nd function call
50 + 20 * 2 = 90 // 50ms + 70ms + 90ms = 210ms - 3rd function call
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> delay = 20, period = 20, cancelTime = 150
<strong>Output:</strong> [20,60,120]
<strong>Explanation:</strong>
20 + 20 * 0 = 20 // 20ms - 1st function call
20 + 20 * 1 = 40 // 20ms + 40ms = 60ms - 2nd function call
20 + 20 * 2 = 60 // 20ms + 40ms + 60ms = 120ms - 3rd function call
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> delay = 100, period = 200, cancelTime = 500
<strong>Output:</strong> [100,400]
<strong>Explanation:</strong>
100 + 200 * 0 = 100 // 100ms - 1st function call
100 + 200 * 1 = 300 // 100ms + 300ms = 400ms - 2nd function call
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>20 <= delay, period <= 250</code></li>
<li><code>20 <= cancelTime <= 1000</code></li>
</ul>
|
JavaScript
|
TypeScript
|
const intervalMap = new Map<number, NodeJS.Timeout>();
function customInterval(fn: Function, delay: number, period: number): number {
let count = 0;
function recursiveTimeout() {
intervalMap.set(
id,
setTimeout(
() => {
fn();
count++;
recursiveTimeout();
},
delay + period * count,
),
);
}
const id = Date.now();
recursiveTimeout();
return id;
}
function customClearInterval(id: number) {
if (intervalMap.has(id)) {
clearTimeout(intervalMap.get(id)!);
intervalMap.delete(id);
}
}
|
2,806
|
Account Balance After Rounded Purchase
|
Easy
|
<p>Initially, you have a bank account balance of <strong>100</strong> dollars.</p>
<p>You are given an integer <code>purchaseAmount</code> representing the amount you will spend on a purchase in dollars, in other words, its price.</p>
<p>When making the purchase, first the <code>purchaseAmount</code> <strong>is rounded to the nearest multiple of 10</strong>. Let us call this value <code>roundedAmount</code>. Then, <code>roundedAmount</code> dollars are removed from your bank account.</p>
<p>Return an integer denoting your final bank account balance after this purchase.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>0 is considered to be a multiple of 10 in this problem.</li>
<li>When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 9</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 15</span></p>
<p><strong>Output:</strong> <span class="example-io">80</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= purchaseAmount <= 100</code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
int accountBalanceAfterPurchase(int purchaseAmount) {
int diff = 100, x = 0;
for (int y = 100; y >= 0; y -= 10) {
int t = abs(y - purchaseAmount);
if (t < diff) {
diff = t;
x = y;
}
}
return 100 - x;
}
};
|
2,806
|
Account Balance After Rounded Purchase
|
Easy
|
<p>Initially, you have a bank account balance of <strong>100</strong> dollars.</p>
<p>You are given an integer <code>purchaseAmount</code> representing the amount you will spend on a purchase in dollars, in other words, its price.</p>
<p>When making the purchase, first the <code>purchaseAmount</code> <strong>is rounded to the nearest multiple of 10</strong>. Let us call this value <code>roundedAmount</code>. Then, <code>roundedAmount</code> dollars are removed from your bank account.</p>
<p>Return an integer denoting your final bank account balance after this purchase.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>0 is considered to be a multiple of 10 in this problem.</li>
<li>When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 9</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 15</span></p>
<p><strong>Output:</strong> <span class="example-io">80</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= purchaseAmount <= 100</code></li>
</ul>
|
Math
|
Go
|
func accountBalanceAfterPurchase(purchaseAmount int) int {
diff, x := 100, 0
for y := 100; y >= 0; y -= 10 {
t := abs(y - purchaseAmount)
if t < diff {
diff = t
x = y
}
}
return 100 - x
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
2,806
|
Account Balance After Rounded Purchase
|
Easy
|
<p>Initially, you have a bank account balance of <strong>100</strong> dollars.</p>
<p>You are given an integer <code>purchaseAmount</code> representing the amount you will spend on a purchase in dollars, in other words, its price.</p>
<p>When making the purchase, first the <code>purchaseAmount</code> <strong>is rounded to the nearest multiple of 10</strong>. Let us call this value <code>roundedAmount</code>. Then, <code>roundedAmount</code> dollars are removed from your bank account.</p>
<p>Return an integer denoting your final bank account balance after this purchase.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>0 is considered to be a multiple of 10 in this problem.</li>
<li>When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 9</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 15</span></p>
<p><strong>Output:</strong> <span class="example-io">80</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= purchaseAmount <= 100</code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int accountBalanceAfterPurchase(int purchaseAmount) {
int diff = 100, x = 0;
for (int y = 100; y >= 0; y -= 10) {
int t = Math.abs(y - purchaseAmount);
if (t < diff) {
diff = t;
x = y;
}
}
return 100 - x;
}
}
|
2,806
|
Account Balance After Rounded Purchase
|
Easy
|
<p>Initially, you have a bank account balance of <strong>100</strong> dollars.</p>
<p>You are given an integer <code>purchaseAmount</code> representing the amount you will spend on a purchase in dollars, in other words, its price.</p>
<p>When making the purchase, first the <code>purchaseAmount</code> <strong>is rounded to the nearest multiple of 10</strong>. Let us call this value <code>roundedAmount</code>. Then, <code>roundedAmount</code> dollars are removed from your bank account.</p>
<p>Return an integer denoting your final bank account balance after this purchase.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>0 is considered to be a multiple of 10 in this problem.</li>
<li>When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 9</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 15</span></p>
<p><strong>Output:</strong> <span class="example-io">80</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= purchaseAmount <= 100</code></li>
</ul>
|
Math
|
Python
|
class Solution:
def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
diff, x = 100, 0
for y in range(100, -1, -10):
if (t := abs(y - purchaseAmount)) < diff:
diff = t
x = y
return 100 - x
|
2,806
|
Account Balance After Rounded Purchase
|
Easy
|
<p>Initially, you have a bank account balance of <strong>100</strong> dollars.</p>
<p>You are given an integer <code>purchaseAmount</code> representing the amount you will spend on a purchase in dollars, in other words, its price.</p>
<p>When making the purchase, first the <code>purchaseAmount</code> <strong>is rounded to the nearest multiple of 10</strong>. Let us call this value <code>roundedAmount</code>. Then, <code>roundedAmount</code> dollars are removed from your bank account.</p>
<p>Return an integer denoting your final bank account balance after this purchase.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>0 is considered to be a multiple of 10 in this problem.</li>
<li>When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 9</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 15</span></p>
<p><strong>Output:</strong> <span class="example-io">80</span></p>
<p><strong>Explanation:</strong></p>
<p>The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">purchaseAmount = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">90</span></p>
<p><strong>Explanation:</strong></p>
<p>10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= purchaseAmount <= 100</code></li>
</ul>
|
Math
|
TypeScript
|
function accountBalanceAfterPurchase(purchaseAmount: number): number {
let [diff, x] = [100, 0];
for (let y = 100; y >= 0; y -= 10) {
const t = Math.abs(y - purchaseAmount);
if (t < diff) {
diff = t;
x = y;
}
}
return 100 - x;
}
|
2,807
|
Insert Greatest Common Divisors in Linked List
|
Medium
|
<p>Given the head of a linked list <code>head</code>, in which each node contains an integer value.</p>
<p>Between every pair of adjacent nodes, insert a new node with a value equal to the <strong>greatest common divisor</strong> of them.</p>
<p>Return <em>the linked list after insertion</em>.</p>
<p>The <strong>greatest common divisor</strong> of two numbers is the largest positive integer that evenly divides both numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex1_copy.png" style="width: 641px; height: 181px;" />
<pre>
<strong>Input:</strong> head = [18,6,10,3]
<strong>Output:</strong> [18,6,6,2,10,1,3]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
- We insert the greatest common divisor of 18 and 6 = 6 between the 1<sup>st</sup> and the 2<sup>nd</sup> nodes.
- We insert the greatest common divisor of 6 and 10 = 2 between the 2<sup>nd</sup> and the 3<sup>rd</sup> nodes.
- We insert the greatest common divisor of 10 and 3 = 1 between the 3<sup>rd</sup> and the 4<sup>th</sup> nodes.
There are no more adjacent nodes, so we return the linked list.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex2_copy1.png" style="width: 51px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [7]
<strong>Output:</strong> [7]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes.
There are no pairs of adjacent nodes, so we return the initial linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>
<li><code>1 <= Node.val <= 1000</code></li>
</ul>
|
Linked List; Math; Number Theory
|
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* insertGreatestCommonDivisors(ListNode* head) {
ListNode* pre = head;
for (ListNode* cur = head->next; cur; cur = cur->next) {
int x = gcd(pre->val, cur->val);
pre->next = new ListNode(x, cur);
pre = cur;
}
return head;
}
};
|
2,807
|
Insert Greatest Common Divisors in Linked List
|
Medium
|
<p>Given the head of a linked list <code>head</code>, in which each node contains an integer value.</p>
<p>Between every pair of adjacent nodes, insert a new node with a value equal to the <strong>greatest common divisor</strong> of them.</p>
<p>Return <em>the linked list after insertion</em>.</p>
<p>The <strong>greatest common divisor</strong> of two numbers is the largest positive integer that evenly divides both numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex1_copy.png" style="width: 641px; height: 181px;" />
<pre>
<strong>Input:</strong> head = [18,6,10,3]
<strong>Output:</strong> [18,6,6,2,10,1,3]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
- We insert the greatest common divisor of 18 and 6 = 6 between the 1<sup>st</sup> and the 2<sup>nd</sup> nodes.
- We insert the greatest common divisor of 6 and 10 = 2 between the 2<sup>nd</sup> and the 3<sup>rd</sup> nodes.
- We insert the greatest common divisor of 10 and 3 = 1 between the 3<sup>rd</sup> and the 4<sup>th</sup> nodes.
There are no more adjacent nodes, so we return the linked list.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex2_copy1.png" style="width: 51px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [7]
<strong>Output:</strong> [7]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes.
There are no pairs of adjacent nodes, so we return the initial linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>
<li><code>1 <= Node.val <= 1000</code></li>
</ul>
|
Linked List; Math; Number Theory
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
for pre, cur := head, head.Next; cur != nil; cur = cur.Next {
x := gcd(pre.Val, cur.Val)
pre.Next = &ListNode{x, cur}
pre = cur
}
return head
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
2,807
|
Insert Greatest Common Divisors in Linked List
|
Medium
|
<p>Given the head of a linked list <code>head</code>, in which each node contains an integer value.</p>
<p>Between every pair of adjacent nodes, insert a new node with a value equal to the <strong>greatest common divisor</strong> of them.</p>
<p>Return <em>the linked list after insertion</em>.</p>
<p>The <strong>greatest common divisor</strong> of two numbers is the largest positive integer that evenly divides both numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex1_copy.png" style="width: 641px; height: 181px;" />
<pre>
<strong>Input:</strong> head = [18,6,10,3]
<strong>Output:</strong> [18,6,6,2,10,1,3]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
- We insert the greatest common divisor of 18 and 6 = 6 between the 1<sup>st</sup> and the 2<sup>nd</sup> nodes.
- We insert the greatest common divisor of 6 and 10 = 2 between the 2<sup>nd</sup> and the 3<sup>rd</sup> nodes.
- We insert the greatest common divisor of 10 and 3 = 1 between the 3<sup>rd</sup> and the 4<sup>th</sup> nodes.
There are no more adjacent nodes, so we return the linked list.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex2_copy1.png" style="width: 51px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [7]
<strong>Output:</strong> [7]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes.
There are no pairs of adjacent nodes, so we return the initial linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>
<li><code>1 <= Node.val <= 1000</code></li>
</ul>
|
Linked List; Math; Number Theory
|
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 insertGreatestCommonDivisors(ListNode head) {
for (ListNode pre = head, cur = head.next; cur != null; cur = cur.next) {
int x = gcd(pre.val, cur.val);
pre.next = new ListNode(x, cur);
pre = cur;
}
return head;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.