Title
stringlengths 3
81
| Description
stringlengths 219
5.66k
⌀ | C
stringclasses 154
values | C#
stringclasses 299
values | C++
stringlengths 88
4.55k
⌀ | Cangjie
stringclasses 3
values | Dart
stringclasses 2
values | Go
stringlengths 47
3.11k
⌀ | Java
stringlengths 86
5.36k
⌀ | JavaScript
stringclasses 465
values | Kotlin
stringclasses 15
values | MySQL
stringclasses 282
values | Nim
stringclasses 4
values | PHP
stringclasses 111
values | Pandas
stringclasses 31
values | Python3
stringlengths 82
4.27k
⌀ | Ruby
stringclasses 8
values | Rust
stringlengths 83
4.8k
⌀ | Scala
stringclasses 5
values | Shell
stringclasses 4
values | Swift
stringclasses 13
values | TypeScript
stringlengths 65
20.6k
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Find Minimum Log Transportation Cost
|
You are given integers
n
,
m
, and
k
.
There are two logs of lengths
n
and
m
units, which need to be transported in three trucks where each truck can carry one log with length
at most
k
units.
You may cut the logs into smaller pieces, where the cost of cutting a log of length
x
into logs of length
len1
and
len2
is
cost = len1 * len2
such that
len1 + len2 = x
.
Return the
minimum total cost
to distribute the logs onto the trucks. If the logs don't need to be cut, the total cost is 0.
Example 1:
Input:
n = 6, m = 5, k = 5
Output:
5
Explanation:
Cut the log with length 6 into logs with length 1 and 5, at a cost equal to
1 * 5 == 5
. Now the three logs of length 1, 5, and 5 can fit in one truck each.
Example 2:
Input:
n = 4, m = 4, k = 6
Output:
0
Explanation:
The two logs can fit in the trucks already, hence we don't need to cut the logs.
Constraints:
2 <= k <= 10
5
1 <= n, m <= 2 * k
The input is generated such that it is always possible to transport the logs.
| null | null |
class Solution {
public:
long long minCuttingCost(int n, int m, int k) {
int x = max(n, m);
return x <= k ? 0 : 1LL * k * (x - k);
}
};
| null | null |
func minCuttingCost(n int, m int, k int) int64 {
x := max(n, m)
if x <= k {
return 0
}
return int64(k * (x - k))
}
|
class Solution {
public long minCuttingCost(int n, int m, int k) {
int x = Math.max(n, m);
return x <= k ? 0 : 1L * k * (x - k);
}
}
| null | null | null | null | null | null |
class Solution:
def minCuttingCost(self, n: int, m: int, k: int) -> int:
x = max(n, m)
return 0 if x <= k else k * (x - k)
| null | null | null | null | null |
function minCuttingCost(n: number, m: number, k: number): number {
const x = Math.max(n, m);
return x <= k ? 0 : k * (x - k);
}
|
Maximum Gap
|
Given an integer array
nums
, return
the maximum difference between two successive elements in its sorted form
. If the array contains less than two elements, return
0
.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input:
nums = [3,6,9,1]
Output:
3
Explanation:
The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input:
nums = [10]
Output:
0
Explanation:
The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] <= 10
9
| null |
using System;
using System.Linq;
public class Solution {
public int MaximumGap(int[] nums) {
if (nums.Length < 2) return 0;
var max = nums.Max();
var min = nums.Min();
var bucketSize = Math.Max(1, (max - min) / (nums.Length - 1));
var buckets = new Tuple<int, int>[(max - min) / bucketSize + 1];
foreach (var num in nums)
{
var index = (num - min) / bucketSize;
if (buckets[index] == null)
{
buckets[index] = Tuple.Create(num, num);
}
else
{
buckets[index] = Tuple.Create(Math.Min(buckets[index].Item1, num), Math.Max(buckets[index].Item2, num));
}
}
var result = 0;
Tuple<int, int> lastBucket = null;
for (var i = 0; i < buckets.Length; ++i)
{
if (buckets[i] != null)
{
if (lastBucket != null)
{
result = Math.Max(result, buckets[i].Item1 - lastBucket.Item2);
}
lastBucket = buckets[i];
}
}
return result;
}
}
|
using pii = pair<int, int>;
class Solution {
public:
const int inf = 0x3f3f3f3f;
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2) return 0;
int mi = inf, mx = -inf;
for (int v : nums) {
mi = min(mi, v);
mx = max(mx, v);
}
int bucketSize = max(1, (mx - mi) / (n - 1));
int bucketCount = (mx - mi) / bucketSize + 1;
vector<pii> buckets(bucketCount, {inf, -inf});
for (int v : nums) {
int i = (v - mi) / bucketSize;
buckets[i].first = min(buckets[i].first, v);
buckets[i].second = max(buckets[i].second, v);
}
int ans = 0;
int prev = inf;
for (auto [curmin, curmax] : buckets) {
if (curmin > curmax) continue;
ans = max(ans, curmin - prev);
prev = curmax;
}
return ans;
}
};
| null | null |
func maximumGap(nums []int) int {
n := len(nums)
if n < 2 {
return 0
}
inf := 0x3f3f3f3f
mi, mx := inf, -inf
for _, v := range nums {
mi = min(mi, v)
mx = max(mx, v)
}
bucketSize := max(1, (mx-mi)/(n-1))
bucketCount := (mx-mi)/bucketSize + 1
buckets := make([][]int, bucketCount)
for i := range buckets {
buckets[i] = []int{inf, -inf}
}
for _, v := range nums {
i := (v - mi) / bucketSize
buckets[i][0] = min(buckets[i][0], v)
buckets[i][1] = max(buckets[i][1], v)
}
ans := 0
prev := inf
for _, bucket := range buckets {
if bucket[0] > bucket[1] {
continue
}
ans = max(ans, bucket[0]-prev)
prev = bucket[1]
}
return ans
}
|
class Solution {
public int maximumGap(int[] nums) {
int n = nums.length;
if (n < 2) {
return 0;
}
int inf = 0x3f3f3f3f;
int mi = inf, mx = -inf;
for (int v : nums) {
mi = Math.min(mi, v);
mx = Math.max(mx, v);
}
int bucketSize = Math.max(1, (mx - mi) / (n - 1));
int bucketCount = (mx - mi) / bucketSize + 1;
int[][] buckets = new int[bucketCount][2];
for (var bucket : buckets) {
bucket[0] = inf;
bucket[1] = -inf;
}
for (int v : nums) {
int i = (v - mi) / bucketSize;
buckets[i][0] = Math.min(buckets[i][0], v);
buckets[i][1] = Math.max(buckets[i][1], v);
}
int prev = inf;
int ans = 0;
for (var bucket : buckets) {
if (bucket[0] > bucket[1]) {
continue;
}
ans = Math.max(ans, bucket[0] - prev);
prev = bucket[1];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumGap(self, nums: List[int]) -> int:
n = len(nums)
if n < 2:
return 0
mi, mx = min(nums), max(nums)
bucket_size = max(1, (mx - mi) // (n - 1))
bucket_count = (mx - mi) // bucket_size + 1
buckets = [[inf, -inf] for _ in range(bucket_count)]
for v in nums:
i = (v - mi) // bucket_size
buckets[i][0] = min(buckets[i][0], v)
buckets[i][1] = max(buckets[i][1], v)
ans = 0
prev = inf
for curmin, curmax in buckets:
if curmin > curmax:
continue
ans = max(ans, curmin - prev)
prev = curmax
return ans
| null | null | null | null | null | null |
Group Employees of the Same Salary 🔒
|
Table:
Employees
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| name | varchar |
| salary | int |
+-------------+---------+
employee_id is the column with unique values for this table.
Each row of this table indicates the employee ID, employee name, and salary.
A company wants to divide the employees into teams such that all the members on each team have the
same salary
. The teams should follow these criteria:
Each team should consist of
at least two
employees.
All the employees on a team should have the
same salary
.
All the employees of the same salary should be assigned to the same team.
If the salary of an employee is unique, we
do not
assign this employee to any team.
A team's ID is assigned based on the
rank of the team's salary
relative to the other teams' salaries, where the team with the
lowest
salary has
team_id = 1
. Note that the salaries for employees not on a team are
not included
in this ranking.
Write a solution to get the
team_id
of each employee that is in a team.
Return the result table ordered by
team_id
in ascending order
. In case of a tie, order it by
employee_id
in
ascending order
.
The result format is in the following example.
Example 1:
Input:
Employees table:
+-------------+---------+--------+
| employee_id | name | salary |
+-------------+---------+--------+
| 2 | Meir | 3000 |
| 3 | Michael | 3000 |
| 7 | Addilyn | 7400 |
| 8 | Juan | 6100 |
| 9 | Kannon | 7400 |
+-------------+---------+--------+
Output:
+-------------+---------+--------+---------+
| employee_id | name | salary | team_id |
+-------------+---------+--------+---------+
| 2 | Meir | 3000 | 1 |
| 3 | Michael | 3000 | 1 |
| 7 | Addilyn | 7400 | 2 |
| 9 | Kannon | 7400 | 2 |
+-------------+---------+--------+---------+
Explanation:
Meir (employee_id=2) and Michael (employee_id=3) are in the same team because they have the same salary of 3000.
Addilyn (employee_id=7) and Kannon (employee_id=9) are in the same team because they have the same salary of 7400.
Juan (employee_id=8) is not included in any team because their salary of 6100 is unique (i.e. no other employee has the same salary).
The team IDs are assigned as follows (based on salary ranking, lowest first):
- team_id=1: Meir and Michael, a salary of 3000
- team_id=2: Addilyn and Kannon, a salary of 7400
Juan's salary of 6100 is not included in the ranking because they are not on a team.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
WITH
S AS (
SELECT salary
FROM Employees
GROUP BY salary
HAVING COUNT(1) > 1
),
T AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary) AS team_id
FROM S
)
SELECT e.*, t.team_id
FROM
Employees AS e
JOIN T AS t ON e.salary = t.salary
ORDER BY 4, 1;
| null | null | null | null | null | null | null | null | null | null |
Paint House II 🔒
|
There are a row of
n
houses, each house can be painted with one of the
k
colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an
n x k
cost matrix costs.
For example,
costs[0][0]
is the cost of painting house
0
with color
0
;
costs[1][2]
is the cost of painting house
1
with color
2
, and so on...
Return
the minimum cost to paint all houses
.
Example 1:
Input:
costs = [[1,5,3],[2,9,4]]
Output:
5
Explanation:
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
Example 2:
Input:
costs = [[1,3],[2,4]]
Output:
5
Constraints:
costs.length == n
costs[i].length == k
1 <= n <= 100
2 <= k <= 20
1 <= costs[i][j] <= 20
Follow up:
Could you solve it in
O(nk)
runtime?
| null | null |
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
int n = costs.size(), k = costs[0].size();
vector<int> f = costs[0];
for (int i = 1; i < n; ++i) {
vector<int> g = costs[i];
for (int j = 0; j < k; ++j) {
int t = INT_MAX;
for (int h = 0; h < k; ++h) {
if (h != j) {
t = min(t, f[h]);
}
}
g[j] += t;
}
f = move(g);
}
return *min_element(f.begin(), f.end());
}
};
| null | null |
func minCostII(costs [][]int) int {
n, k := len(costs), len(costs[0])
f := cp(costs[0])
for i := 1; i < n; i++ {
g := cp(costs[i])
for j := 0; j < k; j++ {
t := math.MaxInt32
for h := 0; h < k; h++ {
if h != j && t > f[h] {
t = f[h]
}
}
g[j] += t
}
f = g
}
return slices.Min(f)
}
func cp(arr []int) []int {
t := make([]int, len(arr))
copy(t, arr)
return t
}
|
class Solution {
public int minCostII(int[][] costs) {
int n = costs.length, k = costs[0].length;
int[] f = costs[0].clone();
for (int i = 1; i < n; ++i) {
int[] g = costs[i].clone();
for (int j = 0; j < k; ++j) {
int t = Integer.MAX_VALUE;
for (int h = 0; h < k; ++h) {
if (h != j) {
t = Math.min(t, f[h]);
}
}
g[j] += t;
}
f = g;
}
return Arrays.stream(f).min().getAsInt();
}
}
| null | null | null | null | null | null |
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
n, k = len(costs), len(costs[0])
f = costs[0][:]
for i in range(1, n):
g = costs[i][:]
for j in range(k):
t = min(f[h] for h in range(k) if h != j)
g[j] += t
f = g
return min(f)
| null | null | null | null | null | null |
Longest Even Odd Subarray With Threshold
|
You are given a
0-indexed
integer array
nums
and an integer
threshold
.
Find the length of the
longest subarray
of
nums
starting at index
l
and ending at index
r
(0 <= l <= r < nums.length)
that satisfies the following conditions:
nums[l] % 2 == 0
For all indices
i
in the range
[l, r - 1]
,
nums[i] % 2 != nums[i + 1] % 2
For all indices
i
in the range
[l, r]
,
nums[i] <= threshold
Return
an integer denoting the length of the longest such subarray.
Note:
A
subarray
is a contiguous non-empty sequence of elements within an array.
Example 1:
Input:
nums = [3,2,5,4], threshold = 5
Output:
3
Explanation:
In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions.
Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.
Example 2:
Input:
nums = [1,2], threshold = 2
Output:
1
Explanation:
In this example, we can select the subarray that starts at l = 1 and ends at r = 1 => [2].
It satisfies all the conditions and we can show that 1 is the maximum possible achievable length.
Example 3:
Input:
nums = [2,3,4,5], threshold = 4
Output:
3
Explanation:
In this example, we can select the subarray that starts at l = 0 and ends at r = 2 => [2,3,4].
It satisfies all the conditions.
Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= threshold <= 100
| null | null |
class Solution {
public:
int longestAlternatingSubarray(vector<int>& nums, int threshold) {
int ans = 0;
for (int l = 0, n = nums.size(); l < n;) {
if (nums[l] % 2 == 0 && nums[l] <= threshold) {
int r = l + 1;
while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) {
++r;
}
ans = max(ans, r - l);
l = r;
} else {
++l;
}
}
return ans;
}
};
| null | null |
func longestAlternatingSubarray(nums []int, threshold int) (ans int) {
for l, n := 0, len(nums); l < n; {
if nums[l]%2 == 0 && nums[l] <= threshold {
r := l + 1
for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold {
r++
}
ans = max(ans, r-l)
l = r
} else {
l++
}
}
return
}
|
class Solution {
public int longestAlternatingSubarray(int[] nums, int threshold) {
int ans = 0;
for (int l = 0, n = nums.length; l < n;) {
if (nums[l] % 2 == 0 && nums[l] <= threshold) {
int r = l + 1;
while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) {
++r;
}
ans = Math.max(ans, r - l);
l = r;
} else {
++l;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
ans, l, n = 0, 0, len(nums)
while l < n:
if nums[l] % 2 == 0 and nums[l] <= threshold:
r = l + 1
while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold:
r += 1
ans = max(ans, r - l)
l = r
else:
l += 1
return ans
| null | null | null | null | null |
function longestAlternatingSubarray(nums: number[], threshold: number): number {
const n = nums.length;
let ans = 0;
for (let l = 0; l < n; ) {
if (nums[l] % 2 === 0 && nums[l] <= threshold) {
let r = l + 1;
while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) {
++r;
}
ans = Math.max(ans, r - l);
l = r;
} else {
++l;
}
}
return ans;
}
|
K Inverse Pairs Array
|
For an integer array
nums
, an
inverse pair
is a pair of integers
[i, j]
where
0 <= i < j < nums.length
and
nums[i] > nums[j]
.
Given two integers n and k, return the number of different arrays consisting of numbers from
1
to
n
such that there are exactly
k
inverse pairs
. Since the answer can be huge, return it
modulo
10
9
+ 7
.
Example 1:
Input:
n = 3, k = 0
Output:
1
Explanation:
Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
Example 2:
Input:
n = 3, k = 1
Output:
2
Explanation:
The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
Constraints:
1 <= n <= 1000
0 <= k <= 1000
| null | null |
class Solution {
public:
int kInversePairs(int n, int k) {
int f[k + 1];
int s[k + 2];
memset(f, 0, sizeof(f));
f[0] = 1;
fill(s, s + k + 2, 1);
s[0] = 0;
const int mod = 1e9 + 7;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
f[j] = (s[j + 1] - s[max(0, j - (i - 1))] + mod) % mod;
}
for (int j = 1; j <= k + 1; ++j) {
s[j] = (s[j - 1] + f[j - 1]) % mod;
}
}
return f[k];
}
};
| null | null |
func kInversePairs(n int, k int) int {
f := make([]int, k+1)
s := make([]int, k+2)
f[0] = 1
for i, x := range f {
s[i+1] = s[i] + x
}
const mod = 1e9 + 7
for i := 1; i <= n; i++ {
for j := 1; j <= k; j++ {
f[j] = (s[j+1] - s[max(0, j-(i-1))] + mod) % mod
}
for j := 1; j <= k+1; j++ {
s[j] = (s[j-1] + f[j-1]) % mod
}
}
return f[k]
}
|
class Solution {
public int kInversePairs(int n, int k) {
final int mod = (int) 1e9 + 7;
int[] f = new int[k + 1];
int[] s = new int[k + 2];
f[0] = 1;
Arrays.fill(s, 1);
s[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
f[j] = (s[j + 1] - s[Math.max(0, j - (i - 1))] + mod) % mod;
}
for (int j = 1; j <= k + 1; ++j) {
s[j] = (s[j - 1] + f[j - 1]) % mod;
}
}
return f[k];
}
}
| null | null | null | null | null | null |
class Solution:
def kInversePairs(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [1] + [0] * k
s = [0] * (k + 2)
for i in range(1, n + 1):
for j in range(1, k + 1):
f[j] = (s[j + 1] - s[max(0, j - (i - 1))]) % mod
for j in range(1, k + 2):
s[j] = (s[j - 1] + f[j - 1]) % mod
return f[k]
| null | null | null | null | null |
function kInversePairs(n: number, k: number): number {
const f: number[] = Array(k + 1).fill(0);
f[0] = 1;
const s: number[] = Array(k + 2).fill(1);
s[0] = 0;
const mod: number = 1e9 + 7;
for (let i = 1; i <= n; ++i) {
for (let j = 1; j <= k; ++j) {
f[j] = (s[j + 1] - s[Math.max(0, j - (i - 1))] + mod) % mod;
}
for (let j = 1; j <= k + 1; ++j) {
s[j] = (s[j - 1] + f[j - 1]) % mod;
}
}
return f[k];
}
|
Check if Grid Satisfies Conditions
|
You are given a 2D matrix
grid
of size
m x n
. You need to check if each cell
grid[i][j]
is:
Equal to the cell below it, i.e.
grid[i][j] == grid[i + 1][j]
(if it exists).
Different from the cell to its right, i.e.
grid[i][j] != grid[i][j + 1]
(if it exists).
Return
true
if
all
the cells satisfy these conditions, otherwise, return
false
.
Example 1:
Input:
grid = [[1,0,2],[1,0,2]]
Output:
true
Explanation:
All the cells in the grid satisfy the conditions.
Example 2:
Input:
grid = [[1,1,1],[0,0,0]]
Output:
false
Explanation:
All cells in the first row are equal.
Example 3:
Input:
grid = [[1],[2],[3]]
Output:
false
Explanation:
Cells in the first column have different values.
Constraints:
1 <= n, m <= 10
0 <= grid[i][j] <= 9
| null | null |
class Solution {
public:
bool satisfiesConditions(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
};
| null | null |
func satisfiesConditions(grid [][]int) bool {
m, n := len(grid), len(grid[0])
for i, row := range grid {
for j, x := range row {
if i+1 < m && x != grid[i+1][j] {
return false
}
if j+1 < n && x == grid[i][j+1] {
return false
}
}
}
return true
}
|
class Solution {
public boolean satisfiesConditions(int[][] grid) {
int m = grid.length, n = grid[0].length;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def satisfiesConditions(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
if i + 1 < m and x != grid[i + 1][j]:
return False
if j + 1 < n and x == grid[i][j + 1]:
return False
return True
| null | null | null | null | null |
function satisfiesConditions(grid: number[][]): boolean {
const [m, n] = [grid.length, grid[0].length];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] !== grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] === grid[i][j + 1]) {
return false;
}
}
}
return true;
}
|
Word Break
|
Given a string
s
and a dictionary of strings
wordDict
, return
true
if
s
can be segmented into a space-separated sequence of one or more dictionary words.
Note
that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input:
s = "leetcode", wordDict = ["leet","code"]
Output:
true
Explanation:
Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input:
s = "applepenapple", wordDict = ["apple","pen"]
Output:
true
Explanation:
Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output:
false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
and
wordDict[i]
consist of only lowercase English letters.
All the strings of
wordDict
are
unique
.
| null |
public class Solution {
public bool WordBreak(string s, IList<string> wordDict) {
Trie trie = new Trie();
foreach (string w in wordDict) {
trie.Insert(w);
}
int n = s.Length;
bool[] f = new bool[n + 1];
f[n] = true;
for (int i = n - 1; i >= 0; --i) {
Trie node = trie;
for (int j = i; j < n; ++j) {
int k = s[j] - 'a';
if (node.Children[k] == null) {
break;
}
node = node.Children[k];
if (node.IsEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
}
class Trie {
public Trie[] Children { get; set; }
public bool IsEnd { get; set; }
public Trie() {
Children = new Trie[26];
IsEnd = false;
}
public void Insert(string word) {
Trie node = this;
foreach (char c in word) {
int i = c - 'a';
if (node.Children[i] == null) {
node.Children[i] = new Trie();
}
node = node.Children[i];
}
node.IsEnd = true;
}
}
|
class Trie {
public:
vector<Trie*> children;
bool isEnd;
Trie()
: children(26)
, isEnd(false) {}
void insert(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) node->children[c] = new Trie();
node = node->children[c];
}
node->isEnd = true;
}
};
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
Trie trie;
for (auto& w : wordDict) {
trie.insert(w);
}
int n = s.size();
vector<bool> f(n + 1);
f[n] = true;
for (int i = n - 1; ~i; --i) {
Trie* node = ≜
for (int j = i; j < n; ++j) {
int k = s[j] - 'a';
if (!node->children[k]) {
break;
}
node = node->children[k];
if (node->isEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
};
| null | null |
type trie struct {
children [26]*trie
isEnd bool
}
func newTrie() *trie {
return &trie{}
}
func (t *trie) insert(w string) {
node := t
for _, c := range w {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func wordBreak(s string, wordDict []string) bool {
trie := newTrie()
for _, w := range wordDict {
trie.insert(w)
}
n := len(s)
f := make([]bool, n+1)
f[n] = true
for i := n - 1; i >= 0; i-- {
node := trie
for j := i; j < n; j++ {
k := s[j] - 'a'
if node.children[k] == nil {
break
}
node = node.children[k]
if node.isEnd && f[j+1] {
f[i] = true
break
}
}
}
return f[0]
}
|
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Trie trie = new Trie();
for (String w : wordDict) {
trie.insert(w);
}
int n = s.length();
boolean[] f = new boolean[n + 1];
f[n] = true;
for (int i = n - 1; i >= 0; --i) {
Trie node = trie;
for (int j = i; j < n; ++j) {
int k = s.charAt(j) - 'a';
if (node.children[k] == null) {
break;
}
node = node.children[k];
if (node.isEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
}
class Trie {
Trie[] children = new Trie[26];
boolean isEnd = false;
public void insert(String w) {
Trie node = this;
for (int i = 0; i < w.length(); ++i) {
int j = w.charAt(i) - 'a';
if (node.children[j] == null) {
node.children[j] = new Trie();
}
node = node.children[j];
}
node.isEnd = true;
}
}
| null | null | null | null | null | null |
class Trie:
def __init__(self):
self.children: List[Trie | None] = [None] * 26
self.isEnd = False
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord('a')
if not node.children[idx]:
node.children[idx] = Trie()
node = node.children[idx]
node.isEnd = True
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
trie = Trie()
for w in wordDict:
trie.insert(w)
n = len(s)
f = [False] * (n + 1)
f[n] = True
for i in range(n - 1, -1, -1):
node = trie
for j in range(i, n):
idx = ord(s[j]) - ord('a')
if not node.children[idx]:
break
node = node.children[idx]
if node.isEnd and f[j + 1]:
f[i] = True
break
return f[0]
| null |
impl Solution {
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let words: std::collections::HashSet<String> = word_dict.into_iter().collect();
let mut f = vec![false; s.len() + 1];
f[0] = true;
for i in 1..=s.len() {
for j in 0..i {
f[i] |= f[j] && words.contains(&s[j..i]);
}
}
f[s.len()]
}
}
| null | null | null |
function wordBreak(s: string, wordDict: string[]): boolean {
const trie = new Trie();
for (const w of wordDict) {
trie.insert(w);
}
const n = s.length;
const f: boolean[] = new Array(n + 1).fill(false);
f[n] = true;
for (let i = n - 1; i >= 0; --i) {
let node: Trie = trie;
for (let j = i; j < n; ++j) {
const k = s.charCodeAt(j) - 97;
if (!node.children[k]) {
break;
}
node = node.children[k];
if (node.isEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
class Trie {
children: Trie[];
isEnd: boolean;
constructor() {
this.children = new Array(26);
this.isEnd = false;
}
insert(w: string): void {
let node: Trie = this;
for (const c of w) {
const i = c.charCodeAt(0) - 97;
if (!node.children[i]) {
node.children[i] = new Trie();
}
node = node.children[i];
}
node.isEnd = true;
}
}
|
Permutations II
|
Given a collection of numbers,
nums
, that might contain duplicates, return
all possible unique permutations
in any order
.
Example 1:
Input:
nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input:
nums = [1,2,3]
Output:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
| null |
public class Solution {
private List<IList<int>> ans = new List<IList<int>>();
private List<int> t = new List<int>();
private int[] nums;
private bool[] vis;
public IList<IList<int>> PermuteUnique(int[] nums) {
Array.Sort(nums);
int n = nums.Length;
vis = new bool[n];
this.nums = nums;
dfs(0);
return ans;
}
private void dfs(int i) {
if (i == nums.Length) {
ans.Add(new List<int>(t));
return;
}
for (int j = 0; j < nums.Length; ++j) {
if (vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1])) {
continue;
}
vis[j] = true;
t.Add(nums[j]);
dfs(i + 1);
t.RemoveAt(t.Count - 1);
vis[j] = false;
}
}
}
|
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
ranges::sort(nums);
int n = nums.size();
vector<vector<int>> ans;
vector<int> t(n);
vector<bool> vis(n);
auto dfs = [&](this auto&& dfs, int i) {
if (i == n) {
ans.emplace_back(t);
return;
}
for (int j = 0; j < n; ++j) {
if (vis[j] || (j && nums[j] == nums[j - 1] && !vis[j - 1])) {
continue;
}
t[i] = nums[j];
vis[j] = true;
dfs(i + 1);
vis[j] = false;
}
};
dfs(0);
return ans;
}
};
| null | null |
func permuteUnique(nums []int) (ans [][]int) {
slices.Sort(nums)
n := len(nums)
t := make([]int, n)
vis := make([]bool, n)
var dfs func(int)
dfs = func(i int) {
if i == n {
ans = append(ans, slices.Clone(t))
return
}
for j := 0; j < n; j++ {
if vis[j] || (j > 0 && nums[j] == nums[j-1] && !vis[j-1]) {
continue
}
vis[j] = true
t[i] = nums[j]
dfs(i + 1)
vis[j] = false
}
}
dfs(0)
return
}
|
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> t = new ArrayList<>();
private int[] nums;
private boolean[] vis;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
this.nums = nums;
vis = new boolean[nums.length];
dfs(0);
return ans;
}
private void dfs(int i) {
if (i == nums.length) {
ans.add(new ArrayList<>(t));
return;
}
for (int j = 0; j < nums.length; ++j) {
if (vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1])) {
continue;
}
t.add(nums[j]);
vis[j] = true;
dfs(i + 1);
vis[j] = false;
t.remove(t.size() - 1);
}
}
}
|
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function (nums) {
nums.sort((a, b) => a - b);
const n = nums.length;
const ans = [];
const t = Array(n);
const vis = Array(n).fill(false);
const dfs = i => {
if (i === n) {
ans.push(t.slice());
return;
}
for (let j = 0; j < n; ++j) {
if (vis[j] || (j > 0 && nums[j] === nums[j - 1] && !vis[j - 1])) {
continue;
}
t[i] = nums[j];
vis[j] = true;
dfs(i + 1);
vis[j] = false;
}
};
dfs(0);
return ans;
};
| null | null | null | null | null |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def dfs(i: int):
if i == n:
ans.append(t[:])
return
for j in range(n):
if vis[j] or (j and nums[j] == nums[j - 1] and not vis[j - 1]):
continue
t[i] = nums[j]
vis[j] = True
dfs(i + 1)
vis[j] = False
n = len(nums)
nums.sort()
ans = []
t = [0] * n
vis = [False] * n
dfs(0)
return ans
| null |
impl Solution {
pub fn permute_unique(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
nums.sort();
let n = nums.len();
let mut ans = Vec::new();
let mut t = vec![0; n];
let mut vis = vec![false; n];
fn dfs(
nums: &Vec<i32>,
t: &mut Vec<i32>,
vis: &mut Vec<bool>,
ans: &mut Vec<Vec<i32>>,
i: usize,
) {
if i == nums.len() {
ans.push(t.clone());
return;
}
for j in 0..nums.len() {
if vis[j] || (j > 0 && nums[j] == nums[j - 1] && !vis[j - 1]) {
continue;
}
t[i] = nums[j];
vis[j] = true;
dfs(nums, t, vis, ans, i + 1);
vis[j] = false;
}
}
dfs(&nums, &mut t, &mut vis, &mut ans, 0);
ans
}
}
| null | null | null |
function permuteUnique(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const n = nums.length;
const ans: number[][] = [];
const t: number[] = Array(n);
const vis: boolean[] = Array(n).fill(false);
const dfs = (i: number) => {
if (i === n) {
ans.push(t.slice());
return;
}
for (let j = 0; j < n; ++j) {
if (vis[j] || (j > 0 && nums[j] === nums[j - 1] && !vis[j - 1])) {
continue;
}
t[i] = nums[j];
vis[j] = true;
dfs(i + 1);
vis[j] = false;
}
};
dfs(0);
return ans;
}
|
Describe the Painting
|
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a
unique
color. You are given a 2D integer array
segments
, where
segments[i] = [start
i
, end
i
, color
i
]
represents the
half-closed segment
[start
i
, end
i
)
with
color
i
as the color.
The colors in the overlapping segments of the painting were
mixed
when it was painted. When two or more colors mix, they form a new color that can be represented as a
set
of mixed colors.
For example, if colors
2
,
4
, and
6
are mixed, then the resulting mixed color is
{2,4,6}
.
For the sake of simplicity, you should only output the
sum
of the elements in the set rather than the full set.
You want to
describe
the painting with the
minimum
number of non-overlapping
half-closed segments
of these mixed colors. These segments can be represented by the 2D array
painting
where
painting[j] = [left
j
, right
j
, mix
j
]
describes a
half-closed segment
[left
j
, right
j
)
with the mixed color
sum
of
mix
j
.
For example, the painting created with
segments = [[1,4,5],[1,7,7]]
can be described by
painting = [[1,4,12],[4,7,7]]
because:
[1,4)
is colored
{5,7}
(with a sum of
12
) from both the first and second segments.
[4,7)
is colored
{7}
from only the second segment.
Return
the 2D array
painting
describing the finished painting (excluding any parts that are
not
painted). You may return the segments in
any order
.
A
half-closed segment
[a, b)
is the section of the number line between points
a
and
b
including
point
a
and
not including
point
b
.
Example 1:
Input:
segments = [[1,4,5],[4,7,7],[1,7,9]]
Output:
[[1,4,14],[4,7,16]]
Explanation:
The painting can be described as follows:
- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.
- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.
Example 2:
Input:
segments = [[1,7,9],[6,8,15],[8,10,7]]
Output:
[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]
Explanation:
The painting can be described as follows:
- [1,6) is colored 9 from the first segment.
- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.
- [7,8) is colored 15 from the second segment.
- [8,10) is colored 7 from the third segment.
Example 3:
Input:
segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]
Output:
[[1,4,12],[4,7,12]]
Explanation:
The painting can be described as follows:
- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.
- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.
Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.
Constraints:
1 <= segments.length <= 2 * 10
4
segments[i].length == 3
1 <= start
i
< end
i
<= 10
5
1 <= color
i
<= 10
9
Each
color
i
is distinct.
| null | null |
class Solution {
public:
vector<vector<long long>> splitPainting(vector<vector<int>>& segments) {
map<int, long long> d;
for (auto& e : segments) {
int l = e[0], r = e[1], c = e[2];
d[l] += c;
d[r] -= c;
}
vector<vector<long long>> ans;
long long i, j, cur = 0;
for (auto& it : d) {
if (it == *d.begin())
i = it.first;
else {
j = it.first;
if (cur > 0) ans.push_back({i, j, cur});
i = j;
}
cur += it.second;
}
return ans;
}
};
| null | null |
func splitPainting(segments [][]int) [][]int64 {
d := make(map[int]int64)
for _, seg := range segments {
d[seg[0]] += int64(seg[2])
d[seg[1]] -= int64(seg[2])
}
dList := make([]int, 0, len(d))
for k := range d {
dList = append(dList, k)
}
sort.Ints(dList)
var ans [][]int64
i := dList[0]
cur := d[i]
for j := 1; j < len(dList); j++ {
it := d[dList[j]]
if cur > 0 {
ans = append(ans, []int64{int64(i), int64(dList[j]), cur})
}
cur += it
i = dList[j]
}
return ans
}
|
class Solution {
public List<List<Long>> splitPainting(int[][] segments) {
TreeMap<Integer, Long> d = new TreeMap<>();
for (int[] e : segments) {
int l = e[0], r = e[1], c = e[2];
d.put(l, d.getOrDefault(l, 0L) + c);
d.put(r, d.getOrDefault(r, 0L) - c);
}
List<List<Long>> ans = new ArrayList<>();
long i = 0, j = 0;
long cur = 0;
for (Map.Entry<Integer, Long> e : d.entrySet()) {
if (Objects.equals(e.getKey(), d.firstKey())) {
i = e.getKey();
} else {
j = e.getKey();
if (cur > 0) {
ans.add(Arrays.asList(i, j, cur));
}
i = j;
}
cur += e.getValue();
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
d = defaultdict(int)
for l, r, c in segments:
d[l] += c
d[r] -= c
s = sorted([[k, v] for k, v in d.items()])
n = len(s)
for i in range(1, n):
s[i][1] += s[i - 1][1]
return [[s[i][0], s[i + 1][0], s[i][1]] for i in range(n - 1) if s[i][1]]
| null | null | null | null | null | null |
Chalkboard XOR Game
|
You are given an array of integers
nums
represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become
0
, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is
0
.
Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to
0
, then that player wins.
Return
true
if and only if Alice wins the game, assuming both players play optimally
.
Example 1:
Input:
nums = [1,1,2]
Output:
false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Example 2:
Input:
nums = [0,1]
Output:
true
Example 3:
Input:
nums = [1,2,3]
Output:
true
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 2
16
| null | null |
class Solution {
public:
bool xorGame(vector<int>& nums) {
if (nums.size() % 2 == 0) return true;
int x = 0;
for (int& v : nums) x ^= v;
return x == 0;
}
};
| null | null |
func xorGame(nums []int) bool {
if len(nums)%2 == 0 {
return true
}
x := 0
for _, v := range nums {
x ^= v
}
return x == 0
}
|
class Solution {
public boolean xorGame(int[] nums) {
return nums.length % 2 == 0 || Arrays.stream(nums).reduce(0, (a, b) -> a ^ b) == 0;
}
}
| null | null | null | null | null | null |
class Solution:
def xorGame(self, nums: List[int]) -> bool:
return len(nums) % 2 == 0 or reduce(xor, nums) == 0
| null | null | null | null | null | null |
Sum of Total Strength of Wizards
|
As the ruler of a kingdom, you have an army of wizards at your command.
You are given a
0-indexed
integer array
strength
, where
strength[i]
denotes the strength of the
i
th
wizard. For a
contiguous
group of wizards (i.e. the wizards' strengths form a
subarray
of
strength
), the
total strength
is defined as the
product
of the following two values:
The strength of the
weakest
wizard in the group.
The
total
of all the individual strengths of the wizards in the group.
Return
the
sum
of the total strengths of
all
contiguous groups of wizards
. Since the answer may be very large, return it
modulo
10
9
+ 7
.
A
subarray
is a contiguous
non-empty
sequence of elements within an array.
Example 1:
Input:
strength = [1,3,1,2]
Output:
44
Explanation:
The following are all the contiguous groups of wizards:
- [1] from [
1
,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [3] from [1,
3
,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9
- [1] from [1,3,
1
,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1
- [2] from [1,3,1,
2
] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4
- [1,3] from [
1,3
,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4
- [3,1] from [1,
3,1
,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4
- [1,2] from [1,3,
1,2
] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3
- [1,3,1] from [
1,3,1
,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5
- [3,1,2] from [1,
3,1,2
] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6
- [1,3,1,2] from [
1,3,1,2
] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7
The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.
Example 2:
Input:
strength = [5,4,6]
Output:
213
Explanation:
The following are all the contiguous groups of wizards:
- [5] from [
5
,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25
- [4] from [5,
4
,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16
- [6] from [5,4,
6
] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36
- [5,4] from [
5,4
,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36
- [4,6] from [5,
4,6
] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40
- [5,4,6] from [
5,4,6
] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60
The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.
Constraints:
1 <= strength.length <= 10
5
1 <= strength[i] <= 10
9
| null | null |
class Solution {
public:
int totalStrength(vector<int>& strength) {
int n = strength.size();
vector<int> left(n, -1);
vector<int> right(n, n);
stack<int> stk;
for (int i = 0; i < n; ++i) {
while (!stk.empty() && strength[stk.top()] >= strength[i]) stk.pop();
if (!stk.empty()) left[i] = stk.top();
stk.push(i);
}
stk = stack<int>();
for (int i = n - 1; i >= 0; --i) {
while (!stk.empty() && strength[stk.top()] > strength[i]) stk.pop();
if (!stk.empty()) right[i] = stk.top();
stk.push(i);
}
int mod = 1e9 + 7;
vector<int> s(n + 1);
for (int i = 0; i < n; ++i) s[i + 1] = (s[i] + strength[i]) % mod;
vector<int> ss(n + 2);
for (int i = 0; i < n + 1; ++i) ss[i + 1] = (ss[i] + s[i]) % mod;
int ans = 0;
for (int i = 0; i < n; ++i) {
int v = strength[i];
int l = left[i] + 1, r = right[i] - 1;
long a = (long) (i - l + 1) * (ss[r + 2] - ss[i + 1]);
long b = (long) (r - i + 1) * (ss[i + 1] - ss[l]);
ans = (ans + v * ((a - b) % mod)) % mod;
}
return (int) (ans + mod) % mod;
}
};
| null | null |
func totalStrength(strength []int) int {
n := len(strength)
left := make([]int, n)
right := make([]int, n)
for i := range left {
left[i] = -1
right[i] = n
}
stk := []int{}
for i, v := range strength {
for len(stk) > 0 && strength[stk[len(stk)-1]] >= v {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
left[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
stk = []int{}
for i := n - 1; i >= 0; i-- {
for len(stk) > 0 && strength[stk[len(stk)-1]] > strength[i] {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
right[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
mod := int(1e9) + 7
s := make([]int, n+1)
for i, v := range strength {
s[i+1] = (s[i] + v) % mod
}
ss := make([]int, n+2)
for i, v := range s {
ss[i+1] = (ss[i] + v) % mod
}
ans := 0
for i, v := range strength {
l, r := left[i]+1, right[i]-1
a := (ss[r+2] - ss[i+1]) * (i - l + 1)
b := (ss[i+1] - ss[l]) * (r - i + 1)
ans = (ans + v*((a-b)%mod)) % mod
}
return (ans + mod) % mod
}
|
class Solution {
public int totalStrength(int[] strength) {
int n = strength.length;
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, -1);
Arrays.fill(right, n);
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
while (!stk.isEmpty() && strength[stk.peek()] >= strength[i]) {
stk.pop();
}
if (!stk.isEmpty()) {
left[i] = stk.peek();
}
stk.push(i);
}
stk.clear();
for (int i = n - 1; i >= 0; --i) {
while (!stk.isEmpty() && strength[stk.peek()] > strength[i]) {
stk.pop();
}
if (!stk.isEmpty()) {
right[i] = stk.peek();
}
stk.push(i);
}
int mod = (int) 1e9 + 7;
int[] s = new int[n + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = (s[i] + strength[i]) % mod;
}
int[] ss = new int[n + 2];
for (int i = 0; i < n + 1; ++i) {
ss[i + 1] = (ss[i] + s[i]) % mod;
}
long ans = 0;
for (int i = 0; i < n; ++i) {
int v = strength[i];
int l = left[i] + 1, r = right[i] - 1;
long a = (long) (i - l + 1) * (ss[r + 2] - ss[i + 1]);
long b = (long) (r - i + 1) * (ss[i + 1] - ss[l]);
ans = (ans + v * ((a - b) % mod)) % mod;
}
return (int) (ans + mod) % mod;
}
}
| null | null | null | null | null | null |
class Solution:
def totalStrength(self, strength: List[int]) -> int:
n = len(strength)
left = [-1] * n
right = [n] * n
stk = []
for i, v in enumerate(strength):
while stk and strength[stk[-1]] >= v:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
while stk and strength[stk[-1]] > strength[i]:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
ss = list(accumulate(list(accumulate(strength, initial=0)), initial=0))
mod = int(1e9) + 7
ans = 0
for i, v in enumerate(strength):
l, r = left[i] + 1, right[i] - 1
a = (ss[r + 2] - ss[i + 1]) * (i - l + 1)
b = (ss[i + 1] - ss[l]) * (r - i + 1)
ans = (ans + (a - b) * v) % mod
return ans
| null | null | null | null | null | null |
Subarrays with XOR at Least K 🔒
|
Given an array of positive integers
nums
of length
n
and a non‑negative integer
k
.
Return the number of
contiguous
subarrays
whose bitwise XOR of all elements is
greater
than or
equal
to
k
.
Example 1:
Input:
nums = [3,1,2,3], k = 2
Output:
6
Explanation:
The valid subarrays with
XOR >= 2
are
[3]
at index 0,
[3, 1]
at indices 0 - 1,
[3, 1, 2, 3]
at indices 0 - 3,
[1, 2]
at indices 1 - 2,
[2]
at index 2, and
[3]
at index 3; there are 6 in total.
Example 2:
Input:
nums = [0,0,0], k = 0
Output:
6
Explanation:
Every contiguous subarray yields
XOR = 0
, which meets
k = 0
. There are 6 such subarrays in total.
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] <= 10
9
0 <= k <= 10
9
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Minimum Steps to Convert String with Operations
|
You are given two strings,
word1
and
word2
, of equal length. You need to transform
word1
into
word2
.
For this, divide
word1
into one or more
contiguous
substrings
. For each substring
substr
you can perform the following operations:
Replace:
Replace the character at any one index of
substr
with another lowercase English letter.
Swap:
Swap any two characters in
substr
.
Reverse Substring:
Reverse
substr
.
Each of these counts as
one
operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).
Return the
minimum number of operations
required to transform
word1
into
word2
.
Example 1:
Input:
word1 = "abcdf", word2 = "dacbe"
Output:
4
Explanation:
Divide
word1
into
"ab"
,
"c"
, and
"df"
. The operations are:
For the substring
"ab"
,
Perform operation of type 3 on
"ab" -> "ba"
.
Perform operation of type 1 on
"ba" -> "da"
.
For the substring
"c"
do no operations.
For the substring
"df"
,
Perform operation of type 1 on
"df" -> "bf"
.
Perform operation of type 1 on
"bf" -> "be"
.
Example 2:
Input:
word1 = "abceded", word2 = "baecfef"
Output:
4
Explanation:
Divide
word1
into
"ab"
,
"ce"
, and
"ded"
. The operations are:
For the substring
"ab"
,
Perform operation of type 2 on
"ab" -> "ba"
.
For the substring
"ce"
,
Perform operation of type 2 on
"ce" -> "ec"
.
For the substring
"ded"
,
Perform operation of type 1 on
"ded" -> "fed"
.
Perform operation of type 1 on
"fed" -> "fef"
.
Example 3:
Input:
word1 = "abcdef", word2 = "fedabc"
Output:
2
Explanation:
Divide
word1
into
"abcdef"
. The operations are:
For the substring
"abcdef"
,
Perform operation of type 3 on
"abcdef" -> "fedcba"
.
Perform operation of type 2 on
"fedcba" -> "fedabc"
.
Constraints:
1 <= word1.length == word2.length <= 100
word1
and
word2
consist only of lowercase English letters.
| null | null |
class Solution {
public:
int minOperations(string word1, string word2) {
int n = word1.length();
vector<int> f(n + 1, INT_MAX);
f[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
int a = calc(word1, word2, j, i - 1, false);
int b = 1 + calc(word1, word2, j, i - 1, true);
int t = min(a, b);
f[i] = min(f[i], f[j] + t);
}
}
return f[n];
}
private:
int calc(const string& word1, const string& word2, int l, int r, bool rev) {
int cnt[26][26] = {0};
int res = 0;
for (int i = l; i <= r; ++i) {
int j = rev ? r - (i - l) : i;
int a = word1[j] - 'a';
int b = word2[i] - 'a';
if (a != b) {
if (cnt[b][a] > 0) {
cnt[b][a]--;
} else {
cnt[a][b]++;
res++;
}
}
}
return res;
}
};
| null | null |
func minOperations(word1 string, word2 string) int {
n := len(word1)
f := make([]int, n+1)
for i := range f {
f[i] = math.MaxInt32
}
f[0] = 0
calc := func(l, r int, rev bool) int {
var cnt [26][26]int
res := 0
for i := l; i <= r; i++ {
j := i
if rev {
j = r - (i - l)
}
a := word1[j] - 'a'
b := word2[i] - 'a'
if a != b {
if cnt[b][a] > 0 {
cnt[b][a]--
} else {
cnt[a][b]++
res++
}
}
}
return res
}
for i := 1; i <= n; i++ {
for j := 0; j < i; j++ {
a := calc(j, i-1, false)
b := 1 + calc(j, i-1, true)
t := min(a, b)
f[i] = min(f[i], f[j]+t)
}
}
return f[n]
}
|
class Solution {
public int minOperations(String word1, String word2) {
int n = word1.length();
int[] f = new int[n + 1];
Arrays.fill(f, Integer.MAX_VALUE);
f[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
int a = calc(word1, word2, j, i - 1, false);
int b = 1 + calc(word1, word2, j, i - 1, true);
int t = Math.min(a, b);
f[i] = Math.min(f[i], f[j] + t);
}
}
return f[n];
}
private int calc(String word1, String word2, int l, int r, boolean rev) {
int[][] cnt = new int[26][26];
int res = 0;
for (int i = l; i <= r; i++) {
int j = rev ? r - (i - l) : i;
int a = word1.charAt(j) - 'a';
int b = word2.charAt(i) - 'a';
if (a != b) {
if (cnt[b][a] > 0) {
cnt[b][a]--;
} else {
cnt[a][b]++;
res++;
}
}
}
return res;
}
}
| null | null | null | null | null | null |
class Solution:
def minOperations(self, word1: str, word2: str) -> int:
def calc(l: int, r: int, rev: bool) -> int:
cnt = Counter()
res = 0
for i in range(l, r + 1):
j = r - (i - l) if rev else i
a, b = word1[j], word2[i]
if a != b:
if cnt[(b, a)] > 0:
cnt[(b, a)] -= 1
else:
cnt[(a, b)] += 1
res += 1
return res
n = len(word1)
f = [inf] * (n + 1)
f[0] = 0
for i in range(1, n + 1):
for j in range(i):
t = min(calc(j, i - 1, False), 1 + calc(j, i - 1, True))
f[i] = min(f[i], f[j] + t)
return f[n]
| null |
impl Solution {
pub fn min_operations(word1: String, word2: String) -> i32 {
let n = word1.len();
let word1 = word1.as_bytes();
let word2 = word2.as_bytes();
let mut f = vec![i32::MAX; n + 1];
f[0] = 0;
for i in 1..=n {
for j in 0..i {
let a = Self::calc(word1, word2, j, i - 1, false);
let b = 1 + Self::calc(word1, word2, j, i - 1, true);
let t = a.min(b);
f[i] = f[i].min(f[j] + t);
}
}
f[n]
}
fn calc(word1: &[u8], word2: &[u8], l: usize, r: usize, rev: bool) -> i32 {
let mut cnt = [[0i32; 26]; 26];
let mut res = 0;
for i in l..=r {
let j = if rev { r - (i - l) } else { i };
let a = (word1[j] - b'a') as usize;
let b = (word2[i] - b'a') as usize;
if a != b {
if cnt[b][a] > 0 {
cnt[b][a] -= 1;
} else {
cnt[a][b] += 1;
res += 1;
}
}
}
res
}
}
| null | null | null |
function minOperations(word1: string, word2: string): number {
const n = word1.length;
const f = Array(n + 1).fill(Number.MAX_SAFE_INTEGER);
f[0] = 0;
function calc(l: number, r: number, rev: boolean): number {
const cnt: number[][] = Array.from({ length: 26 }, () => Array(26).fill(0));
let res = 0;
for (let i = l; i <= r; i++) {
const j = rev ? r - (i - l) : i;
const a = word1.charCodeAt(j) - 97;
const b = word2.charCodeAt(i) - 97;
if (a !== b) {
if (cnt[b][a] > 0) {
cnt[b][a]--;
} else {
cnt[a][b]++;
res++;
}
}
}
return res;
}
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) {
const a = calc(j, i - 1, false);
const b = 1 + calc(j, i - 1, true);
const t = Math.min(a, b);
f[i] = Math.min(f[i], f[j] + t);
}
}
return f[n];
}
|
Reverse String
|
Write a function that reverses a string. The input string is given as an array of characters
s
.
You must do this by modifying the input array
in-place
with
O(1)
extra memory.
Example 1:
Input:
s = ["h","e","l","l","o"]
Output:
["o","l","l","e","h"]
Example 2:
Input:
s = ["H","a","n","n","a","h"]
Output:
["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 10
5
s[i]
is a
printable ascii character
.
| null | null |
class Solution {
public:
void reverseString(vector<char>& s) {
for (int i = 0, j = s.size() - 1; i < j;) {
swap(s[i++], s[j--]);
}
}
};
| null | null |
func reverseString(s []byte) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
|
class Solution {
public void reverseString(char[] s) {
for (int i = 0, j = s.length - 1; i < j; ++i, --j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
|
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
for (let i = 0, j = s.length - 1; i < j; ++i, --j) {
[s[i], s[j]] = [s[j], s[i]];
}
};
| null | null | null | null | null |
class Solution:
def reverseString(self, s: List[str]) -> None:
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
| null |
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
let mut i = 0;
let mut j = s.len() - 1;
while i < j {
s.swap(i, j);
i += 1;
j -= 1;
}
}
}
| null | null | null |
/**
Do not return anything, modify s in-place instead.
*/
function reverseString(s: string[]): void {
for (let i = 0, j = s.length - 1; i < j; ++i, --j) {
[s[i], s[j]] = [s[j], s[i]];
}
}
|
Make String Anti-palindrome 🔒
|
We call a string
s
of
even
length
n
an
anti-palindrome
if for each index
0 <= i < n
,
s[i] != s[n - i - 1]
.
Given a string
s
, your task is to make
s
an
anti-palindrome
by doing
any
number of operations (including zero).
In one operation, you can select two characters from
s
and swap them.
Return
the resulting string. If multiple strings meet the conditions, return the
lexicographically smallest
one. If it can't be made into an anti-palindrome, return
"-1"
.
Example 1:
Input:
s = "abca"
Output:
"aabc"
Explanation:
"aabc"
is an anti-palindrome string since
s[0] != s[3]
and
s[1] != s[2]
. Also, it is a rearrangement of
"abca"
.
Example 2:
Input:
s = "abba"
Output:
"aabb"
Explanation:
"aabb"
is an anti-palindrome string since
s[0] != s[3]
and
s[1] != s[2]
. Also, it is a rearrangement of
"abba"
.
Example 3:
Input:
s = "cccd"
Output:
"-1"
Explanation:
You can see that no matter how you rearrange the characters of
"cccd"
, either
s[0] == s[3]
or
s[1] == s[2]
. So it can not form an anti-palindrome string.
Constraints:
2 <= s.length <= 10
5
s.length % 2 == 0
s
consists only of lowercase English letters.
| null | null |
class Solution {
public:
string makeAntiPalindrome(string s) {
sort(s.begin(), s.end());
int n = s.length();
int m = n / 2;
if (s[m] == s[m - 1]) {
int i = m;
while (i < n && s[i] == s[i - 1]) {
++i;
}
for (int j = m; j < n && s[j] == s[n - j - 1]; ++i, ++j) {
if (i >= n) {
return "-1";
}
swap(s[i], s[j]);
}
}
return s;
}
};
| null | null |
func makeAntiPalindrome(s string) string {
cs := []byte(s)
sort.Slice(cs, func(i, j int) bool { return cs[i] < cs[j] })
n := len(cs)
m := n / 2
if cs[m] == cs[m-1] {
i := m
for i < n && cs[i] == cs[i-1] {
i++
}
for j := m; j < n && cs[j] == cs[n-j-1]; i, j = i+1, j+1 {
if i >= n {
return "-1"
}
cs[i], cs[j] = cs[j], cs[i]
}
}
return string(cs)
}
|
class Solution {
public String makeAntiPalindrome(String s) {
char[] cs = s.toCharArray();
Arrays.sort(cs);
int n = cs.length;
int m = n / 2;
if (cs[m] == cs[m - 1]) {
int i = m;
while (i < n && cs[i] == cs[i - 1]) {
++i;
}
for (int j = m; j < n && cs[j] == cs[n - j - 1]; ++i, ++j) {
if (i >= n) {
return "-1";
}
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
}
}
return new String(cs);
}
}
| null | null | null | null | null | null |
class Solution:
def makeAntiPalindrome(self, s: str) -> str:
cs = sorted(s)
n = len(cs)
m = n // 2
if cs[m] == cs[m - 1]:
i = m
while i < n and cs[i] == cs[i - 1]:
i += 1
j = m
while j < n and cs[j] == cs[n - j - 1]:
if i >= n:
return "-1"
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j + 1
return "".join(cs)
| null | null | null | null | null |
function makeAntiPalindrome(s: string): string {
const cs: string[] = s.split('').sort();
const n: number = cs.length;
const m = n >> 1;
if (cs[m] === cs[m - 1]) {
let i = m;
for (; i < n && cs[i] === cs[i - 1]; i++);
for (let j = m; j < n && cs[j] === cs[n - j - 1]; ++i, ++j) {
if (i >= n) {
return '-1';
}
[cs[j], cs[i]] = [cs[i], cs[j]];
}
}
return cs.join('');
}
|
Word Squares 🔒
|
Given an array of
unique
strings
words
, return
all the
word squares
you can build from
words
. The same word from
words
can be used
multiple times
. You can return the answer in
any order
.
A sequence of strings forms a valid
word square
if the
k
th
row and column read the same string, where
0 <= k < max(numRows, numColumns)
.
For example, the word sequence
["ball","area","lead","lady"]
forms a word square because each word reads the same both horizontally and vertically.
Example 1:
Input:
words = ["area","lead","wall","lady","ball"]
Output:
[["ball","area","lead","lady"],["wall","area","lead","lady"]]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Example 2:
Input:
words = ["abat","baba","atan","atal"]
Output:
[["baba","abat","baba","atal"],["baba","abat","baba","atan"]]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 4
All
words[i]
have the same length.
words[i]
consists of only lowercase English letters.
All
words[i]
are
unique
.
| null | null | null | null | null |
type Trie struct {
children [26]*Trie
v []int
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string, i int) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
node.v = append(node.v, i)
}
}
func (this *Trie) search(word string) []int {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return []int{}
}
node = node.children[c]
}
return node.v
}
func wordSquares(words []string) [][]string {
trie := newTrie()
for i, w := range words {
trie.insert(w, i)
}
ans := [][]string{}
var dfs func([]string)
dfs = func(t []string) {
if len(t) == len(words[0]) {
cp := make([]string, len(t))
copy(cp, t)
ans = append(ans, cp)
return
}
idx := len(t)
pref := []byte{}
for _, v := range t {
pref = append(pref, v[idx])
}
indexes := trie.search(string(pref))
for _, i := range indexes {
t = append(t, words[i])
dfs(t)
t = t[:len(t)-1]
}
}
for _, w := range words {
dfs([]string{w})
}
return ans
}
|
class Trie {
Trie[] children = new Trie[26];
List<Integer> v = new ArrayList<>();
void insert(String word, int i) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
node.v.add(i);
}
}
List<Integer> search(String pref) {
Trie node = this;
for (char c : pref.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return Collections.emptyList();
}
node = node.children[c];
}
return node.v;
}
}
class Solution {
private Trie trie = new Trie();
private String[] words;
private List<List<String>> ans = new ArrayList<>();
public List<List<String>> wordSquares(String[] words) {
this.words = words;
for (int i = 0; i < words.length; ++i) {
trie.insert(words[i], i);
}
List<String> t = new ArrayList<>();
for (String w : words) {
t.add(w);
dfs(t);
t.remove(t.size() - 1);
}
return ans;
}
private void dfs(List<String> t) {
if (t.size() == words[0].length()) {
ans.add(new ArrayList<>(t));
return;
}
int idx = t.size();
StringBuilder pref = new StringBuilder();
for (String x : t) {
pref.append(x.charAt(idx));
}
List<Integer> indexes = trie.search(pref.toString());
for (int i : indexes) {
t.add(words[i]);
dfs(t);
t.remove(t.size() - 1);
}
}
}
| null | null | null | null | null | null |
class Trie:
def __init__(self):
self.children = [None] * 26
self.v = []
def insert(self, w, i):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.v.append(i)
def search(self, w):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return []
node = node.children[idx]
return node.v
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
def dfs(t):
if len(t) == len(words[0]):
ans.append(t[:])
return
idx = len(t)
pref = [v[idx] for v in t]
indexes = trie.search(''.join(pref))
for i in indexes:
t.append(words[i])
dfs(t)
t.pop()
trie = Trie()
ans = []
for i, w in enumerate(words):
trie.insert(w, i)
for w in words:
dfs([w])
return ans
| null | null | null | null | null | null |
Make Lexicographically Smallest Array by Swapping Elements
|
You are given a
0-indexed
array of
positive
integers
nums
and a
positive
integer
limit
.
In one operation, you can choose any two indices
i
and
j
and swap
nums[i]
and
nums[j]
if
|nums[i] - nums[j]| <= limit
.
Return
the
lexicographically smallest array
that can be obtained by performing the operation any number of times
.
An array
a
is lexicographically smaller than an array
b
if in the first position where
a
and
b
differ, array
a
has an element that is less than the corresponding element in
b
. For example, the array
[2,10,3]
is lexicographically smaller than the array
[10,2,3]
because they differ at index
0
and
2 < 10
.
Example 1:
Input:
nums = [1,5,3,9,8], limit = 2
Output:
[1,3,5,8,9]
Explanation:
Apply the operation 2 times:
- Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8]
- Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9]
We cannot obtain a lexicographically smaller array by applying any more operations.
Note that it may be possible to get the same result by doing different operations.
Example 2:
Input:
nums = [1,7,6,18,2,1], limit = 3
Output:
[1,6,7,18,1,2]
Explanation:
Apply the operation 3 times:
- Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1]
- Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1]
- Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2]
We cannot obtain a lexicographically smaller array by applying any more operations.
Example 3:
Input:
nums = [1,7,28,19,10], limit = 3
Output:
[1,7,28,19,10]
Explanation:
[1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices.
Constraints:
1 <= nums.length <= 10
5
1 <= nums[i] <= 10
9
1 <= limit <= 10
9
| null | null |
class Solution {
public:
vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) {
int n = nums.size();
vector<int> idx(n);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) {
return nums[i] < nums[j];
});
vector<int> ans(n);
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) {
++j;
}
vector<int> t(idx.begin() + i, idx.begin() + j);
sort(t.begin(), t.end());
for (int k = i; k < j; ++k) {
ans[t[k - i]] = nums[idx[k]];
}
i = j;
}
return ans;
}
};
| null | null |
func lexicographicallySmallestArray(nums []int, limit int) []int {
n := len(nums)
idx := make([]int, n)
for i := range idx {
idx[i] = i
}
slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] })
ans := make([]int, n)
for i := 0; i < n; {
j := i + 1
for j < n && nums[idx[j]]-nums[idx[j-1]] <= limit {
j++
}
t := slices.Clone(idx[i:j])
slices.Sort(t)
for k := i; k < j; k++ {
ans[t[k-i]] = nums[idx[k]]
}
i = j
}
return ans
}
|
class Solution {
public int[] lexicographicallySmallestArray(int[] nums, int limit) {
int n = nums.length;
Integer[] idx = new Integer[n];
Arrays.setAll(idx, i -> i);
Arrays.sort(idx, (i, j) -> nums[i] - nums[j]);
int[] ans = new int[n];
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) {
++j;
}
Integer[] t = Arrays.copyOfRange(idx, i, j);
Arrays.sort(t, (x, y) -> x - y);
for (int k = i; k < j; ++k) {
ans[t[k - i]] = nums[idx[k]];
}
i = j;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]:
n = len(nums)
arr = sorted(zip(nums, range(n)))
ans = [0] * n
i = 0
while i < n:
j = i + 1
while j < n and arr[j][0] - arr[j - 1][0] <= limit:
j += 1
idx = sorted(k for _, k in arr[i:j])
for k, (x, _) in zip(idx, arr[i:j]):
ans[k] = x
i = j
return ans
| null | null | null | null | null |
function lexicographicallySmallestArray(nums: number[], limit: number): number[] {
const n: number = nums.length;
const idx: number[] = Array.from({ length: n }, (_, i) => i);
idx.sort((i, j) => nums[i] - nums[j]);
const ans: number[] = Array(n).fill(0);
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) {
j++;
}
const t: number[] = idx.slice(i, j).sort((a, b) => a - b);
for (let k: number = i; k < j; k++) {
ans[t[k - i]] = nums[idx[k]];
}
i = j;
}
return ans;
}
|
Friday Purchases II 🔒
|
Table:
Purchases
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user id, purchase date, and amount spend.
Write a solution to calculate the
total spending
by users on
each Friday
of
every week
in
November 2023
. If there are
no
purchases on a particular
Friday of a week
, it will be considered as
0
.
Return
the result table ordered by week of month
in
ascending
order.
The result format is in the following example.
Example 1:
Input:
Purchases table:
+---------+---------------+--------------+
| user_id | purchase_date | amount_spend |
+---------+---------------+--------------+
| 11 | 2023-11-07 | 1126 |
| 15 | 2023-11-30 | 7473 |
| 17 | 2023-11-14 | 2414 |
| 12 | 2023-11-24 | 9692 |
| 8 | 2023-11-03 | 5117 |
| 1 | 2023-11-16 | 5241 |
| 10 | 2023-11-12 | 8266 |
| 13 | 2023-11-24 | 12000 |
+---------+---------------+--------------+
Output:
+---------------+---------------+--------------+
| week_of_month | purchase_date | total_amount |
+---------------+---------------+--------------+
| 1 | 2023-11-03 | 5117 |
| 2 | 2023-11-10 | 0 |
| 3 | 2023-11-17 | 0 |
| 4 | 2023-11-24 | 21692 |
+---------------+---------------+--------------+
Explanation:
- During the first week of November 2023, transactions amounting to $5,117 occurred on Friday, 2023-11-03.
- For the second week of November 2023, there were no transactions on Friday, 2023-11-10, resulting in a value of 0 in the output table for that day.
- Similarly, during the third week of November 2023, there were no transactions on Friday, 2023-11-17, reflected as 0 in the output table for that specific day.
- In the fourth week of November 2023, two transactions took place on Friday, 2023-11-24, amounting to $12,000 and $9,692 respectively, summing up to a total of $21,692.
Output table is ordered by week_of_month in ascending order.
| null | null | null | null | null | null | null | null | null |
WITH RECURSIVE
T AS (
SELECT '2023-11-01' AS purchase_date
UNION
SELECT purchase_date + INTERVAL 1 DAY
FROM T
WHERE purchase_date < '2023-11-30'
)
SELECT
CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month,
purchase_date,
IFNULL(SUM(amount_spend), 0) AS total_amount
FROM
T
LEFT JOIN Purchases USING (purchase_date)
WHERE DAYOFWEEK(purchase_date) = 6
GROUP BY 2
ORDER BY 1;
| null | null | null | null | null | null | null | null | null | null |
Mice and Cheese
|
There are two mice and
n
different types of cheese, each type of cheese should be eaten by exactly one mouse.
A point of the cheese with index
i
(
0-indexed
) is:
reward1[i]
if the first mouse eats it.
reward2[i]
if the second mouse eats it.
You are given a positive integer array
reward1
, a positive integer array
reward2
, and a non-negative integer
k
.
Return
the maximum
points the mice can achieve if the first mouse eats exactly
k
types of cheese.
Example 1:
Input:
reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
Output:
15
Explanation:
In this example, the first mouse eats the 2
nd
(0-indexed) and the 3
rd
types of cheese, and the second mouse eats the 0
th
and the 1
st
types of cheese.
The total points are 4 + 4 + 3 + 4 = 15.
It can be proven that 15 is the maximum total points that the mice can achieve.
Example 2:
Input:
reward1 = [1,1], reward2 = [1,1], k = 2
Output:
2
Explanation:
In this example, the first mouse eats the 0
th
(0-indexed) and 1
st
types of cheese, and the second mouse does not eat any cheese.
The total points are 1 + 1 = 2.
It can be proven that 2 is the maximum total points that the mice can achieve.
Constraints:
1 <= n == reward1.length == reward2.length <= 10
5
1 <= reward1[i], reward2[i] <= 1000
0 <= k <= n
| null | null |
class Solution {
public:
int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) {
int n = reward1.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += reward2[i];
reward1[i] -= reward2[i];
}
sort(reward1.rbegin(), reward1.rend());
ans += accumulate(reward1.begin(), reward1.begin() + k, 0);
return ans;
}
};
| null | null |
func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) {
for i, x := range reward2 {
ans += x
reward1[i] -= x
}
sort.Ints(reward1)
n := len(reward1)
for i := 0; i < k; i++ {
ans += reward1[n-i-1]
}
return
}
|
class Solution {
public int miceAndCheese(int[] reward1, int[] reward2, int k) {
int ans = 0;
int n = reward1.length;
for (int i = 0; i < n; ++i) {
ans += reward2[i];
reward1[i] -= reward2[i];
}
Arrays.sort(reward1);
for (int i = 0; i < k; ++i) {
ans += reward1[n - i - 1];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:
for i, x in enumerate(reward2):
reward1[i] -= x
reward1.sort(reverse=True)
return sum(reward2) + sum(reward1[:k])
| null | null | null | null | null |
function miceAndCheese(reward1: number[], reward2: number[], k: number): number {
const n = reward1.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
ans += reward2[i];
reward1[i] -= reward2[i];
}
reward1.sort((a, b) => b - a);
for (let i = 0; i < k; ++i) {
ans += reward1[i];
}
return ans;
}
|
Lowest Common Ancestor of a Binary Search Tree
|
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the
definition of LCA on Wikipedia
: “The lowest common ancestor is defined between two nodes
p
and
q
as the lowest node in
T
that has both
p
and
q
as descendants (where we allow
a node to be a descendant of itself
).”
Example 1:
Input:
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output:
6
Explanation:
The LCA of nodes 2 and 8 is 6.
Example 2:
Input:
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output:
2
Explanation:
The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input:
root = [2,1], p = 2, q = 1
Output:
2
Constraints:
The number of nodes in the tree is in the range
[2, 10
5
]
.
-10
9
<= Node.val <= 10
9
All
Node.val
are
unique
.
p != q
p
and
q
will exist in the BST.
| null |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val < Math.Min(p.val, q.val)) {
return LowestCommonAncestor(root.right, p, q);
}
if (root.val > Math.Max(p.val, q.val)) {
return LowestCommonAncestor(root.left, p, q);
}
return root;
}
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val < min(p->val, q->val)) {
return lowestCommonAncestor(root->right, p, q);
}
if (root->val > max(p->val, q->val)) {
return lowestCommonAncestor(root->left, p, q);
}
return root;
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root.Val < p.Val && root.Val < q.Val {
return lowestCommonAncestor(root.Right, p, q)
}
if root.Val > p.Val && root.Val > q.Val {
return lowestCommonAncestor(root.Left, p, q)
}
return root
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val < Math.min(p.val, q.val)) {
return lowestCommonAncestor(root.right, p, q);
}
if (root.val > Math.max(p.val, q.val)) {
return lowestCommonAncestor(root.left, p, q);
}
return root;
}
}
| null | null | null | null | null | null |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(
self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'
) -> 'TreeNode':
if root.val < min(p.val, q.val):
return self.lowestCommonAncestor(root.right, p, q)
if root.val > max(p.val, q.val):
return self.lowestCommonAncestor(root.left, p, q)
return root
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function lowestCommonAncestor(
root: TreeNode | null,
p: TreeNode | null,
q: TreeNode | null,
): TreeNode | null {
if (root.val > p.val && root.val > q.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
|
Build Binary Expression Tree From Infix Expression 🔒
|
A
binary expression tree
is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with 2 children) correspond to the operators
'+'
(addition),
'-'
(subtraction),
'*'
(multiplication), and
'/'
(division).
For each internal node with operator
o
, the
infix expression
it represents is
(A o B)
, where
A
is the expression the left subtree represents and
B
is the expression the right subtree represents.
You are given a string
s
, an
infix expression
containing operands, the operators described above, and parentheses
'('
and
')'
.
Return
any valid
binary expression tree
, whose
in-order traversal
reproduces
s
after omitting the parenthesis from it.
Please note that order of operations applies in
s
.
That is, expressions in parentheses are evaluated first, and multiplication and division happen before addition and subtraction.
Operands must also appear in the
same order
in both
s
and the in-order traversal of the tree.
Example 1:
Input:
s = "3*4-2*5"
Output:
[-,*,*,3,4,2,5]
Explanation:
The tree above is the only valid tree whose inorder traversal produces s.
Example 2:
Input:
s = "2-3/(5*2)+1"
Output:
[+,-,1,2,/,null,null,null,null,3,*,null,null,5,2]
Explanation:
The inorder traversal of the tree above is 2-3/5*2+1 which is the same as s without the parenthesis. The tree also produces the correct result and its operands are in the same order as they appear in s.
The tree below is also a valid binary expression tree with the same inorder traversal as s, but it not a valid answer because it does not evaluate to the same value.
The third tree below is also not valid. Although it produces the same result and is equivalent to the above trees, its inorder traversal does not produce s and its operands are not in the same order as s.
Example 3:
Input:
s = "1+2+3+4+5"
Output:
[+,+,5,+,4,null,null,+,3,null,null,1,2]
Explanation:
The tree [+,+,5,+,+,null,null,1,2,3,4] is also one of many other valid trees.
Constraints:
1 <= s.length <= 100
s
consists of digits and the characters
'('
,
')'
,
'+'
,
'-'
,
'*'
, and
'/'
.
Operands in
s
are
exactly
1 digit.
It is guaranteed that
s
is a valid expression.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Count Pairs That Form a Complete Day I
|
Given an integer array
hours
representing times in
hours
, return an integer denoting the number of pairs
i
,
j
where
i < j
and
hours[i] + hours[j]
forms a
complete day
.
A
complete day
is defined as a time duration that is an
exact
multiple
of 24 hours.
For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
Example 1:
Input:
hours = [12,12,30,24,24]
Output:
2
Explanation:
The pairs of indices that form a complete day are
(0, 1)
and
(3, 4)
.
Example 2:
Input:
hours = [72,48,24,3]
Output:
3
Explanation:
The pairs of indices that form a complete day are
(0, 1)
,
(0, 2)
, and
(1, 2)
.
Constraints:
1 <= hours.length <= 100
1 <= hours[i] <= 10
9
| null | null |
class Solution {
public:
int countCompleteDayPairs(vector<int>& hours) {
int cnt[24]{};
int ans = 0;
for (int x : hours) {
ans += cnt[(24 - x % 24) % 24];
++cnt[x % 24];
}
return ans;
}
};
| null | null |
func countCompleteDayPairs(hours []int) (ans int) {
cnt := [24]int{}
for _, x := range hours {
ans += cnt[(24-x%24)%24]
cnt[x%24]++
}
return
}
|
class Solution {
public int countCompleteDayPairs(int[] hours) {
int[] cnt = new int[24];
int ans = 0;
for (int x : hours) {
ans += cnt[(24 - x % 24) % 24];
++cnt[x % 24];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
cnt = Counter()
ans = 0
for x in hours:
ans += cnt[(24 - (x % 24)) % 24]
cnt[x % 24] += 1
return ans
| null | null | null | null | null |
function countCompleteDayPairs(hours: number[]): number {
const cnt: number[] = Array(24).fill(0);
let ans: number = 0;
for (const x of hours) {
ans += cnt[(24 - (x % 24)) % 24];
++cnt[x % 24];
}
return ans;
}
|
Smallest Palindromic Rearrangement I
|
You are given a
palindromic
string
s
.
Return the
lexicographically smallest
palindromic
permutation
of
s
.
Example 1:
Input:
s = "z"
Output:
"z"
Explanation:
A string of only one character is already the lexicographically smallest palindrome.
Example 2:
Input:
s = "babab"
Output:
"abbba"
Explanation:
Rearranging
"babab"
→
"abbba"
gives the smallest lexicographic palindrome.
Example 3:
Input:
s = "daccad"
Output:
"acddca"
Explanation:
Rearranging
"daccad"
→
"acddca"
gives the smallest lexicographic palindrome.
Constraints:
1 <= s.length <= 10
5
s
consists of lowercase English letters.
s
is guaranteed to be palindromic.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Design Browser History
|
You have a
browser
of one tab where you start on the
homepage
and you can visit another
url
, get back in the history number of
steps
or move forward in the history number of
steps
.
Implement the
BrowserHistory
class:
BrowserHistory(string homepage)
Initializes the object with the
homepage
of the browser.
void visit(string url)
Visits
url
from the current page. It clears up all the forward history.
string back(int steps)
Move
steps
back in history. If you can only return
x
steps in the history and
steps > x
, you will return only
x
steps. Return the current
url
after moving back in history
at most
steps
.
string forward(int steps)
Move
steps
forward in history. If you can only forward
x
steps in the history and
steps > x
, you will forward only
x
steps. Return the current
url
after forwarding in history
at most
steps
.
Example:
Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Explanation:
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
Constraints:
1 <= homepage.length <= 20
1 <= url.length <= 20
1 <= steps <= 100
homepage
and
url
consist of '.' or lower case English letters.
At most
5000
calls will be made to
visit
,
back
, and
forward
.
| null | null |
class BrowserHistory {
public:
stack<string> stk1;
stack<string> stk2;
BrowserHistory(string homepage) {
visit(homepage);
}
void visit(string url) {
stk1.push(url);
stk2 = stack<string>();
}
string back(int steps) {
for (; steps && stk1.size() > 1; --steps) {
stk2.push(stk1.top());
stk1.pop();
}
return stk1.top();
}
string forward(int steps) {
for (; steps && !stk2.empty(); --steps) {
stk1.push(stk2.top());
stk2.pop();
}
return stk1.top();
}
};
/**
* Your BrowserHistory object will be instantiated and called as such:
* BrowserHistory* obj = new BrowserHistory(homepage);
* obj->visit(url);
* string param_2 = obj->back(steps);
* string param_3 = obj->forward(steps);
*/
| null | null |
type BrowserHistory struct {
stk1 []string
stk2 []string
}
func Constructor(homepage string) BrowserHistory {
t := BrowserHistory{[]string{}, []string{}}
t.Visit(homepage)
return t
}
func (this *BrowserHistory) Visit(url string) {
this.stk1 = append(this.stk1, url)
this.stk2 = []string{}
}
func (this *BrowserHistory) Back(steps int) string {
for i := 0; i < steps && len(this.stk1) > 1; i++ {
this.stk2 = append(this.stk2, this.stk1[len(this.stk1)-1])
this.stk1 = this.stk1[:len(this.stk1)-1]
}
return this.stk1[len(this.stk1)-1]
}
func (this *BrowserHistory) Forward(steps int) string {
for i := 0; i < steps && len(this.stk2) > 0; i++ {
this.stk1 = append(this.stk1, this.stk2[len(this.stk2)-1])
this.stk2 = this.stk2[:len(this.stk2)-1]
}
return this.stk1[len(this.stk1)-1]
}
/**
* Your BrowserHistory object will be instantiated and called as such:
* obj := Constructor(homepage);
* obj.Visit(url);
* param_2 := obj.Back(steps);
* param_3 := obj.Forward(steps);
*/
|
class BrowserHistory {
private Deque<String> stk1 = new ArrayDeque<>();
private Deque<String> stk2 = new ArrayDeque<>();
public BrowserHistory(String homepage) {
visit(homepage);
}
public void visit(String url) {
stk1.push(url);
stk2.clear();
}
public String back(int steps) {
for (; steps > 0 && stk1.size() > 1; --steps) {
stk2.push(stk1.pop());
}
return stk1.peek();
}
public String forward(int steps) {
for (; steps > 0 && !stk2.isEmpty(); --steps) {
stk1.push(stk2.pop());
}
return stk1.peek();
}
}
/**
* Your BrowserHistory object will be instantiated and called as such:
* BrowserHistory obj = new BrowserHistory(homepage);
* obj.visit(url);
* String param_2 = obj.back(steps);
* String param_3 = obj.forward(steps);
*/
| null | null | null | null | null | null |
class BrowserHistory:
def __init__(self, homepage: str):
self.stk1 = []
self.stk2 = []
self.visit(homepage)
def visit(self, url: str) -> None:
self.stk1.append(url)
self.stk2.clear()
def back(self, steps: int) -> str:
while steps and len(self.stk1) > 1:
self.stk2.append(self.stk1.pop())
steps -= 1
return self.stk1[-1]
def forward(self, steps: int) -> str:
while steps and self.stk2:
self.stk1.append(self.stk2.pop())
steps -= 1
return self.stk1[-1]
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)
| null | null | null | null | null | null |
Balance a Binary Search Tree
|
Given the
root
of a binary search tree, return
a
balanced
binary search tree with the same node values
. If there is more than one answer, return
any of them
.
A binary search tree is
balanced
if the depth of the two subtrees of every node never differs by more than
1
.
Example 1:
Input:
root = [1,null,2,null,3,null,4,null,null]
Output:
[2,1,3,null,null,null,4]
Explanation:
This is not the only correct answer, [3,1,4,null,2] is also correct.
Example 2:
Input:
root = [2,1,3]
Output:
[2,1,3]
Constraints:
The number of nodes in the tree is in the range
[1, 10
4
]
.
1 <= Node.val <= 10
5
| null | null |
/**
* 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:
TreeNode* balanceBST(TreeNode* root) {
dfs(root);
return build(0, nums.size() - 1);
}
private:
vector<int> nums;
void dfs(TreeNode* root) {
if (!root) {
return;
}
dfs(root->left);
nums.push_back(root->val);
dfs(root->right);
}
TreeNode* build(int i, int j) {
if (i > j) {
return nullptr;
}
int mid = (i + j) >> 1;
TreeNode* left = build(i, mid - 1);
TreeNode* right = build(mid + 1, j);
return new TreeNode(nums[mid], left, right);
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func balanceBST(root *TreeNode) *TreeNode {
ans := []int{}
var dfs func(*TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
dfs(root.Left)
ans = append(ans, root.Val)
dfs(root.Right)
}
var build func(i, j int) *TreeNode
build = func(i, j int) *TreeNode {
if i > j {
return nil
}
mid := (i + j) >> 1
left := build(i, mid-1)
right := build(mid+1, j)
return &TreeNode{Val: ans[mid], Left: left, Right: right}
}
dfs(root)
return build(0, len(ans)-1)
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> nums = new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
dfs(root);
return build(0, nums.size() - 1);
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
nums.add(root.val);
dfs(root.right);
}
private TreeNode build(int i, int j) {
if (i > j) {
return null;
}
int mid = (i + j) >> 1;
TreeNode left = build(i, mid - 1);
TreeNode right = build(mid + 1, j);
return new TreeNode(nums.get(mid), left, right);
}
}
| null | null | null | null | null | null |
# 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 balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(root: TreeNode):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
def build(i: int, j: int) -> TreeNode:
if i > j:
return None
mid = (i + j) >> 1
left = build(i, mid - 1)
right = build(mid + 1, j)
return TreeNode(nums[mid], left, right)
nums = []
dfs(root)
return build(0, len(nums) - 1)
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function balanceBST(root: TreeNode | null): TreeNode | null {
const nums: number[] = [];
const dfs = (root: TreeNode | null): void => {
if (root == null) {
return;
}
dfs(root.left);
nums.push(root.val);
dfs(root.right);
};
const build = (i: number, j: number): TreeNode | null => {
if (i > j) {
return null;
}
const mid: number = (i + j) >> 1;
const left: TreeNode | null = build(i, mid - 1);
const right: TreeNode | null = build(mid + 1, j);
return new TreeNode(nums[mid], left, right);
};
dfs(root);
return build(0, nums.length - 1);
}
|
Number of Integers With Popcount-Depth Equal to K II
|
You are given an integer array
nums
.
For any positive integer
x
, define the following sequence:
p
0
= x
p
i+1
= popcount(p
i
)
for all
i >= 0
, where
popcount(y)
is the number of set bits (1's) in the binary representation of
y
.
This sequence will eventually reach the value 1.
The
popcount-depth
of
x
is defined as the
smallest
integer
d >= 0
such that
p
d
= 1
.
For example, if
x = 7
(binary representation
"111"
). Then, the sequence is:
7 → 3 → 2 → 1
, so the popcount-depth of 7 is 3.
You are also given a 2D integer array
queries
, where each
queries[i]
is either:
[1, l, r, k]
-
Determine
the number of indices
j
such that
l <= j <= r
and the
popcount-depth
of
nums[j]
is equal to
k
.
[2, idx, val]
-
Update
nums[idx]
to
val
.
Return an integer array
answer
, where
answer[i]
is the number of indices for the
i
th
query of type
[1, l, r, k]
.
Example 1:
Input:
nums = [2,4], queries = [[1,0,1,1],[2,1,1],[1,0,1,0]]
Output:
[2,1]
Explanation:
i
queries[i]
nums
binary(
nums
)
popcount-
depth
[l, r]
k
Valid
nums[j]
updated
nums
Answer
0
[1,0,1,1]
[2,4]
[10, 100]
[1, 1]
[0, 1]
1
[0, 1]
—
2
1
[2,1,1]
[2,4]
[10, 100]
[1, 1]
—
—
—
[2,1]
—
2
[1,0,1,0]
[2,1]
[10, 1]
[1, 0]
[0, 1]
0
[1]
—
1
Thus, the final
answer
is
[2, 1]
.
Example 2:
Input:
nums = [3,5,6], queries = [[1,0,2,2],[2,1,4],[1,1,2,1],[1,0,1,0]]
Output:
[3,1,0]
Explanation:
i
queries[i]
nums
binary(
nums
)
popcount-
depth
[l, r]
k
Valid
nums[j]
updated
nums
Answer
0
[1,0,2,2]
[3, 5, 6]
[11, 101, 110]
[2, 2, 2]
[0, 2]
2
[0, 1, 2]
—
3
1
[2,1,4]
[3, 5, 6]
[11, 101, 110]
[2, 2, 2]
—
—
—
[3, 4, 6]
—
2
[1,1,2,1]
[3, 4, 6]
[11, 100, 110]
[2, 1, 2]
[1, 2]
1
[1]
—
1
3
[1,0,1,0]
[3, 4, 6]
[11, 100, 110]
[2, 1, 2]
[0, 1]
0
[]
—
0
Thus, the final
answer
is
[3, 1, 0]
.
Example 3:
Input:
nums = [1,2], queries = [[1,0,1,1],[2,0,3],[1,0,0,1],[1,0,0,2]]
Output:
[1,0,1]
Explanation:
i
queries[i]
nums
binary(
nums
)
popcount-
depth
[l, r]
k
Valid
nums[j]
updated
nums
Answer
0
[1,0,1,1]
[1, 2]
[1, 10]
[0, 1]
[0, 1]
1
[1]
—
1
1
[2,0,3]
[1, 2]
[1, 10]
[0, 1]
—
—
—
[3, 2]
2
[1,0,0,1]
[3, 2]
[11, 10]
[2, 1]
[0, 0]
1
[]
—
0
3
[1,0,0,2]
[3, 2]
[11, 10]
[2, 1]
[0, 0]
2
[0]
—
1
Thus, the final
answer
is
[1, 0, 1]
.
Constraints:
1 <= n == nums.length <= 10
5
1 <= nums[i] <= 10
15
1 <= queries.length <= 10
5
queries[i].length == 3
or
4
queries[i] == [1, l, r, k]
or,
queries[i] == [2, idx, val]
0 <= l <= r <= n - 1
0 <= k <= 5
0 <= idx <= n - 1
1 <= val <= 10
15
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Distribute Candies to People
|
We distribute some number of
candies
, to a row of
n = num_people
people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give
n
candies to the last person.
Then, we go back to the start of the row, giving
n + 1
candies to the first person,
n + 2
candies to the second person, and so on until we give
2 * n
candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length
num_people
and sum
candies
) that represents the final distribution of candies.
Example 1:
Input:
candies = 7, num_people = 4
Output:
[1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].
Example 2:
Input:
candies = 10, num_people = 3
Output:
[5,2,3]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].
Constraints:
1 <= candies <= 10^9
1 <= num_people <= 1000
| null | null |
class Solution {
public:
vector<int> distributeCandies(int candies, int num_people) {
vector<int> ans(num_people);
for (int i = 0; candies > 0; ++i) {
ans[i % num_people] += min(candies, i + 1);
candies -= min(candies, i + 1);
}
return ans;
}
};
| null | null |
func distributeCandies(candies int, num_people int) []int {
ans := make([]int, num_people)
for i := 0; candies > 0; i++ {
ans[i%num_people] += min(candies, i+1)
candies -= min(candies, i+1)
}
return ans
}
|
class Solution {
public int[] distributeCandies(int candies, int num_people) {
int[] ans = new int[num_people];
for (int i = 0; candies > 0; ++i) {
ans[i % num_people] += Math.min(candies, i + 1);
candies -= Math.min(candies, i + 1);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
ans = [0] * num_people
i = 0
while candies:
ans[i % num_people] += min(candies, i + 1)
candies -= min(candies, i + 1)
i += 1
return ans
| null | null | null | null | null |
function distributeCandies(candies: number, num_people: number): number[] {
const ans: number[] = Array(num_people).fill(0);
for (let i = 0; candies > 0; ++i) {
ans[i % num_people] += Math.min(candies, i + 1);
candies -= Math.min(candies, i + 1);
}
return ans;
}
|
Shortest Cycle in a Graph
|
There is a
bi-directional
graph with
n
vertices, where each vertex is labeled from
0
to
n - 1
. The edges in the graph are represented by a given 2D integer array
edges
, where
edges[i] = [u
i
, v
i
]
denotes an edge between vertex
u
i
and vertex
v
i
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
Return
the length of the
shortest
cycle in the graph
. If no cycle exists, return
-1
.
A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.
Example 1:
Input:
n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
Output:
3
Explanation:
The cycle with the smallest length is : 0 -> 1 -> 2 -> 0
Example 2:
Input:
n = 4, edges = [[0,1],[0,2]]
Output:
-1
Explanation:
There are no cycles in this graph.
Constraints:
2 <= n <= 1000
1 <= edges.length <= 1000
edges[i].length == 2
0 <= u
i
, v
i
< n
u
i
!= v
i
There are no repeated edges.
| null | null |
class Solution {
public:
int findShortestCycle(int n, vector<vector<int>>& edges) {
vector<vector<int>> g(n);
for (auto& e : edges) {
int u = e[0], v = e[1];
g[u].push_back(v);
g[v].push_back(u);
}
const int inf = 1 << 30;
auto bfs = [&](int u) -> int {
int dist[n];
memset(dist, -1, sizeof(dist));
dist[u] = 0;
queue<pair<int, int>> q;
q.emplace(u, -1);
int ans = inf;
while (!q.empty()) {
auto p = q.front();
u = p.first;
int fa = p.second;
q.pop();
for (int v : g[u]) {
if (dist[v] < 0) {
dist[v] = dist[u] + 1;
q.emplace(v, u);
} else if (v != fa) {
ans = min(ans, dist[u] + dist[v] + 1);
}
}
}
return ans;
};
int ans = inf;
for (int i = 0; i < n; ++i) {
ans = min(ans, bfs(i));
}
return ans < inf ? ans : -1;
}
};
| null | null |
func findShortestCycle(n int, edges [][]int) int {
g := make([][]int, n)
for _, e := range edges {
u, v := e[0], e[1]
g[u] = append(g[u], v)
g[v] = append(g[v], u)
}
const inf = 1 << 30
bfs := func(u int) int {
dist := make([]int, n)
for i := range dist {
dist[i] = -1
}
dist[u] = 0
q := [][2]int{{u, -1}}
ans := inf
for len(q) > 0 {
p := q[0]
u = p[0]
fa := p[1]
q = q[1:]
for _, v := range g[u] {
if dist[v] < 0 {
dist[v] = dist[u] + 1
q = append(q, [2]int{v, u})
} else if v != fa {
ans = min(ans, dist[u]+dist[v]+1)
}
}
}
return ans
}
ans := inf
for i := 0; i < n; i++ {
ans = min(ans, bfs(i))
}
if ans < inf {
return ans
}
return -1
}
|
class Solution {
private List<Integer>[] g;
private final int inf = 1 << 30;
public int findShortestCycle(int n, int[][] edges) {
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int u = e[0], v = e[1];
g[u].add(v);
g[v].add(u);
}
int ans = inf;
for (int i = 0; i < n; ++i) {
ans = Math.min(ans, bfs(i));
}
return ans < inf ? ans : -1;
}
private int bfs(int u) {
int[] dist = new int[g.length];
Arrays.fill(dist, -1);
dist[u] = 0;
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[] {u, -1});
int ans = inf;
while (!q.isEmpty()) {
var p = q.poll();
u = p[0];
int fa = p[1];
for (int v : g[u]) {
if (dist[v] < 0) {
dist[v] = dist[u] + 1;
q.offer(new int[] {v, u});
} else if (v != fa) {
ans = Math.min(ans, dist[u] + dist[v] + 1);
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
def bfs(u: int) -> int:
dist = [-1] * n
dist[u] = 0
q = deque([(u, -1)])
ans = inf
while q:
u, fa = q.popleft()
for v in g[u]:
if dist[v] < 0:
dist[v] = dist[u] + 1
q.append((v, u))
elif v != fa:
ans = min(ans, dist[u] + dist[v] + 1)
return ans
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
ans = min(bfs(i) for i in range(n))
return ans if ans < inf else -1
| null | null | null | null | null |
function findShortestCycle(n: number, edges: number[][]): number {
const g: number[][] = new Array(n).fill(0).map(() => []);
for (const [u, v] of edges) {
g[u].push(v);
g[v].push(u);
}
const inf = 1 << 30;
let ans = inf;
const bfs = (u: number) => {
const dist: number[] = new Array(n).fill(-1);
dist[u] = 0;
const q: number[][] = [[u, -1]];
let ans = inf;
while (q.length) {
const p = q.shift()!;
u = p[0];
const fa = p[1];
for (const v of g[u]) {
if (dist[v] < 0) {
dist[v] = dist[u] + 1;
q.push([v, u]);
} else if (v !== fa) {
ans = Math.min(ans, dist[u] + dist[v] + 1);
}
}
}
return ans;
};
for (let i = 0; i < n; ++i) {
ans = Math.min(ans, bfs(i));
}
return ans < inf ? ans : -1;
}
|
Minimum Number of Swaps to Make the Binary String Alternating
|
Given a binary string
s
, return
the
minimum
number of character swaps to make it
alternating
, or
-1
if it is impossible.
The string is called
alternating
if no two adjacent characters are equal. For example, the strings
"010"
and
"1010"
are alternating, while the string
"0100"
is not.
Any two characters may be swapped, even if they are
not adjacent
.
Example 1:
Input:
s = "111000"
Output:
1
Explanation:
Swap positions 1 and 4: "1
1
10
0
0" -> "1
0
10
1
0"
The string is now alternating.
Example 2:
Input:
s = "010"
Output:
0
Explanation:
The string is already alternating, no swaps are needed.
Example 3:
Input:
s = "1110"
Output:
-1
Constraints:
1 <= s.length <= 1000
s[i]
is either
'0'
or
'1'
.
| null | null |
class Solution {
public:
int minSwaps(string s) {
int n0 = ranges::count(s, '0');
int n1 = s.size() - n0;
if (abs(n0 - n1) > 1) {
return -1;
}
auto calc = [&](int c) -> int {
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
int x = s[i] - '0';
if ((i & 1 ^ c) != x) {
++cnt;
}
}
return cnt / 2;
};
if (n0 == n1) {
return min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
}
};
| null | null |
func minSwaps(s string) int {
n0 := strings.Count(s, "0")
n1 := len(s) - n0
if abs(n0-n1) > 1 {
return -1
}
calc := func(c int) int {
cnt := 0
for i, ch := range s {
x := int(ch - '0')
if i&1^c != x {
cnt++
}
}
return cnt / 2
}
if n0 == n1 {
return min(calc(0), calc(1))
}
if n0 > n1 {
return calc(0)
}
return calc(1)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
private char[] s;
public int minSwaps(String s) {
this.s = s.toCharArray();
int n1 = 0;
for (char c : this.s) {
n1 += (c - '0');
}
int n0 = this.s.length - n1;
if (Math.abs(n0 - n1) > 1) {
return -1;
}
if (n0 == n1) {
return Math.min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
}
private int calc(int c) {
int cnt = 0;
for (int i = 0; i < s.length; ++i) {
int x = s[i] - '0';
if ((i & 1 ^ c) != x) {
++cnt;
}
}
return cnt / 2;
}
}
|
/**
* @param {string} s
* @return {number}
*/
var minSwaps = function (s) {
const n0 = (s.match(/0/g) || []).length;
const n1 = s.length - n0;
if (Math.abs(n0 - n1) > 1) {
return -1;
}
const calc = c => {
let cnt = 0;
for (let i = 0; i < s.length; i++) {
const x = +s[i];
if (((i & 1) ^ c) !== x) {
cnt++;
}
}
return Math.floor(cnt / 2);
};
if (n0 === n1) {
return Math.min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
};
| null | null | null | null | null |
class Solution:
def minSwaps(self, s: str) -> int:
def calc(c: int) -> int:
return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2
n0 = s.count("0")
n1 = len(s) - n0
if abs(n0 - n1) > 1:
return -1
if n0 == n1:
return min(calc(0), calc(1))
return calc(0 if n0 > n1 else 1)
| null | null | null | null | null |
function minSwaps(s: string): number {
const n0 = (s.match(/0/g) || []).length;
const n1 = s.length - n0;
if (Math.abs(n0 - n1) > 1) {
return -1;
}
const calc = (c: number): number => {
let cnt = 0;
for (let i = 0; i < s.length; i++) {
const x = +s[i];
if (((i & 1) ^ c) !== x) {
cnt++;
}
}
return Math.floor(cnt / 2);
};
if (n0 === n1) {
return Math.min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
}
|
Minimum Number of Steps to Make Two Strings Anagram II
|
You are given two strings
s
and
t
. In one step, you can append
any character
to either
s
or
t
.
Return
the minimum number of steps to make
s
and
t
anagrams
of each other.
An
anagram
of a string is a string that contains the same characters with a different (or the same) ordering.
Example 1:
Input:
s = "
lee
tco
de
", t = "co
a
t
s
"
Output:
7
Explanation:
- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcode
as
".
- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coats
leede
".
"leetcodeas" and "coatsleede" are now anagrams of each other.
We used a total of 2 + 5 = 7 steps.
It can be shown that there is no way to make them anagrams of each other with less than 7 steps.
Example 2:
Input:
s = "night", t = "thing"
Output:
0
Explanation:
The given strings are already anagrams of each other. Thus, we do not need any further steps.
Constraints:
1 <= s.length, t.length <= 2 * 10
5
s
and
t
consist of lowercase English letters.
| null | null |
class Solution {
public:
int minSteps(string s, string t) {
vector<int> cnt(26);
for (char& c : s) ++cnt[c - 'a'];
for (char& c : t) --cnt[c - 'a'];
int ans = 0;
for (int& v : cnt) ans += abs(v);
return ans;
}
};
| null | null |
func minSteps(s string, t string) int {
cnt := make([]int, 26)
for _, c := range s {
cnt[c-'a']++
}
for _, c := range t {
cnt[c-'a']--
}
ans := 0
for _, v := range cnt {
ans += abs(v)
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
public int minSteps(String s, String t) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
for (char c : t.toCharArray()) {
--cnt[c - 'a'];
}
int ans = 0;
for (int v : cnt) {
ans += Math.abs(v);
}
return ans;
}
}
|
/**
* @param {string} s
* @param {string} t
* @return {number}
*/
var minSteps = function (s, t) {
let cnt = new Array(26).fill(0);
for (const c of s) {
++cnt[c.charCodeAt() - 'a'.charCodeAt()];
}
for (const c of t) {
--cnt[c.charCodeAt() - 'a'.charCodeAt()];
}
let ans = 0;
for (const v of cnt) {
ans += Math.abs(v);
}
return ans;
};
| null | null | null | null | null |
class Solution:
def minSteps(self, s: str, t: str) -> int:
cnt = Counter(s)
for c in t:
cnt[c] -= 1
return sum(abs(v) for v in cnt.values())
| null | null | null | null | null |
function minSteps(s: string, t: string): number {
let cnt = new Array(128).fill(0);
for (const c of s) {
++cnt[c.charCodeAt(0)];
}
for (const c of t) {
--cnt[c.charCodeAt(0)];
}
let ans = 0;
for (const v of cnt) {
ans += Math.abs(v);
}
return ans;
}
|
Check if Strings Can be Made Equal With Operations II
|
You are given two strings
s1
and
s2
, both of length
n
, consisting of
lowercase
English letters.
You can apply the following operation on
any
of the two strings
any
number of times:
Choose any two indices
i
and
j
such that
i < j
and the difference
j - i
is
even
, then
swap
the two characters at those indices in the string.
Return
true
if you can make the strings
s1
and
s2
equal, and
false
otherwise
.
Example 1:
Input:
s1 = "abcdba", s2 = "cabdab"
Output:
true
Explanation:
We can apply the following operations on s1:
- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba".
- Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa".
- Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2.
Example 2:
Input:
s1 = "abe", s2 = "bea"
Output:
false
Explanation:
It is not possible to make the two strings equal.
Constraints:
n == s1.length == s2.length
1 <= n <= 10
5
s1
and
s2
consist only of lowercase English letters.
| null | null |
class Solution {
public:
bool checkStrings(string s1, string s2) {
vector<vector<int>> cnt(2, vector<int>(26, 0));
for (int i = 0; i < s1.size(); ++i) {
++cnt[i & 1][s1[i] - 'a'];
--cnt[i & 1][s2[i] - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (cnt[0][i] || cnt[1][i]) {
return false;
}
}
return true;
}
};
| null | null |
func checkStrings(s1 string, s2 string) bool {
cnt := [2][26]int{}
for i := 0; i < len(s1); i++ {
cnt[i&1][s1[i]-'a']++
cnt[i&1][s2[i]-'a']--
}
for i := 0; i < 26; i++ {
if cnt[0][i] != 0 || cnt[1][i] != 0 {
return false
}
}
return true
}
|
class Solution {
public boolean checkStrings(String s1, String s2) {
int[][] cnt = new int[2][26];
for (int i = 0; i < s1.length(); ++i) {
++cnt[i & 1][s1.charAt(i) - 'a'];
--cnt[i & 1][s2.charAt(i) - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (cnt[0][i] != 0 || cnt[1][i] != 0) {
return false;
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def checkStrings(self, s1: str, s2: str) -> bool:
return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted(
s2[1::2]
)
| null | null | null | null | null |
function checkStrings(s1: string, s2: string): boolean {
const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0));
for (let i = 0; i < s1.length; ++i) {
++cnt[i & 1][s1.charCodeAt(i) - 97];
--cnt[i & 1][s2.charCodeAt(i) - 97];
}
for (let i = 0; i < 26; ++i) {
if (cnt[0][i] || cnt[1][i]) {
return false;
}
}
return true;
}
|
Count Positions on Street With Required Brightness 🔒
|
You are given an integer
n
. A perfectly straight street is represented by a number line ranging from
0
to
n - 1
. You are given a 2D integer array
lights
representing the street lamp(s) on the street. Each
lights[i] = [position
i
, range
i
]
indicates that there is a street lamp at position
position
i
that lights up the area from
[max(0, position
i
- range
i
), min(n - 1, position
i
+ range
i
)]
(
inclusive
).
The
brightness
of a position
p
is defined as the number of street lamps that light up the position
p
. You are given a
0-indexed
integer array
requirement
of size
n
where
requirement[i]
is the minimum
brightness
of the
i
th
position on the street.
Return
the number of positions
i
on the street between
0
and
n - 1
that have a
brightness
of
at least
requirement[i]
.
Example 1:
Input:
n = 5, lights = [[0,1],[2,1],[3,2]], requirement = [0,2,1,4,1]
Output:
4
Explanation:
- The first street lamp lights up the area from [max(0, 0 - 1), min(n - 1, 0 + 1)] = [0, 1] (inclusive).
- The second street lamp lights up the area from [max(0, 2 - 1), min(n - 1, 2 + 1)] = [1, 3] (inclusive).
- The third street lamp lights up the area from [max(0, 3 - 2), min(n - 1, 3 + 2)] = [1, 4] (inclusive).
- Position 0 is covered by the first street lamp. It is covered by 1 street lamp which is greater than requirement[0].
- Position 1 is covered by the first, second, and third street lamps. It is covered by 3 street lamps which is greater than requirement[1].
- Position 2 is covered by the second and third street lamps. It is covered by 2 street lamps which is greater than requirement[2].
- Position 3 is covered by the second and third street lamps. It is covered by 2 street lamps which is less than requirement[3].
- Position 4 is covered by the third street lamp. It is covered by 1 street lamp which is equal to requirement[4].
Positions 0, 1, 2, and 4 meet the requirement so we return 4.
Example 2:
Input:
n = 1, lights = [[0,1]], requirement = [2]
Output:
0
Explanation:
- The first street lamp lights up the area from [max(0, 0 - 1), min(n - 1, 0 + 1)] = [0, 0] (inclusive).
- Position 0 is covered by the first street lamp. It is covered by 1 street lamp which is less than requirement[0].
- We return 0 because no position meets their brightness requirement.
Constraints:
1 <= n <= 10
5
1 <= lights.length <= 10
5
0 <= position
i
< n
0 <= range
i
<= 10
5
requirement.length == n
0 <= requirement[i] <= 10
5
| null | null |
class Solution {
public:
int meetRequirement(int n, vector<vector<int>>& lights, vector<int>& requirement) {
vector<int> d(n + 1);
for (const auto& e : lights) {
int i = max(0, e[0] - e[1]), j = min(n - 1, e[0] + e[1]);
++d[i];
--d[j + 1];
}
int s = 0, ans = 0;
for (int i = 0; i < n; ++i) {
s += d[i];
if (s >= requirement[i]) {
++ans;
}
}
return ans;
}
};
| null | null |
func meetRequirement(n int, lights [][]int, requirement []int) (ans int) {
d := make([]int, n+1)
for _, e := range lights {
i, j := max(0, e[0]-e[1]), min(n-1, e[0]+e[1])
d[i]++
d[j+1]--
}
s := 0
for i, r := range requirement {
s += d[i]
if s >= r {
ans++
}
}
return
}
|
class Solution {
public int meetRequirement(int n, int[][] lights, int[] requirement) {
int[] d = new int[n + 1];
for (int[] e : lights) {
int i = Math.max(0, e[0] - e[1]);
int j = Math.min(n - 1, e[0] + e[1]);
++d[i];
--d[j + 1];
}
int s = 0;
int ans = 0;
for (int i = 0; i < n; ++i) {
s += d[i];
if (s >= requirement[i]) {
++ans;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def meetRequirement(
self, n: int, lights: List[List[int]], requirement: List[int]
) -> int:
d = [0] * (n + 1)
for p, r in lights:
i, j = max(0, p - r), min(n - 1, p + r)
d[i] += 1
d[j + 1] -= 1
return sum(s >= r for s, r in zip(accumulate(d), requirement))
| null | null | null | null | null |
function meetRequirement(n: number, lights: number[][], requirement: number[]): number {
const d: number[] = Array(n + 1).fill(0);
for (const [p, r] of lights) {
const [i, j] = [Math.max(0, p - r), Math.min(n - 1, p + r)];
++d[i];
--d[j + 1];
}
let [ans, s] = [0, 0];
for (let i = 0; i < n; ++i) {
s += d[i];
if (s >= requirement[i]) {
++ans;
}
}
return ans;
}
|
Number of Common Factors
|
Given two positive integers
a
and
b
, return
the number of
common
factors of
a
and
b
.
An integer
x
is a
common factor
of
a
and
b
if
x
divides both
a
and
b
.
Example 1:
Input:
a = 12, b = 6
Output:
4
Explanation:
The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2:
Input:
a = 25, b = 30
Output:
2
Explanation:
The common factors of 25 and 30 are 1, 5.
Constraints:
1 <= a, b <= 1000
| null | null |
class Solution {
public:
int commonFactors(int a, int b) {
int g = gcd(a, b);
int ans = 0;
for (int x = 1; x * x <= g; ++x) {
if (g % x == 0) {
ans++;
ans += x * x < g;
}
}
return ans;
}
};
| null | null |
func commonFactors(a int, b int) (ans int) {
g := gcd(a, b)
for x := 1; x*x <= g; x++ {
if g%x == 0 {
ans++
if x*x < g {
ans++
}
}
}
return
}
func gcd(a int, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
class Solution {
public int commonFactors(int a, int b) {
int g = gcd(a, b);
int ans = 0;
for (int x = 1; x * x <= g; ++x) {
if (g % x == 0) {
++ans;
if (x * x < g) {
++ans;
}
}
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
| null | null | null | null | null | null |
class Solution:
def commonFactors(self, a: int, b: int) -> int:
g = gcd(a, b)
ans, x = 0, 1
while x * x <= g:
if g % x == 0:
ans += 1
ans += x * x < g
x += 1
return ans
| null | null | null | null | null |
function commonFactors(a: number, b: number): number {
const g = gcd(a, b);
let ans = 0;
for (let x = 1; x * x <= g; ++x) {
if (g % x === 0) {
++ans;
if (x * x < g) {
++ans;
}
}
}
return ans;
}
function gcd(a: number, b: number): number {
return b === 0 ? a : gcd(b, a % b);
}
|
Find the Derangement of An Array 🔒
|
In combinatorial mathematics, a
derangement
is a permutation of the elements of a set, such that no element appears in its original position.
You are given an integer
n
. There is originally an array consisting of
n
integers from
1
to
n
in ascending order, return
the number of
derangements
it can generate
. Since the answer may be huge, return it
modulo
10
9
+ 7
.
Example 1:
Input:
n = 3
Output:
2
Explanation:
The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Example 2:
Input:
n = 2
Output:
1
Constraints:
1 <= n <= 10
6
| null | null |
class Solution {
public:
int findDerangement(int n) {
long long a = 1, b = 0;
const int mod = 1e9 + 7;
for (int i = 2; i <= n; ++i) {
long long c = (i - 1) * (a + b) % mod;
a = b;
b = c;
}
return b;
}
};
| null | null |
func findDerangement(n int) int {
a, b := 1, 0
const mod = 1e9 + 7
for i := 2; i <= n; i++ {
a, b = b, (i-1)*(a+b)%mod
}
return b
}
|
class Solution {
public int findDerangement(int n) {
final int mod = (int) 1e9 + 7;
long a = 1, b = 0;
for (int i = 2; i <= n; ++i) {
long c = (i - 1) * (a + b) % mod;
a = b;
b = c;
}
return (int) b;
}
}
| null | null | null | null | null | null |
class Solution:
def findDerangement(self, n: int) -> int:
mod = 10**9 + 7
a, b = 1, 0
for i in range(2, n + 1):
a, b = b, ((i - 1) * (a + b)) % mod
return b
| null | null | null | null | null | null |
Check if Point Is Reachable
|
There exists an infinitely large grid. You are currently at point
(1, 1)
, and you need to reach the point
(targetX, targetY)
using a finite number of steps.
In one
step
, you can move from point
(x, y)
to any one of the following points:
(x, y - x)
(x - y, y)
(2 * x, y)
(x, 2 * y)
Given two integers
targetX
and
targetY
representing the X-coordinate and Y-coordinate of your final position, return
true
if you can reach the point from
(1, 1)
using some number of steps, and
false
otherwise
.
Example 1:
Input:
targetX = 6, targetY = 9
Output:
false
Explanation:
It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
Example 2:
Input:
targetX = 4, targetY = 7
Output:
true
Explanation:
You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
Constraints:
1 <= targetX, targetY <= 10
9
| null | null |
class Solution {
public:
bool isReachable(int targetX, int targetY) {
int x = gcd(targetX, targetY);
return (x & (x - 1)) == 0;
}
};
| null | null |
func isReachable(targetX int, targetY int) bool {
x := gcd(targetX, targetY)
return x&(x-1) == 0
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
class Solution {
public boolean isReachable(int targetX, int targetY) {
int x = gcd(targetX, targetY);
return (x & (x - 1)) == 0;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
| null | null | null | null | null | null |
class Solution:
def isReachable(self, targetX: int, targetY: int) -> bool:
x = gcd(targetX, targetY)
return x & (x - 1) == 0
| null | null | null | null | null |
function isReachable(targetX: number, targetY: number): boolean {
const x = gcd(targetX, targetY);
return (x & (x - 1)) === 0;
}
function gcd(a: number, b: number): number {
return b == 0 ? a : gcd(b, a % b);
}
|
Island Perimeter
|
You are given
row x col
grid
representing a map where
grid[i][j] = 1
represents land and
grid[i][j] = 0
represents water.
Grid cells are connected
horizontally/vertically
(not diagonally). The
grid
is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example 1:
Input:
grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output:
16
Explanation:
The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input:
grid = [[1]]
Output:
4
Example 3:
Input:
grid = [[1,0]]
Output:
4
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j]
is
0
or
1
.
There is exactly one island in
grid
.
| null | null |
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
ans += 4;
if (i < m - 1 && grid[i + 1][j] == 1) ans -= 2;
if (j < n - 1 && grid[i][j + 1] == 1) ans -= 2;
}
}
}
return ans;
}
};
| null | null |
func islandPerimeter(grid [][]int) int {
m, n := len(grid), len(grid[0])
ans := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
ans += 4
if i < m-1 && grid[i+1][j] == 1 {
ans -= 2
}
if j < n-1 && grid[i][j+1] == 1 {
ans -= 2
}
}
}
}
return ans
}
|
class Solution {
public int islandPerimeter(int[][] grid) {
int ans = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
ans += 4;
if (i < m - 1 && grid[i + 1][j] == 1) {
ans -= 2;
}
if (j < n - 1 && grid[i][j + 1] == 1) {
ans -= 2;
}
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
ans += 4
if i < m - 1 and grid[i + 1][j] == 1:
ans -= 2
if j < n - 1 and grid[i][j + 1] == 1:
ans -= 2
return ans
| null | null | null | null | null |
function islandPerimeter(grid: number[][]): number {
let m = grid.length,
n = grid[0].length;
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
let top = 0,
left = 0;
if (i > 0) {
top = grid[i - 1][j];
}
if (j > 0) {
left = grid[i][j - 1];
}
let cur = grid[i][j];
if (cur != top) ++ans;
if (cur != left) ++ans;
}
}
// 最后一行, 最后一列
for (let i = 0; i < m; ++i) {
if (grid[i][n - 1] == 1) ++ans;
}
for (let j = 0; j < n; ++j) {
if (grid[m - 1][j] == 1) ++ans;
}
return ans;
}
|
Handshakes That Don't Cross 🔒
|
You are given an
even
number of people
numPeople
that stand around a circle and each person shakes hands with someone else so that there are
numPeople / 2
handshakes total.
Return
the number of ways these handshakes could occur such that none of the handshakes cross
.
Since the answer could be very large, return it
modulo
10
9
+ 7
.
Example 1:
Input:
numPeople = 4
Output:
2
Explanation:
There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)].
Example 2:
Input:
numPeople = 6
Output:
5
Constraints:
2 <= numPeople <= 1000
numPeople
is even.
| null | null |
class Solution {
public:
int numberOfWays(int numPeople) {
const int mod = 1e9 + 7;
int f[numPeople + 1];
memset(f, 0, sizeof(f));
function<int(int)> dfs = [&](int i) {
if (i < 2) {
return 1;
}
if (f[i]) {
return f[i];
}
for (int l = 0; l < i; l += 2) {
int r = i - l - 2;
f[i] = (f[i] + 1LL * dfs(l) * dfs(r) % mod) % mod;
}
return f[i];
};
return dfs(numPeople);
}
};
| null | null |
func numberOfWays(numPeople int) int {
const mod int = 1e9 + 7
f := make([]int, numPeople+1)
var dfs func(int) int
dfs = func(i int) int {
if i < 2 {
return 1
}
if f[i] != 0 {
return f[i]
}
for l := 0; l < i; l += 2 {
r := i - l - 2
f[i] = (f[i] + dfs(l)*dfs(r)) % mod
}
return f[i]
}
return dfs(numPeople)
}
|
class Solution {
private int[] f;
private final int mod = (int) 1e9 + 7;
public int numberOfWays(int numPeople) {
f = new int[numPeople + 1];
return dfs(numPeople);
}
private int dfs(int i) {
if (i < 2) {
return 1;
}
if (f[i] != 0) {
return f[i];
}
for (int l = 0; l < i; l += 2) {
int r = i - l - 2;
f[i] = (int) ((f[i] + (1L * dfs(l) * dfs(r) % mod)) % mod);
}
return f[i];
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfWays(self, numPeople: int) -> int:
@cache
def dfs(i: int) -> int:
if i < 2:
return 1
ans = 0
for l in range(0, i, 2):
r = i - l - 2
ans += dfs(l) * dfs(r)
ans %= mod
return ans
mod = 10**9 + 7
return dfs(numPeople)
| null | null | null | null | null |
function numberOfWays(numPeople: number): number {
const mod = 10 ** 9 + 7;
const f: number[] = Array(numPeople + 1).fill(0);
const dfs = (i: number): number => {
if (i < 2) {
return 1;
}
if (f[i] !== 0) {
return f[i];
}
for (let l = 0; l < i; l += 2) {
const r = i - l - 2;
f[i] += Number((BigInt(dfs(l)) * BigInt(dfs(r))) % BigInt(mod));
f[i] %= mod;
}
return f[i];
};
return dfs(numPeople);
}
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
You are given a
0-indexed
array of integers
nums
.
A prefix
nums[0..i]
is
sequential
if, for all
1 <= j <= i
,
nums[j] = nums[j - 1] + 1
. In particular, the prefix consisting only of
nums[0]
is
sequential
.
Return
the
smallest
integer
x
missing from
nums
such that
x
is greater than or equal to the sum of the
longest
sequential prefix.
Example 1:
Input:
nums = [1,2,3,2,5]
Output:
6
Explanation:
The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
Example 2:
Input:
nums = [3,4,5,1,12,14,13]
Output:
15
Explanation:
The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
Constraints:
1 <= nums.length <= 50
1 <= nums[i] <= 50
| null | null |
class Solution {
public:
int missingInteger(vector<int>& nums) {
int s = nums[0];
for (int j = 1; j < nums.size() && nums[j] == nums[j - 1] + 1; ++j) {
s += nums[j];
}
bitset<51> vis;
for (int x : nums) {
vis[x] = 1;
}
for (int x = s;; ++x) {
if (x >= 51 || !vis[x]) {
return x;
}
}
}
};
| null | null |
func missingInteger(nums []int) int {
s := nums[0]
for j := 1; j < len(nums) && nums[j] == nums[j-1]+1; j++ {
s += nums[j]
}
vis := [51]bool{}
for _, x := range nums {
vis[x] = true
}
for x := s; ; x++ {
if x >= len(vis) || !vis[x] {
return x
}
}
}
|
class Solution {
public int missingInteger(int[] nums) {
int s = nums[0];
for (int j = 1; j < nums.length && nums[j] == nums[j - 1] + 1; ++j) {
s += nums[j];
}
boolean[] vis = new boolean[51];
for (int x : nums) {
vis[x] = true;
}
for (int x = s;; ++x) {
if (x >= vis.length || !vis[x]) {
return x;
}
}
}
}
| null | null | null | null | null | null |
class Solution:
def missingInteger(self, nums: List[int]) -> int:
s, j = nums[0], 1
while j < len(nums) and nums[j] == nums[j - 1] + 1:
s += nums[j]
j += 1
vis = set(nums)
for x in count(s):
if x not in vis:
return x
| null | null | null | null | null |
function missingInteger(nums: number[]): number {
let s = nums[0];
for (let j = 1; j < nums.length && nums[j] === nums[j - 1] + 1; ++j) {
s += nums[j];
}
const vis: Set<number> = new Set(nums);
for (let x = s; ; ++x) {
if (!vis.has(x)) {
return x;
}
}
}
|
Check if All Characters Have Equal Number of Occurrences
|
Given a string
s
, return
true
if
s
is a
good
string, or
false
otherwise
.
A string
s
is
good
if
all
the characters that appear in
s
have the
same
number of occurrences (i.e., the same frequency).
Example 1:
Input:
s = "abacbc"
Output:
true
Explanation:
The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
Example 2:
Input:
s = "aaabb"
Output:
false
Explanation:
The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
Constraints:
1 <= s.length <= 1000
s
consists of lowercase English letters.
| null | null |
class Solution {
public:
bool areOccurrencesEqual(string s) {
vector<int> cnt(26);
for (char c : s) {
++cnt[c - 'a'];
}
int v = 0;
for (int x : cnt) {
if (x == 0) {
continue;
}
if (v && v != x) {
return false;
}
v = x;
}
return true;
}
};
| null | null |
func areOccurrencesEqual(s string) bool {
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
v := 0
for _, x := range cnt {
if x == 0 {
continue
}
if v > 0 && v != x {
return false
}
v = x
}
return true
}
|
class Solution {
public boolean areOccurrencesEqual(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
int v = 0;
for (int x : cnt) {
if (x == 0) {
continue;
}
if (v > 0 && v != x) {
return false;
}
v = x;
}
return true;
}
}
| null | null | null | null |
class Solution {
/**
* @param String $s
* @return Boolean
*/
function areOccurrencesEqual($s) {
$cnt = array_fill(0, 26, 0);
for ($i = 0; $i < strlen($s); $i++) {
$cnt[ord($s[$i]) - ord('a')]++;
}
$v = 0;
foreach ($cnt as $x) {
if ($x == 0) {
continue;
}
if ($v && $v != $x) {
return false;
}
$v = $x;
}
return true;
}
}
| null |
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1
| null | null | null | null | null |
function areOccurrencesEqual(s: string): boolean {
const cnt: number[] = Array(26).fill(0);
for (const c of s) {
++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)];
}
const v = cnt.find(v => v);
return cnt.every(x => !x || v === x);
}
|
Recover the Original Array
|
Alice had a
0-indexed
array
arr
consisting of
n
positive
integers. She chose an arbitrary
positive integer
k
and created two new
0-indexed
integer arrays
lower
and
higher
in the following manner:
lower[i] = arr[i] - k
, for every index
i
where
0 <= i < n
higher[i] = arr[i] + k
, for every index
i
where
0 <= i < n
Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays
lower
and
higher
, but not the array each integer belonged to. Help Alice and recover the original array.
Given an array
nums
consisting of
2n
integers, where
exactly
n
of the integers were present in
lower
and the remaining in
higher
, return
the
original
array
arr
. In case the answer is not unique, return
any
valid array
.
Note:
The test cases are generated such that there exists
at least one
valid array
arr
.
Example 1:
Input:
nums = [2,10,6,4,8,12]
Output:
[3,7,11]
Explanation:
If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].
Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.
Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].
Example 2:
Input:
nums = [1,1,3,3]
Output:
[2,2]
Explanation:
If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].
Combining lower and higher gives us [1,1,3,3], which is equal to nums.
Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.
This is invalid since k must be positive.
Example 3:
Input:
nums = [5,435]
Output:
[220]
Explanation:
The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].
Constraints:
2 * n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 10
9
The test cases are generated such that there exists
at least one
valid array
arr
.
| null | null |
class Solution {
public:
vector<int> recoverArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 1, n = nums.size(); i < n; ++i) {
int d = nums[i] - nums[0];
if (d == 0 || d % 2 == 1) continue;
vector<bool> vis(n);
vis[i] = true;
vector<int> ans;
ans.push_back((nums[0] + nums[i]) >> 1);
for (int l = 1, r = i + 1; r < n; ++l, ++r) {
while (l < n && vis[l]) ++l;
while (r < n && nums[r] - nums[l] < d) ++r;
if (r == n || nums[r] - nums[l] > d) break;
vis[r] = true;
ans.push_back((nums[l] + nums[r]) >> 1);
}
if (ans.size() == (n >> 1)) return ans;
}
return {};
}
};
| null | null |
func recoverArray(nums []int) []int {
sort.Ints(nums)
for i, n := 1, len(nums); i < n; i++ {
d := nums[i] - nums[0]
if d == 0 || d%2 == 1 {
continue
}
vis := make([]bool, n)
vis[i] = true
ans := []int{(nums[0] + nums[i]) >> 1}
for l, r := 1, i+1; r < n; l, r = l+1, r+1 {
for l < n && vis[l] {
l++
}
for r < n && nums[r]-nums[l] < d {
r++
}
if r == n || nums[r]-nums[l] > d {
break
}
vis[r] = true
ans = append(ans, (nums[l]+nums[r])>>1)
}
if len(ans) == (n >> 1) {
return ans
}
}
return []int{}
}
|
class Solution {
public int[] recoverArray(int[] nums) {
Arrays.sort(nums);
for (int i = 1, n = nums.length; i < n; ++i) {
int d = nums[i] - nums[0];
if (d == 0 || d % 2 == 1) {
continue;
}
boolean[] vis = new boolean[n];
vis[i] = true;
List<Integer> t = new ArrayList<>();
t.add((nums[0] + nums[i]) >> 1);
for (int l = 1, r = i + 1; r < n; ++l, ++r) {
while (l < n && vis[l]) {
++l;
}
while (r < n && nums[r] - nums[l] < d) {
++r;
}
if (r == n || nums[r] - nums[l] > d) {
break;
}
vis[r] = true;
t.add((nums[l] + nums[r]) >> 1);
}
if (t.size() == (n >> 1)) {
int[] ans = new int[t.size()];
int idx = 0;
for (int e : t) {
ans[idx++] = e;
}
return ans;
}
}
return null;
}
}
| null | null | null | null | null | null |
class Solution:
def recoverArray(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
for i in range(1, n):
d = nums[i] - nums[0]
if d == 0 or d % 2 == 1:
continue
vis = [False] * n
vis[i] = True
ans = [(nums[0] + nums[i]) >> 1]
l, r = 1, i + 1
while r < n:
while l < n and vis[l]:
l += 1
while r < n and nums[r] - nums[l] < d:
r += 1
if r == n or nums[r] - nums[l] > d:
break
vis[r] = True
ans.append((nums[l] + nums[r]) >> 1)
l, r = l + 1, r + 1
if len(ans) == (n >> 1):
return ans
return []
| null | null | null | null | null | null |
Employees With Missing Information
|
Table:
Employees
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| name | varchar |
+-------------+---------+
employee_id is the column with unique values for this table.
Each row of this table indicates the name of the employee whose ID is employee_id.
Table:
Salaries
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| salary | int |
+-------------+---------+
employee_id is the column with unique values for this table.
Each row of this table indicates the salary of the employee whose ID is employee_id.
Write a solution to report the IDs of all the employees with
missing information
. The information of an employee is missing if:
The employee's
name
is missing, or
The employee's
salary
is missing.
Return the result table ordered by
employee_id
in ascending order
.
The result format is in the following example.
Example 1:
Input:
Employees table:
+-------------+----------+
| employee_id | name |
+-------------+----------+
| 2 | Crew |
| 4 | Haven |
| 5 | Kristian |
+-------------+----------+
Salaries table:
+-------------+--------+
| employee_id | salary |
+-------------+--------+
| 5 | 76071 |
| 1 | 22517 |
| 4 | 63539 |
+-------------+--------+
Output:
+-------------+
| employee_id |
+-------------+
| 1 |
| 2 |
+-------------+
Explanation:
Employees 1, 2, 4, and 5 are working at this company.
The name of employee 1 is missing.
The salary of employee 2 is missing.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
SELECT employee_id
FROM Employees
WHERE employee_id NOT IN (SELECT employee_id FROM Salaries)
UNION
SELECT employee_id
FROM Salaries
WHERE employee_id NOT IN (SELECT employee_id FROM Employees)
ORDER BY 1;
| null | null | null | null | null | null | null | null | null | null |
Shift 2D Grid
|
Given a 2D
grid
of size
m x n
and an integer
k
. You need to shift the
grid
k
times.
In one shift operation:
Element at
grid[i][j]
moves to
grid[i][j + 1]
.
Element at
grid[i][n - 1]
moves to
grid[i + 1][0]
.
Element at
grid[m - 1][n - 1]
moves to
grid[0][0]
.
Return the
2D grid
after applying shift operation
k
times.
Example 1:
Input:
grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output:
[[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input:
grid
= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output:
[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input:
grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output:
[[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
| null | null |
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> ans(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int idx = (i * n + j + k) % (m * n);
int x = idx / n, y = idx % n;
ans[x][y] = grid[i][j];
}
}
return ans;
}
};
| null | null |
func shiftGrid(grid [][]int, k int) [][]int {
m, n := len(grid), len(grid[0])
ans := make([][]int, m)
for i := range ans {
ans[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
idx := (i*n + j + k) % (m * n)
x, y := idx/n, idx%n
ans[x][y] = grid[i][j]
}
}
return ans
}
|
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
int m = grid.length, n = grid[0].length;
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < m; ++i) {
List<Integer> row = new ArrayList<>();
for (int j = 0; j < n; ++j) {
row.add(0);
}
ans.add(row);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int idx = (i * n + j + k) % (m * n);
int x = idx / n, y = idx % n;
ans.get(x).set(y, grid[i][j]);
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = [[0] * n for _ in range(m)]
for i, row in enumerate(grid):
for j, v in enumerate(row):
x, y = divmod((i * n + j + k) % (m * n), n)
ans[x][y] = v
return ans
| null | null | null | null | null |
function shiftGrid(grid: number[][], k: number): number[][] {
const [m, n] = [grid.length, grid[0].length];
const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0));
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
const idx = (i * n + j + k) % (m * n);
const [x, y] = [Math.floor(idx / n), idx % n];
ans[x][y] = grid[i][j];
}
}
return ans;
}
|
Combination Sum II
|
Given a collection of candidate numbers (
candidates
) and a target number (
target
), find all unique combinations in
candidates
where the candidate numbers sum to
target
.
Each number in
candidates
may only be used
once
in the combination.
Note:
The solution set must not contain duplicate combinations.
Example 1:
Input:
candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input:
candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
| null |
public class Solution {
private List<IList<int>> ans = new List<IList<int>>();
private List<int> t = new List<int>();
private int[] candidates;
public IList<IList<int>> CombinationSum2(int[] candidates, int target) {
Array.Sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.Add(new List<int>(t));
return;
}
if (i >= candidates.Length || s < candidates[i]) {
return;
}
int x = candidates[i];
t.Add(x);
dfs(i + 1, s - x);
t.RemoveAt(t.Count - 1);
while (i < candidates.Length && candidates[i] == x) {
++i;
}
dfs(i, s);
}
}
|
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> t;
function<void(int, int)> dfs = [&](int i, int s) {
if (s == 0) {
ans.emplace_back(t);
return;
}
if (i >= candidates.size() || s < candidates[i]) {
return;
}
int x = candidates[i];
t.emplace_back(x);
dfs(i + 1, s - x);
t.pop_back();
while (i < candidates.size() && candidates[i] == x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
}
};
| null | null |
func combinationSum2(candidates []int, target int) (ans [][]int) {
sort.Ints(candidates)
t := []int{}
var dfs func(i, s int)
dfs = func(i, s int) {
if s == 0 {
ans = append(ans, slices.Clone(t))
return
}
if i >= len(candidates) || s < candidates[i] {
return
}
for j := i; j < len(candidates); j++ {
if j > i && candidates[j] == candidates[j-1] {
continue
}
t = append(t, candidates[j])
dfs(j+1, s-candidates[j])
t = t[:len(t)-1]
}
}
dfs(0, target)
return
}
|
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> t = new ArrayList<>();
private int[] candidates;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.add(new ArrayList<>(t));
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
int x = candidates[i];
t.add(x);
dfs(i + 1, s - x);
t.remove(t.size() - 1);
while (i < candidates.length && candidates[i] == x) {
++i;
}
dfs(i, s);
}
}
|
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
candidates.sort((a, b) => a - b);
const ans = [];
const t = [];
const dfs = (i, s) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
const x = candidates[i];
t.push(x);
dfs(i + 1, s - x);
t.pop();
while (i < candidates.length && candidates[i] === x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
};
| null | null | null |
class Solution {
/**
* @param integer[] $candidates
* @param integer $target
* @return integer[][]
*/
function combinationSum2($candidates, $target) {
$result = [];
$currentCombination = [];
$startIndex = 0;
sort($candidates);
$this->findCombinations($candidates, $target, $startIndex, $currentCombination, $result);
return $result;
}
function findCombinations($candidates, $target, $startIndex, $currentCombination, &$result) {
if ($target === 0) {
$result[] = $currentCombination;
return;
}
for ($i = $startIndex; $i < count($candidates); $i++) {
$num = $candidates[$i];
if ($num > $target) {
break;
}
if ($i > $startIndex && $candidates[$i] === $candidates[$i - 1]) {
continue;
}
$currentCombination[] = $num;
$this->findCombinations(
$candidates,
$target - $num,
$i + 1,
$currentCombination,
$result,
);
array_pop($currentCombination);
}
}
}
| null |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if i >= len(candidates) or s < candidates[i]:
return
x = candidates[i]
t.append(x)
dfs(i + 1, s - x)
t.pop()
while i < len(candidates) and candidates[i] == x:
i += 1
dfs(i, s)
candidates.sort()
ans = []
t = []
dfs(0, target)
return ans
| null |
impl Solution {
fn dfs(mut i: usize, s: i32, candidates: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if s == 0 {
ans.push(t.clone());
return;
}
if i >= candidates.len() || s < candidates[i] {
return;
}
let x = candidates[i];
t.push(x);
Self::dfs(i + 1, s - x, candidates, t, ans);
t.pop();
while i < candidates.len() && candidates[i] == x {
i += 1;
}
Self::dfs(i, s, candidates, t, ans);
}
pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
candidates.sort();
let mut ans = Vec::new();
Self::dfs(0, target, &candidates, &mut vec![], &mut ans);
ans
}
}
| null | null | null |
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const ans: number[][] = [];
const t: number[] = [];
const dfs = (i: number, s: number) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
const x = candidates[i];
t.push(x);
dfs(i + 1, s - x);
t.pop();
while (i < candidates.length && candidates[i] === x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
}
|
Find Top Scoring Students 🔒
|
Table:
students
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| name | varchar |
| major | varchar |
+-------------+----------+
student_id is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the student ID, student name, and their major.
Table:
courses
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| course_id | int |
| name | varchar |
| credits | int |
| major | varchar |
+-------------+----------+
course_id is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the course ID, course name, the number of credits for the course, and the major it belongs to.
Table:
enrollments
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| student_id | int |
| course_id | int |
| semester | varchar |
| grade | varchar |
+-------------+----------+
(student_id, course_id, semester) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the student ID, course ID, semester, and grade received.
Write a solution to find the students who have
taken
all courses
offered in their
major
and have achieved a
grade of A
in all these courses
.
Return
the result table ordered by
student_id
in
ascending
order
.
The result format is in the following example.
Example:
Input:
students table:
+------------+------------------+------------------+
| student_id | name | major |
+------------+------------------+------------------+
| 1 | Alice | Computer Science |
| 2 | Bob | Computer Science |
| 3 | Charlie | Mathematics |
| 4 | David | Mathematics |
+------------+------------------+------------------+
courses table:
+-----------+-----------------+---------+------------------+
| course_id | name | credits | major |
+-----------+-----------------+---------+------------------+
| 101 | Algorithms | 3 | Computer Science |
| 102 | Data Structures | 3 | Computer Science |
| 103 | Calculus | 4 | Mathematics |
| 104 | Linear Algebra | 4 | Mathematics |
+-----------+-----------------+---------+------------------+
enrollments table:
+------------+-----------+----------+-------+
| student_id | course_id | semester | grade |
+------------+-----------+----------+-------+
| 1 | 101 | Fall 2023| A |
| 1 | 102 | Fall 2023| A |
| 2 | 101 | Fall 2023| B |
| 2 | 102 | Fall 2023| A |
| 3 | 103 | Fall 2023| A |
| 3 | 104 | Fall 2023| A |
| 4 | 103 | Fall 2023| A |
| 4 | 104 | Fall 2023| B |
+------------+-----------+----------+-------+
Output:
+------------+
| student_id |
+------------+
| 1 |
| 3 |
+------------+
Explanation:
Alice (student_id 1) is a Computer Science major and has taken both "Algorithms" and "Data Structures", receiving an 'A' in both.
Bob (student_id 2) is a Computer Science major but did not receive an 'A' in all required courses.
Charlie (student_id 3) is a Mathematics major and has taken both "Calculus" and "Linear Algebra", receiving an 'A' in both.
David (student_id 4) is a Mathematics major but did not receive an 'A' in all required courses.
Note:
Output table is ordered by student_id in ascending order.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
SELECT student_id
FROM
students
JOIN courses USING (major)
LEFT JOIN enrollments USING (student_id, course_id)
GROUP BY 1
HAVING SUM(grade = 'A') = COUNT(major)
ORDER BY 1;
| null | null | null | null | null | null | null | null | null | null |
Successful Pairs of Spells and Potions
|
You are given two positive integer arrays
spells
and
potions
, of length
n
and
m
respectively, where
spells[i]
represents the strength of the
i
th
spell and
potions[j]
represents the strength of the
j
th
potion.
You are also given an integer
success
. A spell and potion pair is considered
successful
if the
product
of their strengths is
at least
success
.
Return
an integer array
pairs
of length
n
where
pairs[i]
is the number of
potions
that will form a successful pair with the
i
th
spell.
Example 1:
Input:
spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output:
[4,0,3]
Explanation:
- 0
th
spell: 5 * [1,2,3,4,5] = [5,
10
,
15
,
20
,
25
]. 4 pairs are successful.
- 1
st
spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2
nd
spell: 3 * [1,2,3,4,5] = [3,6,
9
,
12
,
15
]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input:
spells = [3,1,2], potions = [8,5,8], success = 16
Output:
[2,0,2]
Explanation:
- 0
th
spell: 3 * [8,5,8] = [
24
,15,
24
]. 2 pairs are successful.
- 1
st
spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2
nd
spell: 2 * [8,5,8] = [
16
,10,
16
]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
n == spells.length
m == potions.length
1 <= n, m <= 10
5
1 <= spells[i], potions[i] <= 10
5
1 <= success <= 10
10
| null | null |
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
vector<int> ans;
int m = potions.size();
for (int& v : spells) {
int i = lower_bound(potions.begin(), potions.end(), success * 1.0 / v) - potions.begin();
ans.push_back(m - i);
}
return ans;
}
};
| null | null |
func successfulPairs(spells []int, potions []int, success int64) (ans []int) {
sort.Ints(potions)
m := len(potions)
for _, v := range spells {
i := sort.Search(m, func(i int) bool { return int64(potions[i]*v) >= success })
ans = append(ans, m-i)
}
return ans
}
|
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
Arrays.sort(potions);
int n = spells.length, m = potions.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int left = 0, right = m;
while (left < right) {
int mid = (left + right) >> 1;
if ((long) spells[i] * potions[mid] >= success) {
right = mid;
} else {
left = mid + 1;
}
}
ans[i] = m - left;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def successfulPairs(
self, spells: List[int], potions: List[int], success: int
) -> List[int]:
potions.sort()
m = len(potions)
return [m - bisect_left(potions, success / v) for v in spells]
| null |
impl Solution {
pub fn successful_pairs(spells: Vec<i32>, mut potions: Vec<i32>, success: i64) -> Vec<i32> {
potions.sort();
let m = potions.len();
spells.into_iter().map(|v| {
let i = potions.binary_search_by(|&p| {
let prod = (p as i64) * (v as i64);
if prod >= success {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Less
}
}).unwrap_or_else(|x| x);
(m - i) as i32
}).collect()
}
}
| null | null | null |
function successfulPairs(spells: number[], potions: number[], success: number): number[] {
potions.sort((a, b) => a - b);
const m = potions.length;
const ans: number[] = [];
for (const v of spells) {
let left = 0;
let right = m;
while (left < right) {
const mid = (left + right) >> 1;
if (v * potions[mid] >= success) {
right = mid;
} else {
left = mid + 1;
}
}
ans.push(m - left);
}
return ans;
}
|
String Transforms Into Another String 🔒
|
Given two strings
str1
and
str2
of the same length, determine whether you can transform
str1
into
str2
by doing
zero or more
conversions
.
In one conversion you can convert
all
occurrences of one character in
str1
to
any
other lowercase English character.
Return
true
if and only if you can transform
str1
into
str2
.
Example 1:
Input:
str1 = "aabcc", str2 = "ccdee"
Output:
true
Explanation:
Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
Example 2:
Input:
str1 = "leetcode", str2 = "codeleet"
Output:
false
Explanation:
There is no way to transform str1 to str2.
Constraints:
1 <= str1.length == str2.length <= 10
4
str1
and
str2
contain only lowercase English letters.
| null | null |
class Solution {
public:
bool canConvert(string str1, string str2) {
if (str1 == str2) {
return true;
}
int cnt[26]{};
int m = 0;
for (char& c : str2) {
if (++cnt[c - 'a'] == 1) {
++m;
}
}
if (m == 26) {
return false;
}
int d[26]{};
for (int i = 0; i < str1.size(); ++i) {
int a = str1[i] - 'a';
int b = str2[i] - 'a';
if (d[a] == 0) {
d[a] = b + 1;
} else if (d[a] != b + 1) {
return false;
}
}
return true;
}
};
| null | null |
func canConvert(str1 string, str2 string) bool {
if str1 == str2 {
return true
}
s := map[rune]bool{}
for _, c := range str2 {
s[c] = true
if len(s) == 26 {
return false
}
}
d := [26]int{}
for i, c := range str1 {
a, b := int(c-'a'), int(str2[i]-'a')
if d[a] == 0 {
d[a] = b + 1
} else if d[a] != b+1 {
return false
}
}
return true
}
|
class Solution {
public boolean canConvert(String str1, String str2) {
if (str1.equals(str2)) {
return true;
}
int m = 0;
int[] cnt = new int[26];
int n = str1.length();
for (int i = 0; i < n; ++i) {
if (++cnt[str2.charAt(i) - 'a'] == 1) {
++m;
}
}
if (m == 26) {
return false;
}
int[] d = new int[26];
for (int i = 0; i < n; ++i) {
int a = str1.charAt(i) - 'a';
int b = str2.charAt(i) - 'a';
if (d[a] == 0) {
d[a] = b + 1;
} else if (d[a] != b + 1) {
return false;
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def canConvert(self, str1: str, str2: str) -> bool:
if str1 == str2:
return True
if len(set(str2)) == 26:
return False
d = {}
for a, b in zip(str1, str2):
if a not in d:
d[a] = b
elif d[a] != b:
return False
return True
| null | null | null | null | null |
function canConvert(str1: string, str2: string): boolean {
if (str1 === str2) {
return true;
}
if (new Set(str2).size === 26) {
return false;
}
const d: Map<string, string> = new Map();
for (const [i, c] of str1.split('').entries()) {
if (!d.has(c)) {
d.set(c, str2[i]);
} else if (d.get(c) !== str2[i]) {
return false;
}
}
return true;
}
|
Shuffle an Array
|
Given an integer array
nums
, design an algorithm to randomly shuffle the array. All permutations of the array should be
equally likely
as a result of the shuffling.
Implement the
Solution
class:
Solution(int[] nums)
Initializes the object with the integer array
nums
.
int[] reset()
Resets the array to its original configuration and returns it.
int[] shuffle()
Returns a random shuffling of the array.
Example 1:
Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
// Any permutation of [1,2,3] must be equally likely to be returned.
// Example: return [3, 1, 2]
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
Constraints:
1 <= nums.length <= 50
-10
6
<= nums[i] <= 10
6
All the elements of
nums
are
unique
.
At most
10
4
calls
in total
will be made to
reset
and
shuffle
.
| null | null |
class Solution {
public:
vector<int> nums;
vector<int> original;
Solution(vector<int>& nums) {
this->nums = nums;
this->original.resize(nums.size());
copy(nums.begin(), nums.end(), original.begin());
}
vector<int> reset() {
copy(original.begin(), original.end(), nums.begin());
return nums;
}
vector<int> shuffle() {
for (int i = 0; i < nums.size(); ++i) {
int j = i + rand() % (nums.size() - i);
swap(nums[i], nums[j]);
}
return nums;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/
| null | null |
type Solution struct {
nums, original []int
}
func Constructor(nums []int) Solution {
return Solution{nums, append([]int(nil), nums...)}
}
func (this *Solution) Reset() []int {
copy(this.nums, this.original)
return this.nums
}
func (this *Solution) Shuffle() []int {
n := len(this.nums)
for i := range this.nums {
j := i + rand.Intn(n-i)
this.nums[i], this.nums[j] = this.nums[j], this.nums[i]
}
return this.nums
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.Reset();
* param_2 := obj.Shuffle();
*/
|
class Solution {
private int[] nums;
private int[] original;
private Random rand;
public Solution(int[] nums) {
this.nums = nums;
this.original = Arrays.copyOf(nums, nums.length);
this.rand = new Random();
}
public int[] reset() {
nums = Arrays.copyOf(original, original.length);
return nums;
}
public int[] shuffle() {
for (int i = 0; i < nums.length; ++i) {
swap(i, i + rand.nextInt(nums.length - i));
}
return nums;
}
private void swap(int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/
|
/**
* @param {number[]} nums
*/
const Solution = function (nums) {
this.nums = nums || [];
};
/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function () {
return this.nums;
};
/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function () {
let a = this.nums.slice();
for (let i = 0; i < a.length; i++) {
let rand = Math.floor(Math.random() * (a.length - i)) + i;
let tmp = a[i];
a[i] = a[rand];
a[rand] = tmp;
}
return a;
};
/**
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
| null | null | null | null | null |
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
self.original = nums.copy()
def reset(self) -> List[int]:
self.nums = self.original.copy()
return self.nums
def shuffle(self) -> List[int]:
for i in range(len(self.nums)):
j = random.randrange(i, len(self.nums))
self.nums[i], self.nums[j] = self.nums[j], self.nums[i]
return self.nums
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
| null |
use rand::Rng;
struct Solution {
nums: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Solution {
fn new(nums: Vec<i32>) -> Self {
Self { nums }
}
fn reset(&self) -> Vec<i32> {
self.nums.clone()
}
fn shuffle(&mut self) -> Vec<i32> {
let n = self.nums.len();
let mut res = self.nums.clone();
for i in 0..n {
let j = rand::thread_rng().gen_range(0, n);
res.swap(i, j);
}
res
}
}
| null | null | null |
class Solution {
private nums: number[];
constructor(nums: number[]) {
this.nums = nums;
}
reset(): number[] {
return this.nums;
}
shuffle(): number[] {
const n = this.nums.length;
const res = [...this.nums];
for (let i = 0; i < n; i++) {
const j = Math.floor(Math.random() * n);
[res[i], res[j]] = [res[j], res[i]];
}
return res;
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
|
Number of Different Integers in a String
|
You are given a string
word
that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example,
"a123bc34d8ef34"
will become
" 123 34 8 34"
. Notice that you are left with some integers that are separated by at least one space:
"123"
,
"34"
,
"8"
, and
"34"
.
Return
the number of
different
integers after performing the replacement operations on
word
.
Two integers are considered different if their decimal representations
without any leading zeros
are different.
Example 1:
Input:
word = "a
123
bc
34
d
8
ef
34
"
Output:
3
Explanation:
The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Example 2:
Input:
word = "leet
1234
code
234
"
Output:
2
Example 3:
Input:
word = "a
1
b
01
c
001
"
Output:
1
Explanation:
The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.
Constraints:
1 <= word.length <= 1000
word
consists of digits and lowercase English letters.
| null | null |
class Solution {
public:
int numDifferentIntegers(string word) {
unordered_set<string> s;
int n = word.size();
for (int i = 0; i < n; ++i) {
if (isdigit(word[i])) {
while (i < n && word[i] == '0') ++i;
int j = i;
while (j < n && isdigit(word[j])) ++j;
s.insert(word.substr(i, j - i));
i = j;
}
}
return s.size();
}
};
| null | null |
func numDifferentIntegers(word string) int {
s := map[string]struct{}{}
n := len(word)
for i := 0; i < n; i++ {
if word[i] >= '0' && word[i] <= '9' {
for i < n && word[i] == '0' {
i++
}
j := i
for j < n && word[j] >= '0' && word[j] <= '9' {
j++
}
s[word[i:j]] = struct{}{}
i = j
}
}
return len(s)
}
|
class Solution {
public int numDifferentIntegers(String word) {
Set<String> s = new HashSet<>();
int n = word.length();
for (int i = 0; i < n; ++i) {
if (Character.isDigit(word.charAt(i))) {
while (i < n && word.charAt(i) == '0') {
++i;
}
int j = i;
while (j < n && Character.isDigit(word.charAt(j))) {
++j;
}
s.add(word.substring(i, j));
i = j;
}
}
return s.size();
}
}
| null | null | null | null | null | null |
class Solution:
def numDifferentIntegers(self, word: str) -> int:
s = set()
i, n = 0, len(word)
while i < n:
if word[i].isdigit():
while i < n and word[i] == '0':
i += 1
j = i
while j < n and word[j].isdigit():
j += 1
s.add(word[i:j])
i = j
i += 1
return len(s)
| null |
use std::collections::HashSet;
impl Solution {
pub fn num_different_integers(word: String) -> i32 {
let s = word.as_bytes();
let n = s.len();
let mut set = HashSet::new();
let mut i = 0;
while i < n {
if s[i] >= b'0' && s[i] <= b'9' {
let mut j = i;
while j < n && s[j] >= b'0' && s[j] <= b'9' {
j += 1;
}
while i < j - 1 && s[i] == b'0' {
i += 1;
}
set.insert(String::from_utf8(s[i..j].to_vec()).unwrap());
i = j;
} else {
i += 1;
}
}
set.len() as i32
}
}
| null | null | null |
function numDifferentIntegers(word: string): number {
return new Set(
word
.replace(/\D+/g, ' ')
.trim()
.split(' ')
.filter(v => v !== '')
.map(v => v.replace(/^0+/g, '')),
).size;
}
|
Kth Distinct String in an Array
|
A
distinct string
is a string that is present only
once
in an array.
Given an array of strings
arr
, and an integer
k
, return
the
k
th
distinct string
present in
arr
. If there are
fewer
than
k
distinct strings, return
an
empty string
""
.
Note that the strings are considered in the
order in which they appear
in the array.
Example 1:
Input:
arr = ["d","b","c","b","c","a"], k = 2
Output:
"a"
Explanation:
The only distinct strings in arr are "d" and "a".
"d" appears 1
st
, so it is the 1
st
distinct string.
"a" appears 2
nd
, so it is the 2
nd
distinct string.
Since k == 2, "a" is returned.
Example 2:
Input:
arr = ["aaa","aa","a"], k = 1
Output:
"aaa"
Explanation:
All strings in arr are distinct, so the 1
st
string "aaa" is returned.
Example 3:
Input:
arr = ["a","b","a"], k = 3
Output:
""
Explanation:
The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".
Constraints:
1 <= k <= arr.length <= 1000
1 <= arr[i].length <= 5
arr[i]
consists of lowercase English letters.
| null | null |
class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> cnt;
for (const auto& s : arr) {
++cnt[s];
}
for (const auto& s : arr) {
if (cnt[s] == 1 && --k == 0) {
return s;
}
}
return "";
}
};
| null | null |
func kthDistinct(arr []string, k int) string {
cnt := map[string]int{}
for _, s := range arr {
cnt[s]++
}
for _, s := range arr {
if cnt[s] == 1 {
k--
if k == 0 {
return s
}
}
}
return ""
}
|
class Solution {
public String kthDistinct(String[] arr, int k) {
Map<String, Integer> cnt = new HashMap<>();
for (String s : arr) {
cnt.merge(s, 1, Integer::sum);
}
for (String s : arr) {
if (cnt.get(s) == 1 && --k == 0) {
return s;
}
}
return "";
}
}
|
/**
* @param {string[]} arr
* @param {number} k
* @return {string}
*/
var kthDistinct = function (arr, k) {
const cnt = new Map();
for (const s of arr) {
cnt.set(s, (cnt.get(s) || 0) + 1);
}
for (const s of arr) {
if (cnt.get(s) === 1 && --k === 0) {
return s;
}
}
return '';
};
| null | null | null | null | null |
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
cnt = Counter(arr)
for s in arr:
if cnt[s] == 1:
k -= 1
if k == 0:
return s
return ""
| null |
use std::collections::HashMap;
impl Solution {
pub fn kth_distinct(arr: Vec<String>, mut k: i32) -> String {
let mut cnt = HashMap::new();
for s in &arr {
*cnt.entry(s).or_insert(0) += 1;
}
for s in &arr {
if *cnt.get(s).unwrap() == 1 {
k -= 1;
if k == 0 {
return s.clone();
}
}
}
"".to_string()
}
}
| null | null | null |
function kthDistinct(arr: string[], k: number): string {
const cnt = new Map<string, number>();
for (const s of arr) {
cnt.set(s, (cnt.get(s) || 0) + 1);
}
for (const s of arr) {
if (cnt.get(s) === 1 && --k === 0) {
return s;
}
}
return '';
}
|
Largest Multiple of Three
|
Given an array of digits
digits
, return
the largest multiple of
three
that can be formed by concatenating some of the given digits in
any order
. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
Example 1:
Input:
digits = [8,1,9]
Output:
"981"
Example 2:
Input:
digits = [8,6,7,1,0]
Output:
"8760"
Example 3:
Input:
digits = [1]
Output:
""
Constraints:
1 <= digits.length <= 10
4
0 <= digits[i] <= 9
| null | null |
class Solution {
public:
string largestMultipleOfThree(vector<int>& digits) {
sort(digits.begin(), digits.end());
int n = digits.size();
int f[n + 1][3];
memset(f, -0x3f, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < 3; ++j) {
f[i][j] = max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1);
}
}
if (f[n][0] <= 0) {
return "";
}
string ans;
for (int i = n, j = 0; i; --i) {
int k = (j - digits[i - 1] % 3 + 3) % 3;
if (f[i - 1][k] + 1 == f[i][j]) {
ans += digits[i - 1] + '0';
j = k;
}
}
int i = 0;
while (i < ans.size() - 1 && ans[i] == '0') {
++i;
}
return ans.substr(i);
}
};
| null | null |
func largestMultipleOfThree(digits []int) string {
sort.Ints(digits)
n := len(digits)
const inf = 1 << 30
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, 3)
for j := range f[i] {
f[i][j] = -inf
}
}
f[0][0] = 0
for i := 1; i <= n; i++ {
for j := 0; j < 3; j++ {
f[i][j] = max(f[i-1][j], f[i-1][(j-digits[i-1]%3+3)%3]+1)
}
}
if f[n][0] <= 0 {
return ""
}
ans := []byte{}
for i, j := n, 0; i > 0; i-- {
k := (j - digits[i-1]%3 + 3) % 3
if f[i][j] == f[i-1][k]+1 {
ans = append(ans, byte('0'+digits[i-1]))
j = k
}
}
i := 0
for i < len(ans)-1 && ans[i] == '0' {
i++
}
return string(ans[i:])
}
|
class Solution {
public String largestMultipleOfThree(int[] digits) {
Arrays.sort(digits);
int n = digits.length;
int[][] f = new int[n + 1][3];
final int inf = 1 << 30;
for (var g : f) {
Arrays.fill(g, -inf);
}
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < 3; ++j) {
f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1);
}
}
if (f[n][0] <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = n, j = 0; i > 0; --i) {
int k = (j - digits[i - 1] % 3 + 3) % 3;
if (f[i - 1][k] + 1 == f[i][j]) {
sb.append(digits[i - 1]);
j = k;
}
}
int i = 0;
while (i < sb.length() - 1 && sb.charAt(i) == '0') {
++i;
}
return sb.substring(i);
}
}
| null | null | null | null | null | null |
class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort()
n = len(digits)
f = [[-inf] * 3 for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(digits, 1):
for j in range(3):
f[i][j] = max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + 1)
if f[n][0] <= 0:
return ""
arr = []
j = 0
for i in range(n, 0, -1):
k = (j - digits[i - 1] % 3 + 3) % 3
if f[i - 1][k] + 1 == f[i][j]:
arr.append(digits[i - 1])
j = k
i = 0
while i < len(arr) - 1 and arr[i] == 0:
i += 1
return "".join(map(str, arr[i:]))
| null | null | null | null | null |
function largestMultipleOfThree(digits: number[]): string {
digits.sort((a, b) => a - b);
const n = digits.length;
const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(3).fill(-Infinity));
f[0][0] = 0;
for (let i = 1; i <= n; ++i) {
for (let j = 0; j < 3; ++j) {
f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - (digits[i - 1] % 3) + 3) % 3] + 1);
}
}
if (f[n][0] <= 0) {
return '';
}
const arr: number[] = [];
for (let i = n, j = 0; i; --i) {
const k = (j - (digits[i - 1] % 3) + 3) % 3;
if (f[i - 1][k] + 1 === f[i][j]) {
arr.push(digits[i - 1]);
j = k;
}
}
let i = 0;
while (i < arr.length - 1 && arr[i] === 0) {
++i;
}
return arr.slice(i).join('');
}
|
Reverse Odd Levels of Binary Tree
|
Given the
root
of a
perfect
binary tree, reverse the node values at each
odd
level of the tree.
For example, suppose the node values at level 3 are
[2,1,3,4,7,11,29,18]
, then it should become
[18,29,11,7,4,3,1,2]
.
Return
the root of the reversed tree
.
A binary tree is
perfect
if all parent nodes have two children and all leaves are on the same level.
The
level
of a node is the number of edges along the path between it and the root node.
Example 1:
Input:
root = [2,3,5,8,13,21,34]
Output:
[2,5,3,8,13,21,34]
Explanation:
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.
Example 2:
Input:
root = [7,13,11]
Output:
[7,11,13]
Explanation:
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.
Example 3:
Input:
root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output:
[0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation:
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.
Constraints:
The number of nodes in the tree is in the range
[1, 2
14
]
.
0 <= Node.val <= 10
5
root
is a
perfect
binary tree.
| null | null |
/**
* 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:
TreeNode* reverseOddLevels(TreeNode* root) {
queue<TreeNode*> q{{root}};
for (int i = 0; q.size(); ++i) {
vector<TreeNode*> t;
for (int k = q.size(); k; --k) {
TreeNode* node = q.front();
q.pop();
if (i & 1) {
t.push_back(node);
}
if (node->left) {
q.push(node->left);
q.push(node->right);
}
}
for (int l = 0, r = t.size() - 1; l < r; ++l, --r) {
swap(t[l]->val, t[r]->val);
}
}
return root;
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func reverseOddLevels(root *TreeNode) *TreeNode {
q := []*TreeNode{root}
for i := 0; len(q) > 0; i++ {
t := []*TreeNode{}
for k := len(q); k > 0; k-- {
node := q[0]
q = q[1:]
if i%2 == 1 {
t = append(t, node)
}
if node.Left != nil {
q = append(q, node.Left)
q = append(q, node.Right)
}
}
for l, r := 0, len(t)-1; l < r; l, r = l+1, r-1 {
t[l].Val, t[r].Val = t[r].Val, t[l].Val
}
}
return root
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode reverseOddLevels(TreeNode root) {
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
for (int i = 0; !q.isEmpty(); ++i) {
List<TreeNode> t = new ArrayList<>();
for (int k = q.size(); k > 0; --k) {
var node = q.poll();
if (i % 2 == 1) {
t.add(node);
}
if (node.left != null) {
q.offer(node.left);
q.offer(node.right);
}
}
for (int l = 0, r = t.size() - 1; l < r; ++l, --r) {
var x = t.get(l).val;
t.get(l).val = t.get(r).val;
t.get(r).val = x;
}
}
return root;
}
}
| null | null | null | null | null | null |
# 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 reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
q = deque([root])
i = 0
while q:
if i & 1:
l, r = 0, len(q) - 1
while l < r:
q[l].val, q[r].val = q[r].val, q[l].val
l, r = l + 1, r - 1
for _ in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
q.append(node.right)
i += 1
return root
| null |
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
fn create_tree(vals: &Vec<Vec<i32>>, i: usize, j: usize) -> Option<Rc<RefCell<TreeNode>>> {
if i == vals.len() {
return None;
}
Some(Rc::new(RefCell::new(TreeNode {
val: vals[i][j],
left: Self::create_tree(vals, i + 1, j * 2),
right: Self::create_tree(vals, i + 1, j * 2 + 1),
})))
}
pub fn reverse_odd_levels(
root: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
let mut queue = VecDeque::new();
queue.push_back(root);
let mut d = 0;
let mut vals = Vec::new();
while !queue.is_empty() {
let mut val = Vec::new();
for _ in 0..queue.len() {
let mut node = queue.pop_front().unwrap();
let mut node = node.as_mut().unwrap().borrow_mut();
val.push(node.val);
if node.left.is_some() {
queue.push_back(node.left.take());
}
if node.right.is_some() {
queue.push_back(node.right.take());
}
}
if d % 2 == 1 {
val.reverse();
}
vals.push(val);
d += 1;
}
Self::create_tree(&vals, 0, 0)
}
}
| null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function reverseOddLevels(root: TreeNode | null): TreeNode | null {
const q: TreeNode[] = [root];
for (let i = 0; q.length > 0; ++i) {
if (i % 2) {
for (let l = 0, r = q.length - 1; l < r; ++l, --r) {
[q[l].val, q[r].val] = [q[r].val, q[l].val];
}
}
const nq: TreeNode[] = [];
for (const { left, right } of q) {
if (left) {
nq.push(left);
nq.push(right);
}
}
q.splice(0, q.length, ...nq);
}
return root;
}
|
Fruits Into Baskets II
|
You are given two arrays of integers,
fruits
and
baskets
, each of length
n
, where
fruits[i]
represents the
quantity
of the
i
th
type of fruit, and
baskets[j]
represents the
capacity
of the
j
th
basket.
From left to right, place the fruits according to these rules:
Each fruit type must be placed in the
leftmost available basket
with a capacity
greater than or equal
to the quantity of that fruit type.
Each basket can hold
only one
type of fruit.
If a fruit type
cannot be placed
in any basket, it remains
unplaced
.
Return the number of fruit types that remain unplaced after all possible allocations are made.
Example 1:
Input:
fruits = [4,2,5], baskets = [3,5,4]
Output:
1
Explanation:
fruits[0] = 4
is placed in
baskets[1] = 5
.
fruits[1] = 2
is placed in
baskets[0] = 3
.
fruits[2] = 5
cannot be placed in
baskets[2] = 4
.
Since one fruit type remains unplaced, we return 1.
Example 2:
Input:
fruits = [3,6,1], baskets = [6,4,7]
Output:
0
Explanation:
fruits[0] = 3
is placed in
baskets[0] = 6
.
fruits[1] = 6
cannot be placed in
baskets[1] = 4
(insufficient capacity) but can be placed in the next available basket,
baskets[2] = 7
.
fruits[2] = 1
is placed in
baskets[1] = 4
.
Since all fruits are successfully placed, we return 0.
Constraints:
n == fruits.length == baskets.length
1 <= n <= 100
1 <= fruits[i], baskets[i] <= 1000
| null | null |
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
int n = fruits.size();
vector<bool> vis(n);
int ans = n;
for (int x : fruits) {
for (int i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
};
| null | null |
func numOfUnplacedFruits(fruits []int, baskets []int) int {
n := len(fruits)
ans := n
vis := make([]bool, n)
for _, x := range fruits {
for i, y := range baskets {
if y >= x && !vis[i] {
vis[i] = true
ans--
break
}
}
}
return ans
}
|
class Solution {
public int numOfUnplacedFruits(int[] fruits, int[] baskets) {
int n = fruits.length;
boolean[] vis = new boolean[n];
int ans = n;
for (int x : fruits) {
for (int i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
n = len(fruits)
vis = [False] * n
ans = n
for x in fruits:
for i, y in enumerate(baskets):
if y >= x and not vis[i]:
vis[i] = True
ans -= 1
break
return ans
| null | null | null | null | null |
function numOfUnplacedFruits(fruits: number[], baskets: number[]): number {
const n = fruits.length;
const vis: boolean[] = Array(n).fill(false);
let ans = n;
for (const x of fruits) {
for (let i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
|
Partition Array for Maximum Sum
|
Given an integer array
arr
, partition the array into (contiguous) subarrays of length
at most
k
. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return
the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a
32-bit
integer.
Example 1:
Input:
arr = [1,15,7,9,2,5,10], k = 3
Output:
84
Explanation:
arr becomes [15,15,15,9,10,10,10]
Example 2:
Input:
arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
Output:
83
Example 3:
Input:
arr = [1], k = 1
Output:
1
Constraints:
1 <= arr.length <= 500
0 <= arr[i] <= 10
9
1 <= k <= arr.length
| null | null |
class Solution {
public:
int maxSumAfterPartitioning(vector<int>& arr, int k) {
int n = arr.size();
int f[n + 1];
memset(f, 0, sizeof(f));
for (int i = 1; i <= n; ++i) {
int mx = 0;
for (int j = i; j > max(0, i - k); --j) {
mx = max(mx, arr[j - 1]);
f[i] = max(f[i], f[j - 1] + mx * (i - j + 1));
}
}
return f[n];
}
};
| null | null |
func maxSumAfterPartitioning(arr []int, k int) int {
n := len(arr)
f := make([]int, n+1)
for i := 1; i <= n; i++ {
mx := 0
for j := i; j > max(0, i-k); j-- {
mx = max(mx, arr[j-1])
f[i] = max(f[i], f[j-1]+mx*(i-j+1))
}
}
return f[n]
}
|
class Solution {
public int maxSumAfterPartitioning(int[] arr, int k) {
int n = arr.length;
int[] f = new int[n + 1];
for (int i = 1; i <= n; ++i) {
int mx = 0;
for (int j = i; j > Math.max(0, i - k); --j) {
mx = Math.max(mx, arr[j - 1]);
f[i] = Math.max(f[i], f[j - 1] + mx * (i - j + 1));
}
}
return f[n];
}
}
| null | null | null | null | null | null |
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
f = [0] * (n + 1)
for i in range(1, n + 1):
mx = 0
for j in range(i, max(0, i - k), -1):
mx = max(mx, arr[j - 1])
f[i] = max(f[i], f[j - 1] + mx * (i - j + 1))
return f[n]
| null | null | null | null | null |
function maxSumAfterPartitioning(arr: number[], k: number): number {
const n: number = arr.length;
const f: number[] = new Array(n + 1).fill(0);
for (let i = 1; i <= n; ++i) {
let mx: number = 0;
for (let j = i; j > Math.max(0, i - k); --j) {
mx = Math.max(mx, arr[j - 1]);
f[i] = Math.max(f[i], f[j - 1] + mx * (i - j + 1));
}
}
return f[n];
}
|
Once Twice 🔒
|
You are given an integer array
nums
. In this array:
Exactly one element appears
once
.
Exactly one element appears
twice
.
All other elements appear
exactly three times
.
Return an integer array of length 2, where the first element is the one that appears
once
, and the second is the one that appears
twice
.
Your solution must run in
O(n)
time and
O(1)
space.
Example 1:
Input:
nums = [2,2,3,2,5,5,5,7,7]
Output:
[3,7]
Explanation:
The element 3 appears
once
, and the element 7 appears
twice
. The remaining elements each appear
three times
.
Example 2:
Input:
nums = [4,4,6,4,9,9,9,6,8]
Output:
[8,6]
Explanation:
The element 8 appears
once
, and the element 6 appears
twice
. The remaining elements each appear
three times
.
Constraints:
3 <= nums.length <= 10
5
-2
31
<= nums[i] <= 2
31
- 1
nums.length
is a multiple of 3.
Exactly one element appears once, one element appears twice, and all other elements appear three times.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Find Longest Special Substring That Occurs Thrice II
|
You are given a string
s
that consists of lowercase English letters.
A string is called
special
if it is made up of only a single character. For example, the string
"abc"
is not special, whereas the strings
"ddd"
,
"zz"
, and
"f"
are special.
Return
the length of the
longest special substring
of
s
which occurs
at least thrice
,
or
-1
if no special substring occurs at least thrice
.
A
substring
is a contiguous
non-empty
sequence of characters within a string.
Example 1:
Input:
s = "aaaa"
Output:
2
Explanation:
The longest special substring which occurs thrice is "aa": substrings "
aa
aa", "a
aa
a", and "aa
aa
".
It can be shown that the maximum length achievable is 2.
Example 2:
Input:
s = "abcdef"
Output:
-1
Explanation:
There exists no special substring which occurs at least thrice. Hence return -1.
Example 3:
Input:
s = "abcaba"
Output:
1
Explanation:
The longest special substring which occurs thrice is "a": substrings "
a
bcaba", "abc
a
ba", and "abcab
a
".
It can be shown that the maximum length achievable is 1.
Constraints:
3 <= s.length <= 5 * 10
5
s
consists of only lowercase English letters.
| null | null |
class Solution {
public:
int maximumLength(string s) {
int n = s.size();
int l = 0, r = n;
auto check = [&](int x) {
int cnt[26]{};
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && s[j] == s[i]) {
++j;
}
int k = s[i] - 'a';
cnt[k] += max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
};
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l == 0 ? -1 : l;
}
};
| null | null |
func maximumLength(s string) int {
n := len(s)
l, r := 0, n
check := func(x int) bool {
cnt := [26]int{}
for i := 0; i < n; {
j := i + 1
for j < n && s[j] == s[i] {
j++
}
k := s[i] - 'a'
cnt[k] += max(0, j-i-x+1)
if cnt[k] >= 3 {
return true
}
i = j
}
return false
}
for l < r {
mid := (l + r + 1) >> 1
if check(mid) {
l = mid
} else {
r = mid - 1
}
}
if l == 0 {
return -1
}
return l
}
|
class Solution {
private String s;
private int n;
public int maximumLength(String s) {
this.s = s;
n = s.length();
int l = 0, r = n;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l == 0 ? -1 : l;
}
private boolean check(int x) {
int[] cnt = new int[26];
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && s.charAt(j) == s.charAt(i)) {
j++;
}
int k = s.charAt(i) - 'a';
cnt[k] += Math.max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumLength(self, s: str) -> int:
def check(x: int) -> bool:
cnt = defaultdict(int)
i = 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cnt[s[i]] += max(0, j - i - x + 1)
i = j
return max(cnt.values()) >= 3
n = len(s)
l, r = 0, n
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return -1 if l == 0 else l
| null | null | null | null | null |
function maximumLength(s: string): number {
const n = s.length;
let [l, r] = [0, n];
const check = (x: number): boolean => {
const cnt: number[] = Array(26).fill(0);
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && s[j] === s[i]) {
j++;
}
const k = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
cnt[k] += Math.max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l === 0 ? -1 : l;
}
|
Minimum Flips in Binary Tree to Get Result 🔒
|
You are given the
root
of a
binary tree
with the following properties:
Leaf nodes
have either the value
0
or
1
, representing
false
and
true
respectively.
Non-leaf nodes
have either the value
2
,
3
,
4
, or
5
, representing the boolean operations
OR
,
AND
,
XOR
, and
NOT
, respectively.
You are also given a boolean
result
, which is the desired result of the
evaluation
of the
root
node.
The evaluation of a node is as follows:
If the node is a leaf node, the evaluation is the
value
of the node, i.e.
true
or
false
.
Otherwise,
evaluate
the node's children and
apply
the boolean operation of its value with the children's evaluations.
In one operation, you can
flip
a leaf node, which causes a
false
node to become
true
, and a
true
node to become
false
.
Return
the minimum number of operations that need to be performed such that the evaluation of
root
yields
result
. It can be shown that there is always a way to achieve
result
.
A
leaf node
is a node that has zero children.
Note:
NOT
nodes have either a left child or a right child, but other non-leaf nodes have both a left child and a right child.
Example 1:
Input:
root = [3,5,4,2,null,1,1,1,0], result = true
Output:
2
Explanation:
It can be shown that a minimum of 2 nodes have to be flipped to make the root of the tree
evaluate to true. One way to achieve this is shown in the diagram above.
Example 2:
Input:
root = [0], result = false
Output:
0
Explanation:
The root of the tree already evaluates to false, so 0 nodes have to be flipped.
Constraints:
The number of nodes in the tree is in the range
[1, 10
5
]
.
0 <= Node.val <= 5
OR
,
AND
, and
XOR
nodes have
2
children.
NOT
nodes have
1
child.
Leaf nodes have a value of
0
or
1
.
Non-leaf nodes have a value of
2
,
3
,
4
, or
5
.
| null | null |
/**
* 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 minimumFlips(TreeNode* root, bool result) {
function<pair<int, int>(TreeNode*)> dfs = [&](TreeNode* root) -> pair<int, int> {
if (!root) {
return {1 << 30, 1 << 30};
}
int x = root->val;
if (x < 2) {
return {x, x ^ 1};
}
auto [l0, l1] = dfs(root->left);
auto [r0, r1] = dfs(root->right);
int a = 0, b = 0;
if (x == 2) {
a = l0 + r0;
b = min({l0 + r1, l1 + r0, l1 + r1});
} else if (x == 3) {
a = min({l0 + r0, l0 + r1, l1 + r0});
b = l1 + r1;
} else if (x == 4) {
a = min(l0 + r0, l1 + r1);
b = min(l0 + r1, l1 + r0);
} else {
a = min(l1, r1);
b = min(l0, r0);
}
return {a, b};
};
auto [a, b] = dfs(root);
return result ? b : a;
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minimumFlips(root *TreeNode, result bool) int {
var dfs func(*TreeNode) (int, int)
dfs = func(root *TreeNode) (int, int) {
if root == nil {
return 1 << 30, 1 << 30
}
x := root.Val
if x < 2 {
return x, x ^ 1
}
l0, l1 := dfs(root.Left)
r0, r1 := dfs(root.Right)
var a, b int
if x == 2 {
a = l0 + r0
b = min(l0+r1, min(l1+r0, l1+r1))
} else if x == 3 {
a = min(l0+r0, min(l0+r1, l1+r0))
b = l1 + r1
} else if x == 4 {
a = min(l0+r0, l1+r1)
b = min(l0+r1, l1+r0)
} else {
a = min(l1, r1)
b = min(l0, r0)
}
return a, b
}
a, b := dfs(root)
if result {
return b
}
return a
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minimumFlips(TreeNode root, boolean result) {
return dfs(root)[result ? 1 : 0];
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[] {1 << 30, 1 << 30};
}
int x = root.val;
if (x < 2) {
return new int[] {x, x ^ 1};
}
var l = dfs(root.left);
var r = dfs(root.right);
int a = 0, b = 0;
if (x == 2) {
a = l[0] + r[0];
b = Math.min(l[0] + r[1], Math.min(l[1] + r[0], l[1] + r[1]));
} else if (x == 3) {
a = Math.min(l[0] + r[0], Math.min(l[0] + r[1], l[1] + r[0]));
b = l[1] + r[1];
} else if (x == 4) {
a = Math.min(l[0] + r[0], l[1] + r[1]);
b = Math.min(l[0] + r[1], l[1] + r[0]);
} else {
a = Math.min(l[1], r[1]);
b = Math.min(l[0], r[0]);
}
return new int[] {a, b};
}
}
| null | null | null | null | null | null |
# 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 minimumFlips(self, root: Optional[TreeNode], result: bool) -> int:
def dfs(root: Optional[TreeNode]) -> (int, int):
if root is None:
return inf, inf
x = root.val
if x in (0, 1):
return x, x ^ 1
l, r = dfs(root.left), dfs(root.right)
if x == 2:
return l[0] + r[0], min(l[0] + r[1], l[1] + r[0], l[1] + r[1])
if x == 3:
return min(l[0] + r[0], l[0] + r[1], l[1] + r[0]), l[1] + r[1]
if x == 4:
return min(l[0] + r[0], l[1] + r[1]), min(l[0] + r[1], l[1] + r[0])
return min(l[1], r[1]), min(l[0], r[0])
return dfs(root)[int(result)]
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function minimumFlips(root: TreeNode | null, result: boolean): number {
const dfs = (root: TreeNode | null): [number, number] => {
if (!root) {
return [1 << 30, 1 << 30];
}
const x = root.val;
if (x < 2) {
return [x, x ^ 1];
}
const [l0, l1] = dfs(root.left);
const [r0, r1] = dfs(root.right);
if (x === 2) {
return [l0 + r0, Math.min(l0 + r1, l1 + r0, l1 + r1)];
}
if (x === 3) {
return [Math.min(l0 + r0, l0 + r1, l1 + r0), l1 + r1];
}
if (x === 4) {
return [Math.min(l0 + r0, l1 + r1), Math.min(l0 + r1, l1 + r0)];
}
return [Math.min(l1, r1), Math.min(l0, r0)];
};
return dfs(root)[result ? 1 : 0];
}
|
Second Minimum Time to Reach Destination
|
A city is represented as a
bi-directional connected
graph with
n
vertices where each vertex is labeled from
1
to
n
(
inclusive
). The edges in the graph are represented as a 2D integer array
edges
, where each
edges[i] = [u
i
, v
i
]
denotes a bi-directional edge between vertex
u
i
and vertex
v
i
. Every vertex pair is connected by
at most one
edge, and no vertex has an edge to itself. The time taken to traverse any edge is
time
minutes.
Each vertex has a traffic signal which changes its color from
green
to
red
and vice versa every
change
minutes. All signals change
at the same time
. You can enter a vertex at
any time
, but can leave a vertex
only when the signal is green
. You
cannot wait
at a vertex if the signal is
green
.
The
second minimum value
is defined as the smallest value
strictly larger
than the minimum value.
For example the second minimum value of
[2, 3, 4]
is
3
, and the second minimum value of
[2, 2, 4]
is
4
.
Given
n
,
edges
,
time
, and
change
, return
the
second minimum time
it will take to go from vertex
1
to vertex
n
.
Notes:
You can go through any vertex
any
number of times,
including
1
and
n
.
You can assume that when the journey
starts
, all signals have just turned
green
.
Example 1:
Input:
n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output:
13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input:
n = 2, edges = [[1,2]], time = 3, change = 2
Output:
11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 10
4
n - 1 <= edges.length <= min(2 * 10
4
, n * (n - 1) / 2)
edges[i].length == 2
1 <= u
i
, v
i
<= n
u
i
!= v
i
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 10
3
| null | null | null | null | null | null |
class Solution {
public int secondMinimum(int n, int[][] edges, int time, int change) {
List<Integer>[] g = new List[n + 1];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int u = e[0], v = e[1];
g[u].add(v);
g[v].add(u);
}
Deque<int[]> q = new LinkedList<>();
q.offerLast(new int[] {1, 0});
int[][] dist = new int[n + 1][2];
for (int i = 0; i < n + 1; ++i) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
}
dist[1][1] = 0;
while (!q.isEmpty()) {
int[] e = q.pollFirst();
int u = e[0], d = e[1];
for (int v : g[u]) {
if (d + 1 < dist[v][0]) {
dist[v][0] = d + 1;
q.offerLast(new int[] {v, d + 1});
} else if (dist[v][0] < d + 1 && d + 1 < dist[v][1]) {
dist[v][1] = d + 1;
if (v == n) {
break;
}
q.offerLast(new int[] {v, d + 1});
}
}
}
int ans = 0;
for (int i = 0; i < dist[n][1]; ++i) {
ans += time;
if (i < dist[n][1] - 1 && (ans / change) % 2 == 1) {
ans = (ans + change) / change * change;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def secondMinimum(
self, n: int, edges: List[List[int]], time: int, change: int
) -> int:
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
q = deque([(1, 0)])
dist = [[inf] * 2 for _ in range(n + 1)]
dist[1][1] = 0
while q:
u, d = q.popleft()
for v in g[u]:
if d + 1 < dist[v][0]:
dist[v][0] = d + 1
q.append((v, d + 1))
elif dist[v][0] < d + 1 < dist[v][1]:
dist[v][1] = d + 1
if v == n:
break
q.append((v, d + 1))
ans = 0
for i in range(dist[n][1]):
ans += time
if i < dist[n][1] - 1 and (ans // change) % 2 == 1:
ans = (ans + change) // change * change
return ans
| null | null | null | null | null | null |
Maximum Number of Tasks You Can Assign
|
You have
n
tasks and
m
workers. Each task has a strength requirement stored in a
0-indexed
integer array
tasks
, with the
i
th
task requiring
tasks[i]
strength to complete. The strength of each worker is stored in a
0-indexed
integer array
workers
, with the
j
th
worker having
workers[j]
strength. Each worker can only be assigned to a
single
task and must have a strength
greater than or equal
to the task's strength requirement (i.e.,
workers[j] >= tasks[i]
).
Additionally, you have
pills
magical pills that will
increase a worker's strength
by
strength
. You can decide which workers receive the magical pills, however, you may only give each worker
at most one
magical pill.
Given the
0-indexed
integer arrays
tasks
and
workers
and the integers
pills
and
strength
, return
the
maximum
number of tasks that can be completed.
Example 1:
Input:
tasks = [
3
,
2
,
1
], workers = [
0
,
3
,
3
], pills = 1, strength = 1
Output:
3
Explanation:
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 2 (0 + 1 >= 1)
- Assign worker 1 to task 1 (3 >= 2)
- Assign worker 2 to task 0 (3 >= 3)
Example 2:
Input:
tasks = [
5
,4], workers = [
0
,0,0], pills = 1, strength = 5
Output:
1
Explanation:
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 0 (0 + 5 >= 5)
Example 3:
Input:
tasks = [
10
,
15
,30], workers = [
0
,
10
,10,10,10], pills = 3, strength = 10
Output:
2
Explanation:
We can assign the magical pills and tasks as follows:
- Give the magical pill to worker 0 and worker 1.
- Assign worker 0 to task 0 (0 + 10 >= 10)
- Assign worker 1 to task 1 (10 + 10 >= 15)
The last pill is not given because it will not make any worker strong enough for the last task.
Constraints:
n == tasks.length
m == workers.length
1 <= n, m <= 5 * 10
4
0 <= pills <= m
0 <= tasks[i], workers[j], strength <= 10
9
| null | null |
class Solution {
public:
int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {
sort(tasks.begin(), tasks.end());
sort(workers.begin(), workers.end());
int n = tasks.size(), m = workers.size();
int left = 0, right = min(m, n);
auto check = [&](int x) {
int p = pills;
deque<int> q;
int i = 0;
for (int j = m - x; j < m; ++j) {
while (i < x && tasks[i] <= workers[j] + strength) {
q.push_back(tasks[i++]);
}
if (q.empty()) {
return false;
}
if (q.front() <= workers[j]) {
q.pop_front();
} else if (p == 0) {
return false;
} else {
--p;
q.pop_back();
}
}
return true;
};
while (left < right) {
int mid = (left + right + 1) >> 1;
if (check(mid)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
};
| null | null |
func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {
sort.Ints(tasks)
sort.Ints(workers)
n, m := len(tasks), len(workers)
left, right := 0, min(m, n)
check := func(x int) bool {
p := pills
q := []int{}
i := 0
for j := m - x; j < m; j++ {
for i < x && tasks[i] <= workers[j]+strength {
q = append(q, tasks[i])
i++
}
if len(q) == 0 {
return false
}
if q[0] <= workers[j] {
q = q[1:]
} else if p == 0 {
return false
} else {
p--
q = q[:len(q)-1]
}
}
return true
}
for left < right {
mid := (left + right + 1) >> 1
if check(mid) {
left = mid
} else {
right = mid - 1
}
}
return left
}
|
class Solution {
private int[] tasks;
private int[] workers;
private int strength;
private int pills;
private int m;
private int n;
public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {
Arrays.sort(tasks);
Arrays.sort(workers);
this.tasks = tasks;
this.workers = workers;
this.strength = strength;
this.pills = pills;
n = tasks.length;
m = workers.length;
int left = 0, right = Math.min(m, n);
while (left < right) {
int mid = (left + right + 1) >> 1;
if (check(mid)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
private boolean check(int x) {
int i = 0;
Deque<Integer> q = new ArrayDeque<>();
int p = pills;
for (int j = m - x; j < m; ++j) {
while (i < x && tasks[i] <= workers[j] + strength) {
q.offer(tasks[i++]);
}
if (q.isEmpty()) {
return false;
}
if (q.peekFirst() <= workers[j]) {
q.pollFirst();
} else if (p == 0) {
return false;
} else {
--p;
q.pollLast();
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def maxTaskAssign(
self, tasks: List[int], workers: List[int], pills: int, strength: int
) -> int:
def check(x):
i = 0
q = deque()
p = pills
for j in range(m - x, m):
while i < x and tasks[i] <= workers[j] + strength:
q.append(tasks[i])
i += 1
if not q:
return False
if q[0] <= workers[j]:
q.popleft()
elif p == 0:
return False
else:
p -= 1
q.pop()
return True
n, m = len(tasks), len(workers)
tasks.sort()
workers.sort()
left, right = 0, min(n, m)
while left < right:
mid = (left + right + 1) >> 1
if check(mid):
left = mid
else:
right = mid - 1
return left
| null | null | null | null | null |
function maxTaskAssign(
tasks: number[],
workers: number[],
pills: number,
strength: number,
): number {
tasks.sort((a, b) => a - b);
workers.sort((a, b) => a - b);
const n = tasks.length;
const m = workers.length;
const check = (x: number): boolean => {
const dq = new Array<number>(x);
let head = 0;
let tail = 0;
const empty = () => head === tail;
const pushBack = (val: number) => {
dq[tail++] = val;
};
const popFront = () => {
head++;
};
const popBack = () => {
tail--;
};
const front = () => dq[head];
let i = 0;
let p = pills;
for (let j = m - x; j < m; j++) {
while (i < x && tasks[i] <= workers[j] + strength) {
pushBack(tasks[i]);
i++;
}
if (empty()) return false;
if (front() <= workers[j]) {
popFront();
} else {
if (p === 0) return false;
p--;
popBack();
}
}
return true;
};
let [left, right] = [0, Math.min(n, m)];
while (left < right) {
const mid = (left + right + 1) >> 1;
if (check(mid)) left = mid;
else right = mid - 1;
}
return left;
}
|
Phone Number Prefix 🔒
|
You are given a string array
numbers
that represents phone numbers. Return
true
if no phone number is a prefix of any other phone number; otherwise, return
false
.
Example 1:
Input:
numbers = ["1","2","4","3"]
Output:
true
Explanation:
No number is a prefix of another number, so the output is
true
.
Example 2:
Input:
numbers = ["001","007","15","00153"]
Output:
false
Explanation:
The string
"001"
is a prefix of the string
"00153"
. Thus, the output is
false
.
Constraints:
2 <= numbers.length <= 50
1 <= numbers[i].length <= 50
All numbers contain only digits
'0'
to
'9'
.
| null | null |
#include <ranges>
class Solution {
public:
bool phonePrefix(vector<string>& numbers) {
ranges::sort(numbers, [](const string& a, const string& b) {
return a.size() < b.size();
});
for (int i = 0; i < numbers.size(); i++) {
if (ranges::any_of(numbers | views::take(i), [&](const string& t) {
return numbers[i].starts_with(t);
})) {
return false;
}
}
return true;
}
};
| null | null |
func phonePrefix(numbers []string) bool {
sort.Slice(numbers, func(i, j int) bool {
return len(numbers[i]) < len(numbers[j])
})
for i, s := range numbers {
for _, t := range numbers[:i] {
if strings.HasPrefix(s, t) {
return false
}
}
}
return true
}
|
class Solution {
public boolean phonePrefix(String[] numbers) {
Arrays.sort(numbers, (a, b) -> Integer.compare(a.length(), b.length()));
for (int i = 0; i < numbers.length; i++) {
String s = numbers[i];
for (int j = 0; j < i; j++) {
if (s.startsWith(numbers[j])) {
return false;
}
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def phonePrefix(self, numbers: List[str]) -> bool:
numbers.sort(key=len)
for i, s in enumerate(numbers):
if any(s.startswith(t) for t in numbers[:i]):
return False
return True
| null | null | null | null | null |
function phonePrefix(numbers: string[]): boolean {
numbers.sort((a, b) => a.length - b.length);
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < i; j++) {
if (numbers[i].startsWith(numbers[j])) {
return false;
}
}
}
return true;
}
|
Minimum Element After Replacement With Digit Sum
|
You are given an integer array
nums
.
You replace each element in
nums
with the
sum
of its digits.
Return the
minimum
element in
nums
after all replacements.
Example 1:
Input:
nums = [10,12,13,14]
Output:
1
Explanation:
nums
becomes
[1, 3, 4, 5]
after all replacements, with minimum element 1.
Example 2:
Input:
nums = [1,2,3,4]
Output:
1
Explanation:
nums
becomes
[1, 2, 3, 4]
after all replacements, with minimum element 1.
Example 3:
Input:
nums = [999,19,199]
Output:
10
Explanation:
nums
becomes
[27, 10, 19]
after all replacements, with minimum element 10.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 10
4
| null | null |
class Solution {
public:
int minElement(vector<int>& nums) {
int ans = 100;
for (int x : nums) {
int y = 0;
for (; x > 0; x /= 10) {
y += x % 10;
}
ans = min(ans, y);
}
return ans;
}
};
| null | null |
func minElement(nums []int) int {
ans := 100
for _, x := range nums {
y := 0
for ; x > 0; x /= 10 {
y += x % 10
}
ans = min(ans, y)
}
return ans
}
|
class Solution {
public int minElement(int[] nums) {
int ans = 100;
for (int x : nums) {
int y = 0;
for (; x > 0; x /= 10) {
y += x % 10;
}
ans = Math.min(ans, y);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minElement(self, nums: List[int]) -> int:
return min(sum(int(b) for b in str(x)) for x in nums)
| null | null | null | null | null |
function minElement(nums: number[]): number {
let ans: number = 100;
for (let x of nums) {
let y = 0;
for (; x; x = Math.floor(x / 10)) {
y += x % 10;
}
ans = Math.min(ans, y);
}
return ans;
}
|
Grid Game
|
You are given a
0-indexed
2D array
grid
of size
2 x n
, where
grid[r][c]
represents the number of points at position
(r, c)
on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at
(0, 0)
and want to reach
(1, n-1)
. Each robot may only move to the
right
(
(r, c)
to
(r, c + 1)
) or
down
(
(r, c)
to
(r + 1, c)
).
At the start of the game, the
first
robot moves from
(0, 0)
to
(1, n-1)
, collecting all the points from the cells on its path. For all cells
(r, c)
traversed on the path,
grid[r][c]
is set to
0
. Then, the
second
robot moves from
(0, 0)
to
(1, n-1)
, collecting the points on its path. Note that their paths may intersect with one another.
The
first
robot wants to
minimize
the number of points collected by the
second
robot. In contrast, the
second
robot wants to
maximize
the number of points it collects. If both robots play
optimally
, return
the
number of points
collected by the
second
robot.
Example 1:
Input:
grid = [[2,5,4],[1,5,1]]
Output:
4
Explanation:
The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 0 + 4 + 0 = 4 points.
Example 2:
Input:
grid = [[3,3,1],[8,5,2]]
Output:
4
Explanation:
The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 3 + 1 + 0 = 4 points.
Example 3:
Input:
grid = [[1,3,1,15],[1,3,3,1]]
Output:
7
Explanation:
The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.
Constraints:
grid.length == 2
n == grid[r].length
1 <= n <= 5 * 10
4
1 <= grid[r][c] <= 10
5
| null | null |
using ll = long long;
class Solution {
public:
long long gridGame(vector<vector<int>>& grid) {
ll ans = LONG_MAX;
int n = grid[0].size();
ll s1 = 0, s2 = 0;
for (int& v : grid[0]) s1 += v;
for (int j = 0; j < n; ++j) {
s1 -= grid[0][j];
ans = min(ans, max(s1, s2));
s2 += grid[1][j];
}
return ans;
}
};
| null | null |
func gridGame(grid [][]int) int64 {
ans := math.MaxInt64
s1, s2 := 0, 0
for _, v := range grid[0] {
s1 += v
}
for j, v := range grid[0] {
s1 -= v
ans = min(ans, max(s1, s2))
s2 += grid[1][j]
}
return int64(ans)
}
|
class Solution {
public long gridGame(int[][] grid) {
long ans = Long.MAX_VALUE;
long s1 = 0, s2 = 0;
for (int v : grid[0]) {
s1 += v;
}
int n = grid[0].length;
for (int j = 0; j < n; ++j) {
s1 -= grid[0][j];
ans = Math.min(ans, Math.max(s1, s2));
s2 += grid[1][j];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
ans = inf
s1, s2 = sum(grid[0]), 0
for j, v in enumerate(grid[0]):
s1 -= v
ans = min(ans, max(s1, s2))
s2 += grid[1][j]
return ans
| null | null | null | null | null |
function gridGame(grid: number[][]): number {
let ans = Number.MAX_SAFE_INTEGER;
let s1 = grid[0].reduce((a, b) => a + b, 0);
let s2 = 0;
for (let j = 0; j < grid[0].length; ++j) {
s1 -= grid[0][j];
ans = Math.min(ans, Math.max(s1, s2));
s2 += grid[1][j];
}
return ans;
}
|
Minimum Incompatibility
|
You are given an integer array
nums
and an integer
k
. You are asked to distribute this array into
k
subsets of
equal size
such that there are no two equal elements in the same subset.
A subset's
incompatibility
is the difference between the maximum and minimum elements in that array.
Return
the
minimum possible sum of incompatibilities
of the
k
subsets after distributing the array optimally, or return
-1
if it is not possible.
A subset is a group integers that appear in the array with no particular order.
Example 1:
Input:
nums = [1,2,1,4], k = 2
Output:
4
Explanation:
The optimal distribution of subsets is [1,2] and [1,4].
The incompatibility is (2-1) + (4-1) = 4.
Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input:
nums = [6,3,8,1,3,1,2,2], k = 4
Output:
6
Explanation:
The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input:
nums = [5,3,3,6,3,3], k = 3
Output:
-1
Explanation:
It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16
nums.length
is divisible by
k
1 <= nums[i] <= nums.length
| null |
public class Solution {
public int MinimumIncompatibility(int[] nums, int k) {
int n = nums.Length;
int m = n / k;
int[] g = new int[1 << n];
Array.Fill(g, -1);
for (int i = 1; i < 1 << n; ++i) {
if (bitCount(i) != m) {
continue;
}
HashSet<int> s = new();
int mi = 20, mx = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
if (s.Contains(nums[j])) {
break;
}
s.Add(nums[j]);
mi = Math.Min(mi, nums[j]);
mx = Math.Max(mx, nums[j]);
}
}
if (s.Count == m) {
g[i] = mx - mi;
}
}
int[] f = new int[1 << n];
int inf = 1 << 30;
Array.Fill(f, inf);
f[0] = 0;
for (int i = 0; i < 1 << n; ++i) {
if (f[i] == inf) {
continue;
}
HashSet<int> s = new();
int mask = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 0 && !s.Contains(nums[j])) {
s.Add(nums[j]);
mask |= 1 << j;
}
}
if (s.Count < m) {
continue;
}
for (int j = mask; j > 0; j = (j - 1) & mask) {
if (g[j] != -1) {
f[i | j] = Math.Min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1];
}
private int bitCount(int x) {
int cnt = 0;
while (x > 0) {
x &= x - 1;
++cnt;
}
return cnt;
}
}
|
class Solution {
public:
int minimumIncompatibility(vector<int>& nums, int k) {
int n = nums.size();
int m = n / k;
int g[1 << n];
memset(g, -1, sizeof(g));
for (int i = 1; i < 1 << n; ++i) {
if (__builtin_popcount(i) != m) {
continue;
}
unordered_set<int> s;
int mi = 20, mx = 0;
for (int j = 0; j < n; ++j) {
if (i >> j & 1) {
if (s.count(nums[j])) {
break;
}
s.insert(nums[j]);
mi = min(mi, nums[j]);
mx = max(mx, nums[j]);
}
}
if (s.size() == m) {
g[i] = mx - mi;
}
}
int f[1 << n];
memset(f, 0x3f, sizeof(f));
f[0] = 0;
for (int i = 0; i < 1 << n; ++i) {
if (f[i] == 0x3f3f3f3f) {
continue;
}
unordered_set<int> s;
int mask = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 0 && !s.count(nums[j])) {
s.insert(nums[j]);
mask |= 1 << j;
}
}
if (s.size() < m) {
continue;
}
for (int j = mask; j; j = (j - 1) & mask) {
if (g[j] != -1) {
f[i | j] = min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] == 0x3f3f3f3f ? -1 : f[(1 << n) - 1];
}
};
| null | null |
func minimumIncompatibility(nums []int, k int) int {
n := len(nums)
m := n / k
const inf = 1 << 30
f := make([]int, 1<<n)
g := make([]int, 1<<n)
for i := range g {
f[i] = inf
g[i] = -1
}
for i := 1; i < 1<<n; i++ {
if bits.OnesCount(uint(i)) != m {
continue
}
s := map[int]struct{}{}
mi, mx := 20, 0
for j, x := range nums {
if i>>j&1 == 1 {
if _, ok := s[x]; ok {
break
}
s[x] = struct{}{}
mi = min(mi, x)
mx = max(mx, x)
}
}
if len(s) == m {
g[i] = mx - mi
}
}
f[0] = 0
for i := 0; i < 1<<n; i++ {
if f[i] == inf {
continue
}
s := map[int]struct{}{}
mask := 0
for j, x := range nums {
if _, ok := s[x]; !ok && i>>j&1 == 0 {
s[x] = struct{}{}
mask |= 1 << j
}
}
if len(s) < m {
continue
}
for j := mask; j > 0; j = (j - 1) & mask {
if g[j] != -1 {
f[i|j] = min(f[i|j], f[i]+g[j])
}
}
}
if f[1<<n-1] == inf {
return -1
}
return f[1<<n-1]
}
|
class Solution {
public int minimumIncompatibility(int[] nums, int k) {
int n = nums.length;
int m = n / k;
int[] g = new int[1 << n];
Arrays.fill(g, -1);
for (int i = 1; i < 1 << n; ++i) {
if (Integer.bitCount(i) != m) {
continue;
}
Set<Integer> s = new HashSet<>();
int mi = 20, mx = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
if (!s.add(nums[j])) {
break;
}
mi = Math.min(mi, nums[j]);
mx = Math.max(mx, nums[j]);
}
}
if (s.size() == m) {
g[i] = mx - mi;
}
}
int[] f = new int[1 << n];
final int inf = 1 << 30;
Arrays.fill(f, inf);
f[0] = 0;
for (int i = 0; i < 1 << n; ++i) {
if (f[i] == inf) {
continue;
}
Set<Integer> s = new HashSet<>();
int mask = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 0 && !s.contains(nums[j])) {
s.add(nums[j]);
mask |= 1 << j;
}
}
if (s.size() < m) {
continue;
}
for (int j = mask; j > 0; j = (j - 1) & mask) {
if (g[j] != -1) {
f[i | j] = Math.min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1];
}
}
| null | null | null | null | null | null |
class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
n = len(nums)
m = n // k
g = [-1] * (1 << n)
for i in range(1, 1 << n):
if i.bit_count() != m:
continue
s = set()
mi, mx = 20, 0
for j, x in enumerate(nums):
if i >> j & 1:
if x in s:
break
s.add(x)
mi = min(mi, x)
mx = max(mx, x)
if len(s) == m:
g[i] = mx - mi
f = [inf] * (1 << n)
f[0] = 0
for i in range(1 << n):
if f[i] == inf:
continue
s = set()
mask = 0
for j, x in enumerate(nums):
if (i >> j & 1) == 0 and x not in s:
s.add(x)
mask |= 1 << j
if len(s) < m:
continue
j = mask
while j:
if g[j] != -1:
f[i | j] = min(f[i | j], f[i] + g[j])
j = (j - 1) & mask
return f[-1] if f[-1] != inf else -1
| null | null | null | null | null |
function minimumIncompatibility(nums: number[], k: number): number {
const n = nums.length;
const m = Math.floor(n / k);
const g: number[] = Array(1 << n).fill(-1);
for (let i = 1; i < 1 << n; ++i) {
if (bitCount(i) !== m) {
continue;
}
const s: Set<number> = new Set();
let [mi, mx] = [20, 0];
for (let j = 0; j < n; ++j) {
if ((i >> j) & 1) {
if (s.has(nums[j])) {
break;
}
s.add(nums[j]);
mi = Math.min(mi, nums[j]);
mx = Math.max(mx, nums[j]);
}
}
if (s.size === m) {
g[i] = mx - mi;
}
}
const inf = 1e9;
const f: number[] = Array(1 << n).fill(inf);
f[0] = 0;
for (let i = 0; i < 1 << n; ++i) {
if (f[i] === inf) {
continue;
}
const s: Set<number> = new Set();
let mask = 0;
for (let j = 0; j < n; ++j) {
if (((i >> j) & 1) === 0 && !s.has(nums[j])) {
s.add(nums[j]);
mask |= 1 << j;
}
}
if (s.size < m) {
continue;
}
for (let j = mask; j; j = (j - 1) & mask) {
if (g[j] !== -1) {
f[i | j] = Math.min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] === inf ? -1 : f[(1 << n) - 1];
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
Last Stone Weight
|
You are given an array of integers
stones
where
stones[i]
is the weight of the
i
th
stone.
We are playing a game with the stones. On each turn, we choose the
heaviest two stones
and smash them together. Suppose the heaviest two stones have weights
x
and
y
with
x <= y
. The result of this smash is:
If
x == y
, both stones are destroyed, and
If
x != y
, the stone of weight
x
is destroyed, and the stone of weight
y
has new weight
y - x
.
At the end of the game, there is
at most one
stone left.
Return
the weight of the last remaining stone
. If there are no stones left, return
0
.
Example 1:
Input:
stones = [2,7,4,1,8,1]
Output:
1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
Example 2:
Input:
stones = [1]
Output:
1
Constraints:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
| null | null |
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq;
for (int x : stones) {
pq.push(x);
}
while (pq.size() > 1) {
int y = pq.top();
pq.pop();
int x = pq.top();
pq.pop();
if (x != y) {
pq.push(y - x);
}
}
return pq.empty() ? 0 : pq.top();
}
};
| null | null |
func lastStoneWeight(stones []int) int {
q := &hp{stones}
heap.Init(q)
for q.Len() > 1 {
y, x := q.pop(), q.pop()
if x != y {
q.push(y - x)
}
}
if q.Len() > 0 {
return q.IntSlice[0]
}
return 0
}
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) }
|
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a);
for (int x : stones) {
q.offer(x);
}
while (q.size() > 1) {
int y = q.poll();
int x = q.poll();
if (x != y) {
q.offer(y - x);
}
}
return q.isEmpty() ? 0 : q.poll();
}
}
|
/**
* @param {number[]} stones
* @return {number}
*/
var lastStoneWeight = function (stones) {
const pq = new MaxPriorityQueue();
for (const x of stones) {
pq.enqueue(x);
}
while (pq.size() > 1) {
const y = pq.dequeue();
const x = pq.dequeue();
if (x != y) {
pq.enqueue(y - x);
}
}
return pq.isEmpty() ? 0 : pq.dequeue();
};
| null | null | null | null | null |
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
h = [-x for x in stones]
heapify(h)
while len(h) > 1:
y, x = -heappop(h), -heappop(h)
if x != y:
heappush(h, x - y)
return 0 if not h else -h[0]
| null | null | null | null | null |
function lastStoneWeight(stones: number[]): number {
const pq = new MaxPriorityQueue<number>();
for (const x of stones) {
pq.enqueue(x);
}
while (pq.size() > 1) {
const y = pq.dequeue();
const x = pq.dequeue();
if (x !== y) {
pq.enqueue(y - x);
}
}
return pq.isEmpty() ? 0 : pq.dequeue();
}
|
Minimum Total Distance Traveled
|
There are some robots and factories on the X-axis. You are given an integer array
robot
where
robot[i]
is the position of the
i
th
robot. You are also given a 2D integer array
factory
where
factory[j] = [position
j
, limit
j
]
indicates that
position
j
is the position of the
j
th
factory and that the
j
th
factory can repair at most
limit
j
robots.
The positions of each robot are
unique
. The positions of each factory are also
unique
. Note that a robot can be
in the same position
as a factory initially.
All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.
At any moment
, you can set the initial direction of moving for
some
robot. Your target is to minimize the total distance traveled by all the robots.
Return
the minimum total distance traveled by all the robots
. The test cases are generated such that all the robots can be repaired.
Note that
All robots move at the same speed.
If two robots move in the same direction, they will never collide.
If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
If the robot moved from a position
x
to a position
y
, the distance it moved is
|y - x|
.
Example 1:
Input:
robot = [0,4,6], factory = [[2,2],[6,2]]
Output:
4
Explanation:
As shown in the figure:
- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.
- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.
- The third robot at position 6 will be repaired at the second factory. It does not need to move.
The limit of the first factory is 2, and it fixed 2 robots.
The limit of the second factory is 2, and it fixed 1 robot.
The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
Example 2:
Input:
robot = [1,-1], factory = [[-2,1],[2,1]]
Output:
2
Explanation:
As shown in the figure:
- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.
- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.
The limit of the first factory is 1, and it fixed 1 robot.
The limit of the second factory is 1, and it fixed 1 robot.
The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.
Constraints:
1 <= robot.length, factory.length <= 100
factory[j].length == 2
-10
9
<= robot[i], position
j
<= 10
9
0 <= limit
j
<= robot.length
The input will be generated such that it is always possible to repair every robot.
| null | null |
using ll = long long;
class Solution {
public:
long long minimumTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
sort(robot.begin(), robot.end());
sort(factory.begin(), factory.end());
vector<vector<ll>> f(robot.size(), vector<ll>(factory.size()));
function<ll(int i, int j)> dfs = [&](int i, int j) -> ll {
if (i == robot.size()) return 0;
if (j == factory.size()) return 1e15;
if (f[i][j]) return f[i][j];
ll ans = dfs(i, j + 1);
ll t = 0;
for (int k = 0; k < factory[j][1]; ++k) {
if (i + k >= robot.size()) break;
t += abs(robot[i + k] - factory[j][0]);
ans = min(ans, t + dfs(i + k + 1, j + 1));
}
f[i][j] = ans;
return ans;
};
return dfs(0, 0);
}
};
| null | null |
func minimumTotalDistance(robot []int, factory [][]int) int64 {
sort.Ints(robot)
sort.Slice(factory, func(i, j int) bool { return factory[i][0] < factory[j][0] })
f := make([][]int, len(robot))
for i := range f {
f[i] = make([]int, len(factory))
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i == len(robot) {
return 0
}
if j == len(factory) {
return 1e15
}
if f[i][j] != 0 {
return f[i][j]
}
ans := dfs(i, j+1)
t := 0
for k := 0; k < factory[j][1]; k++ {
if i+k >= len(robot) {
break
}
t += abs(robot[i+k] - factory[j][0])
ans = min(ans, t+dfs(i+k+1, j+1))
}
f[i][j] = ans
return ans
}
return int64(dfs(0, 0))
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
private long[][] f;
private List<Integer> robot;
private int[][] factory;
public long minimumTotalDistance(List<Integer> robot, int[][] factory) {
Collections.sort(robot);
Arrays.sort(factory, (a, b) -> a[0] - b[0]);
this.robot = robot;
this.factory = factory;
f = new long[robot.size()][factory.length];
return dfs(0, 0);
}
private long dfs(int i, int j) {
if (i == robot.size()) {
return 0;
}
if (j == factory.length) {
return Long.MAX_VALUE / 1000;
}
if (f[i][j] != 0) {
return f[i][j];
}
long ans = dfs(i, j + 1);
long t = 0;
for (int k = 0; k < factory[j][1]; ++k) {
if (i + k == robot.size()) {
break;
}
t += Math.abs(robot.get(i + k) - factory[j][0]);
ans = Math.min(ans, t + dfs(i + k + 1, j + 1));
}
f[i][j] = ans;
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
@cache
def dfs(i, j):
if i == len(robot):
return 0
if j == len(factory):
return inf
ans = dfs(i, j + 1)
t = 0
for k in range(factory[j][1]):
if i + k == len(robot):
break
t += abs(robot[i + k] - factory[j][0])
ans = min(ans, t + dfs(i + k + 1, j + 1))
return ans
robot.sort()
factory.sort()
ans = dfs(0, 0)
dfs.cache_clear()
return ans
| null | null | null | null | null | null |
How Many Numbers Are Smaller Than the Current Number
|
Given the array
nums
, for each
nums[i]
find out how many numbers in the array are smaller than it. That is, for each
nums[i]
you have to count the number of valid
j's
such that
j != i
and
nums[j] < nums[i]
.
Return the answer in an array.
Example 1:
Input:
nums = [8,1,2,2,3]
Output:
[4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input:
nums = [6,5,4,8]
Output:
[2,1,0,3]
Example 3:
Input:
nums = [7,7,7,7]
Output:
[0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
| null | null |
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
int cnt[102]{};
for (int& x : nums) {
++cnt[x + 1];
}
for (int i = 1; i < 102; ++i) {
cnt[i] += cnt[i - 1];
}
vector<int> ans;
for (int& x : nums) {
ans.push_back(cnt[x]);
}
return ans;
}
};
| null | null |
func smallerNumbersThanCurrent(nums []int) (ans []int) {
cnt := [102]int{}
for _, x := range nums {
cnt[x+1]++
}
for i := 1; i < len(cnt); i++ {
cnt[i] += cnt[i-1]
}
for _, x := range nums {
ans = append(ans, cnt[x])
}
return
}
|
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] cnt = new int[102];
for (int x : nums) {
++cnt[x + 1];
}
for (int i = 1; i < cnt.length; ++i) {
cnt[i] += cnt[i - 1];
}
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = cnt[nums[i]];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
cnt = [0] * 102
for x in nums:
cnt[x + 1] += 1
s = list(accumulate(cnt))
return [s[x] for x in nums]
| null | null | null | null | null |
function smallerNumbersThanCurrent(nums: number[]): number[] {
const cnt: number[] = new Array(102).fill(0);
for (const x of nums) {
++cnt[x + 1];
}
for (let i = 1; i < cnt.length; ++i) {
cnt[i] += cnt[i - 1];
}
const n = nums.length;
const ans: number[] = new Array(n);
for (let i = 0; i < n; ++i) {
ans[i] = cnt[nums[i]];
}
return ans;
}
|
Count Triplets with Even XOR Set Bits II 🔒
|
Given three integer arrays
a
,
b
, and
c
, return the number of triplets
(a[i], b[j], c[k])
, such that the bitwise
XOR
between the elements of each triplet has an
even
number of
set bits
.
Example 1:
Input:
a = [1], b = [2], c = [3]
Output:
1
Explanation:
The only triplet is
(a[0], b[0], c[0])
and their
XOR
is:
1 XOR 2 XOR 3 = 00
2
.
Example 2:
Input:
a = [1,1], b = [2,3], c = [1,5]
Output:
4
Explanation:
Consider these four triplets:
(a[0], b[1], c[0])
:
1 XOR 3 XOR 1 = 011
2
(a[1], b[1], c[0])
:
1 XOR 3 XOR 1 = 011
2
(a[0], b[0], c[1])
:
1 XOR 2 XOR 5 = 110
2
(a[1], b[0], c[1])
:
1 XOR 2 XOR 5 = 110
2
Constraints:
1 <= a.length, b.length, c.length <= 10
5
0 <= a[i], b[i], c[i] <= 10
9
| null | null |
class Solution {
public:
long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
int cnt1[2]{};
int cnt2[2]{};
int cnt3[2]{};
for (int x : a) {
++cnt1[__builtin_popcount(x) & 1];
}
for (int x : b) {
++cnt2[__builtin_popcount(x) & 1];
}
for (int x : c) {
++cnt3[__builtin_popcount(x) & 1];
}
long long ans = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
if ((i + j + k) % 2 == 0) {
ans += 1LL * cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
};
| null | null |
func tripletCount(a []int, b []int, c []int) (ans int64) {
cnt1 := [2]int{}
cnt2 := [2]int{}
cnt3 := [2]int{}
for _, x := range a {
cnt1[bits.OnesCount(uint(x))%2]++
}
for _, x := range b {
cnt2[bits.OnesCount(uint(x))%2]++
}
for _, x := range c {
cnt3[bits.OnesCount(uint(x))%2]++
}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
for k := 0; k < 2; k++ {
if (i+j+k)%2 == 0 {
ans += int64(cnt1[i] * cnt2[j] * cnt3[k])
}
}
}
}
return
}
|
class Solution {
public long tripletCount(int[] a, int[] b, int[] c) {
int[] cnt1 = new int[2];
int[] cnt2 = new int[2];
int[] cnt3 = new int[2];
for (int x : a) {
++cnt1[Integer.bitCount(x) & 1];
}
for (int x : b) {
++cnt2[Integer.bitCount(x) & 1];
}
for (int x : c) {
++cnt3[Integer.bitCount(x) & 1];
}
long ans = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
if ((i + j + k) % 2 == 0) {
ans += 1L * cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int:
cnt1 = Counter(x.bit_count() & 1 for x in a)
cnt2 = Counter(x.bit_count() & 1 for x in b)
cnt3 = Counter(x.bit_count() & 1 for x in c)
ans = 0
for i in range(2):
for j in range(2):
for k in range(2):
if (i + j + k) & 1 ^ 1:
ans += cnt1[i] * cnt2[j] * cnt3[k]
return ans
| null | null | null | null | null |
function tripletCount(a: number[], b: number[], c: number[]): number {
const cnt1: [number, number] = [0, 0];
const cnt2: [number, number] = [0, 0];
const cnt3: [number, number] = [0, 0];
for (const x of a) {
++cnt1[bitCount(x) & 1];
}
for (const x of b) {
++cnt2[bitCount(x) & 1];
}
for (const x of c) {
++cnt3[bitCount(x) & 1];
}
let ans = 0;
for (let i = 0; i < 2; ++i) {
for (let j = 0; j < 2; ++j) {
for (let k = 0; k < 2; ++k) {
if ((i + j + k) % 2 === 0) {
ans += cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
Divide Chocolate 🔒
|
You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array
sweetness
.
You want to share the chocolate with your
k
friends so you start cutting the chocolate bar into
k + 1
pieces using
k
cuts, each piece consists of some
consecutive
chunks.
Being generous, you will eat the piece with the
minimum total sweetness
and give the other pieces to your friends.
Find the
maximum total sweetness
of the piece you can get by cutting the chocolate bar optimally.
Example 1:
Input:
sweetness = [1,2,3,4,5,6,7,8,9], k = 5
Output:
6
Explanation:
You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
Example 2:
Input:
sweetness = [5,6,7,8,9,1,2,3,4], k = 8
Output:
1
Explanation:
There is only one way to cut the bar into 9 pieces.
Example 3:
Input:
sweetness = [1,2,2,1,2,2,1,2,2], k = 2
Output:
5
Explanation:
You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
Constraints:
0 <= k < sweetness.length <= 10
4
1 <= sweetness[i] <= 10
5
| null | null |
class Solution {
public:
int maximizeSweetness(vector<int>& sweetness, int k) {
int l = 0, r = accumulate(sweetness.begin(), sweetness.end(), 0);
auto check = [&](int x) {
int s = 0, cnt = 0;
for (int v : sweetness) {
s += v;
if (s >= x) {
s = 0;
++cnt;
}
}
return cnt > k;
};
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
};
| null | null |
func maximizeSweetness(sweetness []int, k int) int {
l, r := 0, 0
for _, v := range sweetness {
r += v
}
check := func(x int) bool {
s, cnt := 0, 0
for _, v := range sweetness {
s += v
if s >= x {
s = 0
cnt++
}
}
return cnt > k
}
for l < r {
mid := (l + r + 1) >> 1
if check(mid) {
l = mid
} else {
r = mid - 1
}
}
return l
}
|
class Solution {
public int maximizeSweetness(int[] sweetness, int k) {
int l = 0, r = 0;
for (int v : sweetness) {
r += v;
}
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(sweetness, mid, k)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
private boolean check(int[] nums, int x, int k) {
int s = 0, cnt = 0;
for (int v : nums) {
s += v;
if (s >= x) {
s = 0;
++cnt;
}
}
return cnt > k;
}
}
| null | null | null | null | null | null |
class Solution:
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
def check(x: int) -> bool:
s = cnt = 0
for v in sweetness:
s += v
if s >= x:
s = 0
cnt += 1
return cnt > k
l, r = 0, sum(sweetness)
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l
| null | null | null | null | null |
function maximizeSweetness(sweetness: number[], k: number): number {
let l = 0;
let r = sweetness.reduce((a, b) => a + b);
const check = (x: number): boolean => {
let s = 0;
let cnt = 0;
for (const v of sweetness) {
s += v;
if (s >= x) {
s = 0;
++cnt;
}
}
return cnt > k;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
|
Maximum Star Sum of a Graph
|
There is an undirected graph consisting of
n
nodes numbered from
0
to
n - 1
. You are given a
0-indexed
integer array
vals
of length
n
where
vals[i]
denotes the value of the
i
th
node.
You are also given a 2D integer array
edges
where
edges[i] = [a
i
, b
i
]
denotes that there exists an
undirected
edge connecting nodes
a
i
and
b
i.
A
star graph
is a subgraph of the given graph having a center node containing
0
or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with
3
and
4
neighbors respectively, centered at the blue node.
The
star sum
is the sum of the values of all the nodes present in the star graph.
Given an integer
k
, return
the
maximum star sum
of a star graph containing
at most
k
edges.
Example 1:
Input:
vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2
Output:
16
Explanation:
The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
Example 2:
Input:
vals = [-5], edges = [], k = 0
Output:
-5
Explanation:
There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
Constraints:
n == vals.length
1 <= n <= 10
5
-10
4
<= vals[i] <= 10
4
0 <= edges.length <= min(n * (n - 1) / 2
, 10
5
)
edges[i].length == 2
0 <= a
i
, b
i
<= n - 1
a
i
!= b
i
0 <= k <= n - 1
| null | null |
class Solution {
public:
int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) {
int n = vals.size();
vector<vector<int>> g(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
if (vals[b] > 0) g[a].emplace_back(vals[b]);
if (vals[a] > 0) g[b].emplace_back(vals[a]);
}
for (auto& e : g) sort(e.rbegin(), e.rend());
int ans = INT_MIN;
for (int i = 0; i < n; ++i) {
int v = vals[i];
for (int j = 0; j < min((int) g[i].size(), k); ++j) v += g[i][j];
ans = max(ans, v);
}
return ans;
}
};
| null | null |
func maxStarSum(vals []int, edges [][]int, k int) (ans int) {
n := len(vals)
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
if vals[b] > 0 {
g[a] = append(g[a], vals[b])
}
if vals[a] > 0 {
g[b] = append(g[b], vals[a])
}
}
for _, e := range g {
sort.Sort(sort.Reverse(sort.IntSlice(e)))
}
ans = math.MinInt32
for i, v := range vals {
for j := 0; j < min(len(g[i]), k); j++ {
v += g[i][j]
}
ans = max(ans, v)
}
return
}
|
class Solution {
public int maxStarSum(int[] vals, int[][] edges, int k) {
int n = vals.length;
List<Integer>[] g = new List[n];
Arrays.setAll(g, key -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
if (vals[b] > 0) {
g[a].add(vals[b]);
}
if (vals[a] > 0) {
g[b].add(vals[a]);
}
}
for (var e : g) {
Collections.sort(e, (a, b) -> b - a);
}
int ans = Integer.MIN_VALUE;
for (int i = 0; i < n; ++i) {
int v = vals[i];
for (int j = 0; j < Math.min(g[i].size(), k); ++j) {
v += g[i].get(j);
}
ans = Math.max(ans, v);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:
g = defaultdict(list)
for a, b in edges:
if vals[b] > 0:
g[a].append(vals[b])
if vals[a] > 0:
g[b].append(vals[a])
for bs in g.values():
bs.sort(reverse=True)
return max(v + sum(g[i][:k]) for i, v in enumerate(vals))
| null | null | null | null | null | null |
Prime Number of Set Bits in Binary Representation
|
Given two integers
left
and
right
, return
the
count
of numbers in the
inclusive
range
[left, right]
having a
prime number of set bits
in their binary representation
.
Recall that the
number of set bits
an integer has is the number of
1
's present when written in binary.
For example,
21
written in binary is
10101
, which has
3
set bits.
Example 1:
Input:
left = 6, right = 10
Output:
4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
8 -> 1000 (1 set bit, 1 is not prime)
9 -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.
Example 2:
Input:
left = 10, right = 15
Output:
5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.
Constraints:
1 <= left <= right <= 10
6
0 <= right - left <= 10
4
| null | null |
class Solution {
public:
int countPrimeSetBits(int left, int right) {
unordered_set<int> primes{2, 3, 5, 7, 11, 13, 17, 19};
int ans = 0;
for (int i = left; i <= right; ++i) ans += primes.count(__builtin_popcount(i));
return ans;
}
};
| null | null |
func countPrimeSetBits(left int, right int) (ans int) {
primes := map[int]int{}
for _, v := range []int{2, 3, 5, 7, 11, 13, 17, 19} {
primes[v] = 1
}
for i := left; i <= right; i++ {
ans += primes[bits.OnesCount(uint(i))]
}
return
}
|
class Solution {
private static Set<Integer> primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19);
public int countPrimeSetBits(int left, int right) {
int ans = 0;
for (int i = left; i <= right; ++i) {
if (primes.contains(Integer.bitCount(i))) {
++ans;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
primes = {2, 3, 5, 7, 11, 13, 17, 19}
return sum(i.bit_count() in primes for i in range(left, right + 1))
| null | null | null | null | null | null |
Number of Connected Components in an Undirected Graph 🔒
|
You have a graph of
n
nodes. You are given an integer
n
and an array
edges
where
edges[i] = [a
i
, b
i
]
indicates that there is an edge between
a
i
and
b
i
in the graph.
Return
the number of connected components in the graph
.
Example 1:
Input:
n = 5, edges = [[0,1],[1,2],[3,4]]
Output:
2
Example 2:
Input:
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output:
1
Constraints:
1 <= n <= 2000
1 <= edges.length <= 5000
edges[i].length == 2
0 <= a
i
<= b
i
< n
a
i
!= b
i
There are no repeated edges.
| null | null |
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<int> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
vector<bool> vis(n);
int ans = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) {
continue;
}
vis[i] = true;
++ans;
queue<int> q{{i}};
while (!q.empty()) {
int a = q.front();
q.pop();
for (int b : g[a]) {
if (!vis[b]) {
vis[b] = true;
q.push(b);
}
}
}
}
return ans;
}
};
| null | null |
func countComponents(n int, edges [][]int) (ans int) {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
vis := make([]bool, n)
for i := range g {
if vis[i] {
continue
}
vis[i] = true
ans++
q := []int{i}
for len(q) > 0 {
a := q[0]
q = q[1:]
for _, b := range g[a] {
if !vis[b] {
vis[b] = true
q = append(q, b)
}
}
}
}
return
}
|
class Solution {
public int countComponents(int n, int[][] edges) {
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
int ans = 0;
boolean[] vis = new boolean[n];
for (int i = 0; i < n; ++i) {
if (vis[i]) {
continue;
}
vis[i] = true;
++ans;
Deque<Integer> q = new ArrayDeque<>();
q.offer(i);
while (!q.isEmpty()) {
int a = q.poll();
for (int b : g[a]) {
if (!vis[b]) {
vis[b] = true;
q.offer(b);
}
}
}
}
return ans;
}
}
|
/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countComponents = function (n, edges) {
const g = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const vis = Array(n).fill(false);
const dfs = i => {
if (vis[i]) {
return 0;
}
vis[i] = true;
for (const j of g[i]) {
dfs(j);
}
return 1;
};
return g.reduce((acc, _, i) => acc + dfs(i), 0);
};
| null | null | null | null | null |
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = set()
ans = 0
for i in range(n):
if i in vis:
continue
vis.add(i)
q = deque([i])
while q:
a = q.popleft()
for b in g[a]:
if b not in vis:
vis.add(b)
q.append(b)
ans += 1
return ans
| null | null | null | null | null |
function countComponents(n: number, edges: number[][]): number {
const g: Map<number, number[]> = new Map(Array.from({ length: n }, (_, i) => [i, []]));
for (const [a, b] of edges) {
g.get(a)!.push(b);
g.get(b)!.push(a);
}
const vis = new Set<number>();
let ans = 0;
for (const [i] of g) {
if (vis.has(i)) {
continue;
}
const q = [i];
for (const j of q) {
if (vis.has(j)) {
continue;
}
vis.add(j);
q.push(...g.get(j)!);
}
ans++;
}
return ans;
}
|
Swap Adjacent in LR String
|
In a string composed of
'L'
,
'R'
, and
'X'
characters, like
"RXXLRXRXL"
, a move consists of either replacing one occurrence of
"XL"
with
"LX"
, or replacing one occurrence of
"RX"
with
"XR"
. Given the starting string
start
and the ending string
result
, return
True
if and only if there exists a sequence of moves to transform
start
to
result
.
Example 1:
Input:
start = "RXXLRXRXL", result = "XRLXXRRLX"
Output:
true
Explanation:
We can transform start to result following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Example 2:
Input:
start = "X", result = "L"
Output:
false
Constraints:
1 <= start.length <= 10
4
start.length == result.length
Both
start
and
result
will only consist of characters in
'L'
,
'R'
, and
'X'
.
| null | null |
class Solution {
public:
bool canTransform(string start, string end) {
int n = start.size();
int i = 0, j = 0;
while (true) {
while (i < n && start[i] == 'X') ++i;
while (j < n && end[j] == 'X') ++j;
if (i == n && j == n) return true;
if (i == n || j == n || start[i] != end[j]) return false;
if (start[i] == 'L' && i < j) return false;
if (start[i] == 'R' && i > j) return false;
++i;
++j;
}
}
};
| null | null |
func canTransform(start string, end string) bool {
n := len(start)
i, j := 0, 0
for {
for i < n && start[i] == 'X' {
i++
}
for j < n && end[j] == 'X' {
j++
}
if i == n && j == n {
return true
}
if i == n || j == n || start[i] != end[j] {
return false
}
if start[i] == 'L' && i < j {
return false
}
if start[i] == 'R' && i > j {
return false
}
i, j = i+1, j+1
}
}
|
class Solution {
public boolean canTransform(String start, String end) {
int n = start.length();
int i = 0, j = 0;
while (true) {
while (i < n && start.charAt(i) == 'X') {
++i;
}
while (j < n && end.charAt(j) == 'X') {
++j;
}
if (i == n && j == n) {
return true;
}
if (i == n || j == n || start.charAt(i) != end.charAt(j)) {
return false;
}
if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) {
return false;
}
++i;
++j;
}
}
}
| null | null | null | null | null | null |
class Solution:
def canTransform(self, start: str, end: str) -> bool:
n = len(start)
i = j = 0
while 1:
while i < n and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
if i >= n and j >= n:
return True
if i >= n or j >= n or start[i] != end[j]:
return False
if start[i] == 'L' and i < j:
return False
if start[i] == 'R' and i > j:
return False
i, j = i + 1, j + 1
| null | null | null | null | null | null |
Transpose Matrix
|
Given a 2D integer array
matrix
, return
the
transpose
of
matrix
.
The
transpose
of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1:
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input:
matrix = [[1,2,3],[4,5,6]]
Output:
[[1,4],[2,5],[3,6]]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 10
5
-10
9
<= matrix[i][j] <= 10
9
| null | null |
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> ans(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
ans[i][j] = matrix[j][i];
}
}
return ans;
}
};
| null | null |
func transpose(matrix [][]int) [][]int {
m, n := len(matrix), len(matrix[0])
ans := make([][]int, n)
for i := range ans {
ans[i] = make([]int, m)
for j := range ans[i] {
ans[i][j] = matrix[j][i]
}
}
return ans
}
|
class Solution {
public int[][] transpose(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[][] ans = new int[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
ans[i][j] = matrix[j][i];
}
}
return ans;
}
}
|
/**
* @param {number[][]} matrix
* @return {number[][]}
*/
var transpose = function (matrix) {
const [m, n] = [matrix.length, matrix[0].length];
const ans = Array.from({ length: n }, () => Array(m).fill(0));
for (let i = 0; i < n; ++i) {
for (let j = 0; j < m; ++j) {
ans[i][j] = matrix[j][i];
}
}
return ans;
};
| null | null | null | null | null |
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return list(zip(*matrix))
| null | null | null | null | null |
function transpose(matrix: number[][]): number[][] {
const [m, n] = [matrix.length, matrix[0].length];
const ans: number[][] = Array.from({ length: n }, () => Array(m).fill(0));
for (let i = 0; i < n; ++i) {
for (let j = 0; j < m; ++j) {
ans[i][j] = matrix[j][i];
}
}
return ans;
}
|
Minimum Number of Taps to Open to Water a Garden
|
There is a one-dimensional garden on the x-axis. The garden starts at the point
0
and ends at the point
n
. (i.e., the length of the garden is
n
).
There are
n + 1
taps located at points
[0, 1, ..., n]
in the garden.
Given an integer
n
and an integer array
ranges
of length
n + 1
where
ranges[i]
(0-indexed) means the
i-th
tap can water the area
[i - ranges[i], i + ranges[i]]
if it was open.
Return
the minimum number of taps
that should be open to water the whole garden, If the garden cannot be watered return
-1
.
Example 1:
Input:
n = 5, ranges = [3,4,1,1,0,0]
Output:
1
Explanation:
The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]
Example 2:
Input:
n = 3, ranges = [0,0,0,0]
Output:
-1
Explanation:
Even if you activate all the four taps you cannot water the whole garden.
Constraints:
1 <= n <= 10
4
ranges.length == n + 1
0 <= ranges[i] <= 100
| null | null |
class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
vector<int> last(n + 1);
for (int i = 0; i < n + 1; ++i) {
int l = max(0, i - ranges[i]), r = i + ranges[i];
last[l] = max(last[l], r);
}
int ans = 0, mx = 0, pre = 0;
for (int i = 0; i < n; ++i) {
mx = max(mx, last[i]);
if (mx <= i) {
return -1;
}
if (pre == i) {
++ans;
pre = mx;
}
}
return ans;
}
};
| null | null |
func minTaps(n int, ranges []int) (ans int) {
last := make([]int, n+1)
for i, x := range ranges {
l, r := max(0, i-x), i+x
last[l] = max(last[l], r)
}
var pre, mx int
for i, j := range last[:n] {
mx = max(mx, j)
if mx <= i {
return -1
}
if pre == i {
ans++
pre = mx
}
}
return
}
|
class Solution {
public int minTaps(int n, int[] ranges) {
int[] last = new int[n + 1];
for (int i = 0; i < n + 1; ++i) {
int l = Math.max(0, i - ranges[i]), r = i + ranges[i];
last[l] = Math.max(last[l], r);
}
int ans = 0, mx = 0, pre = 0;
for (int i = 0; i < n; ++i) {
mx = Math.max(mx, last[i]);
if (mx <= i) {
return -1;
}
if (pre == i) {
++ans;
pre = mx;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
last = [0] * (n + 1)
for i, x in enumerate(ranges):
l, r = max(0, i - x), i + x
last[l] = max(last[l], r)
ans = mx = pre = 0
for i in range(n):
mx = max(mx, last[i])
if mx <= i:
return -1
if pre == i:
ans += 1
pre = mx
return ans
| null |
impl Solution {
#[allow(dead_code)]
pub fn min_taps(n: i32, ranges: Vec<i32>) -> i32 {
let mut last = vec![0; (n + 1) as usize];
let mut ans = 0;
let mut mx = 0;
let mut pre = 0;
// Initialize the last vector
for (i, &r) in ranges.iter().enumerate() {
if (i as i32) - r >= 0 {
last[((i as i32) - r) as usize] =
std::cmp::max(last[((i as i32) - r) as usize], (i as i32) + r);
} else {
last[0] = std::cmp::max(last[0], (i as i32) + r);
}
}
for i in 0..n as usize {
mx = std::cmp::max(mx, last[i]);
if mx <= (i as i32) {
return -1;
}
if pre == (i as i32) {
ans += 1;
pre = mx;
}
}
ans
}
}
| null | null | null |
function minTaps(n: number, ranges: number[]): number {
const last = new Array(n + 1).fill(0);
for (let i = 0; i < n + 1; ++i) {
const l = Math.max(0, i - ranges[i]);
const r = i + ranges[i];
last[l] = Math.max(last[l], r);
}
let ans = 0;
let mx = 0;
let pre = 0;
for (let i = 0; i < n; ++i) {
mx = Math.max(mx, last[i]);
if (mx <= i) {
return -1;
}
if (pre == i) {
++ans;
pre = mx;
}
}
return ans;
}
|
Daily Temperatures
|
Given an array of integers
temperatures
represents the daily temperatures, return
an array
answer
such that
answer[i]
is the number of days you have to wait after the
i
th
day to get a warmer temperature
. If there is no future day for which this is possible, keep
answer[i] == 0
instead.
Example 1:
Input:
temperatures = [73,74,75,71,69,72,76,73]
Output:
[1,1,4,2,1,1,0,0]
Example 2:
Input:
temperatures = [30,40,50,60]
Output:
[1,1,1,0]
Example 3:
Input:
temperatures = [30,60,90]
Output:
[1,1,0]
Constraints:
1 <= temperatures.length <= 10
5
30 <= temperatures[i] <= 100
| null | null |
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
stack<int> stk;
vector<int> ans(n);
for (int i = n - 1; ~i; --i) {
while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) {
stk.pop();
}
if (!stk.empty()) {
ans[i] = stk.top() - i;
}
stk.push(i);
}
return ans;
}
};
| null | null |
func dailyTemperatures(temperatures []int) []int {
n := len(temperatures)
ans := make([]int, n)
stk := []int{}
for i := n - 1; i >= 0; i-- {
for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
ans[i] = stk[len(stk)-1] - i
}
stk = append(stk, i)
}
return ans
}
|
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
Deque<Integer> stk = new ArrayDeque<>();
int[] ans = new int[n];
for (int i = n - 1; i >= 0; --i) {
while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) {
stk.pop();
}
if (!stk.isEmpty()) {
ans[i] = stk.peek() - i;
}
stk.push(i);
}
return ans;
}
}
|
/**
* @param {number[]} temperatures
* @return {number[]}
*/
var dailyTemperatures = function (temperatures) {
const n = temperatures.length;
const ans = Array(n).fill(0);
const stk = [];
for (let i = n - 1; ~i; --i) {
while (stk.length && temperatures[stk.at(-1)] <= temperatures[i]) {
stk.pop();
}
if (stk.length) {
ans[i] = stk.at(-1) - i;
}
stk.push(i);
}
return ans;
};
| null | null | null | null | null |
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stk = []
n = len(temperatures)
ans = [0] * n
for i in range(n - 1, -1, -1):
while stk and temperatures[stk[-1]] <= temperatures[i]:
stk.pop()
if stk:
ans[i] = stk[-1] - i
stk.append(i)
return ans
| null |
impl Solution {
pub fn daily_temperatures(temperatures: Vec<i32>) -> Vec<i32> {
let n = temperatures.len();
let mut stk: Vec<usize> = Vec::new();
let mut ans = vec![0; n];
for i in (0..n).rev() {
while let Some(&top) = stk.last() {
if temperatures[top] <= temperatures[i] {
stk.pop();
} else {
break;
}
}
if let Some(&top) = stk.last() {
ans[i] = (top - i) as i32;
}
stk.push(i);
}
ans
}
}
| null | null | null |
function dailyTemperatures(temperatures: number[]): number[] {
const n = temperatures.length;
const ans: number[] = Array(n).fill(0);
const stk: number[] = [];
for (let i = n - 1; ~i; --i) {
while (stk.length && temperatures[stk.at(-1)!] <= temperatures[i]) {
stk.pop();
}
if (stk.length) {
ans[i] = stk.at(-1)! - i;
}
stk.push(i);
}
return ans;
}
|
Minimum One Bit Operations to Make Integers Zero
|
Given an integer
n
, you must transform it into
0
using the following operations any number of times:
Change the rightmost (
0
th
) bit in the binary representation of
n
.
Change the
i
th
bit in the binary representation of
n
if the
(i-1)
th
bit is set to
1
and the
(i-2)
th
through
0
th
bits are set to
0
.
Return
the minimum number of operations to transform
n
into
0
.
Example 1:
Input:
n = 3
Output:
2
Explanation:
The binary representation of 3 is "11".
"
1
1" -> "
0
1" with the 2
nd
operation since the 0
th
bit is 1.
"0
1
" -> "0
0
" with the 1
st
operation.
Example 2:
Input:
n = 6
Output:
4
Explanation:
The binary representation of 6 is "110".
"
1
10" -> "
0
10" with the 2
nd
operation since the 1
st
bit is 1 and 0
th
through 0
th
bits are 0.
"01
0
" -> "01
1
" with the 1
st
operation.
"0
1
1" -> "0
0
1" with the 2
nd
operation since the 0
th
bit is 1.
"00
1
" -> "00
0
" with the 1
st
operation.
Constraints:
0 <= n <= 10
9
| null | null |
class Solution {
public:
int minimumOneBitOperations(int n) {
if (n == 0) {
return 0;
}
return n ^ minimumOneBitOperations(n >> 1);
}
};
| null | null |
func minimumOneBitOperations(n int) int {
if n == 0 {
return 0
}
return n ^ minimumOneBitOperations(n>>1)
}
|
class Solution {
public int minimumOneBitOperations(int n) {
if (n == 0) {
return 0;
}
return n ^ minimumOneBitOperations(n >> 1);
}
}
| null | null | null | null | null | null |
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
if n == 0:
return 0
return n ^ self.minimumOneBitOperations(n >> 1)
| null | null | null | null | null |
function minimumOneBitOperations(n: number): number {
if (n === 0) {
return 0;
}
return n ^ minimumOneBitOperations(n >> 1);
}
|
Maximum Deletions on a String
|
You are given a string
s
consisting of only lowercase English letters. In one operation, you can:
Delete
the entire string
s
, or
Delete the
first
i
letters of
s
if the first
i
letters of
s
are
equal
to the following
i
letters in
s
, for any
i
in the range
1 <= i <= s.length / 2
.
For example, if
s = "ababc"
, then in one operation, you could delete the first two letters of
s
to get
"abc"
, since the first two letters of
s
and the following two letters of
s
are both equal to
"ab"
.
Return
the
maximum
number of operations needed to delete all of
s
.
Example 1:
Input:
s = "abcabcdabc"
Output:
2
Explanation:
- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
- Delete all the letters.
We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.
Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.
Example 2:
Input:
s = "aaabaab"
Output:
4
Explanation:
- Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab".
- Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab".
- Delete the first letter ("a") since the next letter is equal. Now, s = "ab".
- Delete all the letters.
We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.
Example 3:
Input:
s = "aaaaa"
Output:
5
Explanation:
In each operation, we can delete the first letter of s.
Constraints:
1 <= s.length <= 4000
s
consists only of lowercase English letters.
| null | null |
class Solution {
public:
int deleteString(string s) {
int n = s.size();
int g[n + 1][n + 1];
memset(g, 0, sizeof(g));
for (int i = n - 1; ~i; --i) {
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
g[i][j] = g[i + 1][j + 1] + 1;
}
}
}
int f[n];
for (int i = n - 1; ~i; --i) {
f[i] = 1;
for (int j = 1; j <= (n - i) / 2; ++j) {
if (g[i][i + j] >= j) {
f[i] = max(f[i], f[i + j] + 1);
}
}
}
return f[0];
}
};
| null | null |
func deleteString(s string) int {
n := len(s)
g := make([][]int, n+1)
for i := range g {
g[i] = make([]int, n+1)
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
if s[i] == s[j] {
g[i][j] = g[i+1][j+1] + 1
}
}
}
f := make([]int, n)
for i := n - 1; i >= 0; i-- {
f[i] = 1
for j := 1; j <= (n-i)/2; j++ {
if g[i][i+j] >= j {
f[i] = max(f[i], f[i+j]+1)
}
}
}
return f[0]
}
|
class Solution {
public int deleteString(String s) {
int n = s.length();
int[][] g = new int[n + 1][n + 1];
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (s.charAt(i) == s.charAt(j)) {
g[i][j] = g[i + 1][j + 1] + 1;
}
}
}
int[] f = new int[n];
for (int i = n - 1; i >= 0; --i) {
f[i] = 1;
for (int j = 1; j <= (n - i) / 2; ++j) {
if (g[i][i + j] >= j) {
f[i] = Math.max(f[i], f[i + j] + 1);
}
}
}
return f[0];
}
}
| null | null | null | null | null | null |
class Solution:
def deleteString(self, s: str) -> int:
n = len(s)
g = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
g[i][j] = g[i + 1][j + 1] + 1
f = [1] * n
for i in range(n - 1, -1, -1):
for j in range(1, (n - i) // 2 + 1):
if g[i][i + j] >= j:
f[i] = max(f[i], f[i + j] + 1)
return f[0]
| null | null | null | null | null |
function deleteString(s: string): number {
const n = s.length;
const f: number[] = new Array(n).fill(1);
for (let i = n - 1; i >= 0; --i) {
for (let j = 1; j <= (n - i) >> 1; ++j) {
if (s.slice(i, i + j) === s.slice(i + j, i + j + j)) {
f[i] = Math.max(f[i], f[i + j] + 1);
}
}
}
return f[0];
}
|
Merge Intervals
|
Given an array of
intervals
where
intervals[i] = [start
i
, end
i
]
, merge all overlapping intervals, and return
an array of the non-overlapping intervals that cover all the intervals in the input
.
Example 1:
Input:
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:
[[1,6],[8,10],[15,18]]
Explanation:
Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input:
intervals = [[1,4],[4,5]]
Output:
[[1,5]]
Explanation:
Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 10
4
intervals[i].length == 2
0 <= start
i
<= end
i
<= 10
4
| null |
public class Solution {
public int[][] Merge(int[][] intervals) {
intervals = intervals.OrderBy(a => a[0]).ToArray();
var ans = new List<int[]>();
ans.Add(intervals[0]);
for (int i = 1; i < intervals.Length; ++i) {
if (ans[ans.Count - 1][1] < intervals[i][0]) {
ans.Add(intervals[i]);
} else {
ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]);
}
}
return ans.ToArray();
}
}
|
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
ans.emplace_back(intervals[0]);
for (int i = 1; i < intervals.size(); ++i) {
if (ans.back()[1] < intervals[i][0]) {
ans.emplace_back(intervals[i]);
} else {
ans.back()[1] = max(ans.back()[1], intervals[i][1]);
}
}
return ans;
}
};
| null | null |
func merge(intervals [][]int) (ans [][]int) {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
ans = append(ans, intervals[0])
for _, e := range intervals[1:] {
if ans[len(ans)-1][1] < e[0] {
ans = append(ans, e)
} else {
ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1])
}
}
return
}
|
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> ans = new ArrayList<>();
ans.add(intervals[0]);
for (int i = 1; i < intervals.length; ++i) {
int s = intervals[i][0], e = intervals[i][1];
if (ans.get(ans.size() - 1)[1] < s) {
ans.add(intervals[i]);
} else {
ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e);
}
}
return ans.toArray(new int[ans.size()][]);
}
}
| null |
class Solution {
fun merge(intervals: Array<IntArray>): Array<IntArray> {
intervals.sortBy { it[0] }
val result = mutableListOf<IntArray>()
val n = intervals.size
var i = 0
while (i < n) {
val left = intervals[i][0]
var right = intervals[i][1]
while (true) {
i++
if (i < n && right >= intervals[i][0]) {
right = maxOf(right, intervals[i][1])
} else {
result.add(intArrayOf(left, right))
break
}
}
}
return result.toTypedArray()
}
}
| null | null | null | null |
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
ans = [intervals[0]]
for s, e in intervals[1:]:
if ans[-1][1] < s:
ans.append([s, e])
else:
ans[-1][1] = max(ans[-1][1], e)
return ans
| null |
impl Solution {
pub fn merge(mut intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0]));
let n = intervals.len();
let mut res = vec![];
let mut i = 0;
while i < n {
let l = intervals[i][0];
let mut r = intervals[i][1];
i += 1;
while i < n && r >= intervals[i][0] {
r = r.max(intervals[i][1]);
i += 1;
}
res.push(vec![l, r]);
}
res
}
}
| null | null | null |
function merge(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const n = intervals.length;
const res = [];
let i = 0;
while (i < n) {
let [l, r] = intervals[i];
i++;
while (i < n && r >= intervals[i][0]) {
r = Math.max(r, intervals[i][1]);
i++;
}
res.push([l, r]);
}
return res;
}
|
Beautiful Towers II
|
You are given a
0-indexed
array
maxHeights
of
n
integers.
You are tasked with building
n
towers in the coordinate line. The
i
th
tower is built at coordinate
i
and has a height of
heights[i]
.
A configuration of towers is
beautiful
if the following conditions hold:
1 <= heights[i] <= maxHeights[i]
heights
is a
mountain
array.
Array
heights
is a
mountain
if there exists an index
i
such that:
For all
0 < j <= i
,
heights[j - 1] <= heights[j]
For all
i <= k < n - 1
,
heights[k + 1] <= heights[k]
Return
the
maximum possible sum of heights
of a beautiful configuration of towers
.
Example 1:
Input:
maxHeights = [5,3,4,1,1]
Output:
13
Explanation:
One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since:
- 1 <= heights[i] <= maxHeights[i]
- heights is a mountain of peak i = 0.
It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.
Example 2:
Input:
maxHeights = [6,5,3,9,2,7]
Output:
22
Explanation:
One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since:
- 1 <= heights[i] <= maxHeights[i]
- heights is a mountain of peak i = 3.
It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.
Example 3:
Input:
maxHeights = [3,2,5,5,2,3]
Output:
18
Explanation:
One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since:
- 1 <= heights[i] <= maxHeights[i]
- heights is a mountain of peak i = 2.
Note that, for this configuration, i = 3 can also be considered a peak.
It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18.
Constraints:
1 <= n == maxHeights.length <= 10
5
1 <= maxHeights[i] <= 10
9
| null | null |
class Solution {
public:
long long maximumSumOfHeights(vector<int>& maxHeights) {
int n = maxHeights.size();
stack<int> stk;
vector<int> left(n, -1);
vector<int> right(n, n);
for (int i = 0; i < n; ++i) {
int x = maxHeights[i];
while (!stk.empty() && maxHeights[stk.top()] > x) {
stk.pop();
}
if (!stk.empty()) {
left[i] = stk.top();
}
stk.push(i);
}
stk = stack<int>();
for (int i = n - 1; ~i; --i) {
int x = maxHeights[i];
while (!stk.empty() && maxHeights[stk.top()] >= x) {
stk.pop();
}
if (!stk.empty()) {
right[i] = stk.top();
}
stk.push(i);
}
long long f[n], g[n];
for (int i = 0; i < n; ++i) {
int x = maxHeights[i];
if (i && x >= maxHeights[i - 1]) {
f[i] = f[i - 1] + x;
} else {
int j = left[i];
f[i] = 1LL * x * (i - j) + (j != -1 ? f[j] : 0);
}
}
for (int i = n - 1; ~i; --i) {
int x = maxHeights[i];
if (i < n - 1 && x >= maxHeights[i + 1]) {
g[i] = g[i + 1] + x;
} else {
int j = right[i];
g[i] = 1LL * x * (j - i) + (j != n ? g[j] : 0);
}
}
long long ans = 0;
for (int i = 0; i < n; ++i) {
ans = max(ans, f[i] + g[i] - maxHeights[i]);
}
return ans;
}
};
| null | null |
func maximumSumOfHeights(maxHeights []int) (ans int64) {
n := len(maxHeights)
stk := []int{}
left := make([]int, n)
right := make([]int, n)
for i := range left {
left[i] = -1
right[i] = n
}
for i, x := range maxHeights {
for len(stk) > 0 && maxHeights[stk[len(stk)-1]] > x {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
left[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
stk = []int{}
for i := n - 1; i >= 0; i-- {
x := maxHeights[i]
for len(stk) > 0 && maxHeights[stk[len(stk)-1]] >= x {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
right[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
f := make([]int64, n)
g := make([]int64, n)
for i, x := range maxHeights {
if i > 0 && x >= maxHeights[i-1] {
f[i] = f[i-1] + int64(x)
} else {
j := left[i]
f[i] = int64(x) * int64(i-j)
if j != -1 {
f[i] += f[j]
}
}
}
for i := n - 1; i >= 0; i-- {
x := maxHeights[i]
if i < n-1 && x >= maxHeights[i+1] {
g[i] = g[i+1] + int64(x)
} else {
j := right[i]
g[i] = int64(x) * int64(j-i)
if j != n {
g[i] += g[j]
}
}
}
for i, x := range maxHeights {
ans = max(ans, f[i]+g[i]-int64(x))
}
return
}
|
class Solution {
public long maximumSumOfHeights(List<Integer> maxHeights) {
int n = maxHeights.size();
Deque<Integer> stk = new ArrayDeque<>();
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, -1);
Arrays.fill(right, n);
for (int i = 0; i < n; ++i) {
int x = maxHeights.get(i);
while (!stk.isEmpty() && maxHeights.get(stk.peek()) > x) {
stk.pop();
}
if (!stk.isEmpty()) {
left[i] = stk.peek();
}
stk.push(i);
}
stk.clear();
for (int i = n - 1; i >= 0; --i) {
int x = maxHeights.get(i);
while (!stk.isEmpty() && maxHeights.get(stk.peek()) >= x) {
stk.pop();
}
if (!stk.isEmpty()) {
right[i] = stk.peek();
}
stk.push(i);
}
long[] f = new long[n];
long[] g = new long[n];
for (int i = 0; i < n; ++i) {
int x = maxHeights.get(i);
if (i > 0 && x >= maxHeights.get(i - 1)) {
f[i] = f[i - 1] + x;
} else {
int j = left[i];
f[i] = 1L * x * (i - j) + (j >= 0 ? f[j] : 0);
}
}
for (int i = n - 1; i >= 0; --i) {
int x = maxHeights.get(i);
if (i < n - 1 && x >= maxHeights.get(i + 1)) {
g[i] = g[i + 1] + x;
} else {
int j = right[i];
g[i] = 1L * x * (j - i) + (j < n ? g[j] : 0);
}
}
long ans = 0;
for (int i = 0; i < n; ++i) {
ans = Math.max(ans, f[i] + g[i] - maxHeights.get(i));
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumSumOfHeights(self, maxHeights: List[int]) -> int:
n = len(maxHeights)
stk = []
left = [-1] * n
for i, x in enumerate(maxHeights):
while stk and maxHeights[stk[-1]] > x:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
right = [n] * n
for i in range(n - 1, -1, -1):
x = maxHeights[i]
while stk and maxHeights[stk[-1]] >= x:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
f = [0] * n
for i, x in enumerate(maxHeights):
if i and x >= maxHeights[i - 1]:
f[i] = f[i - 1] + x
else:
j = left[i]
f[i] = x * (i - j) + (f[j] if j != -1 else 0)
g = [0] * n
for i in range(n - 1, -1, -1):
if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]:
g[i] = g[i + 1] + maxHeights[i]
else:
j = right[i]
g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0)
return max(a + b - c for a, b, c in zip(f, g, maxHeights))
| null | null | null | null | null |
function maximumSumOfHeights(maxHeights: number[]): number {
const n = maxHeights.length;
const stk: number[] = [];
const left: number[] = Array(n).fill(-1);
const right: number[] = Array(n).fill(n);
for (let i = 0; i < n; ++i) {
const x = maxHeights[i];
while (stk.length && maxHeights[stk.at(-1)] > x) {
stk.pop();
}
if (stk.length) {
left[i] = stk.at(-1);
}
stk.push(i);
}
stk.length = 0;
for (let i = n - 1; ~i; --i) {
const x = maxHeights[i];
while (stk.length && maxHeights[stk.at(-1)] >= x) {
stk.pop();
}
if (stk.length) {
right[i] = stk.at(-1);
}
stk.push(i);
}
const f: number[] = Array(n).fill(0);
const g: number[] = Array(n).fill(0);
for (let i = 0; i < n; ++i) {
const x = maxHeights[i];
if (i && x >= maxHeights[i - 1]) {
f[i] = f[i - 1] + x;
} else {
const j = left[i];
f[i] = x * (i - j) + (j >= 0 ? f[j] : 0);
}
}
for (let i = n - 1; ~i; --i) {
const x = maxHeights[i];
if (i + 1 < n && x >= maxHeights[i + 1]) {
g[i] = g[i + 1] + x;
} else {
const j = right[i];
g[i] = x * (j - i) + (j < n ? g[j] : 0);
}
}
let ans = 0;
for (let i = 0; i < n; ++i) {
ans = Math.max(ans, f[i] + g[i] - maxHeights[i]);
}
return ans;
}
|
Find the Longest Substring Containing Vowels in Even Counts
|
Given the string
s
, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input:
s = "eleetminicoworoep"
Output:
13
Explanation:
The longest substring is "leetminicowor" which contains two each of the vowels:
e
,
i
and
o
and zero of the vowels:
a
and
u
.
Example 2:
Input:
s = "leetcodeisgreat"
Output:
5
Explanation:
The longest substring is "leetc" which contains two e's.
Example 3:
Input:
s = "bcbcbc"
Output:
6
Explanation:
In this case, the given string "bcbcbc" is the longest because all vowels:
a
,
e
,
i
,
o
and
u
appear zero times.
Constraints:
1 <= s.length <= 5 x 10^5
s
contains only lowercase English letters.
| null | null |
class Solution {
public:
int findTheLongestSubstring(string s) {
string vowels = "aeiou";
vector<int> d(32, INT_MAX);
d[0] = 0;
int ans = 0, mask = 0;
for (int i = 1; i <= s.length(); ++i) {
char c = s[i - 1];
for (int j = 0; j < 5; ++j) {
if (c == vowels[j]) {
mask ^= 1 << j;
break;
}
}
ans = max(ans, i - d[mask]);
d[mask] = min(d[mask], i);
}
return ans;
}
};
| null | null |
func findTheLongestSubstring(s string) (ans int) {
vowels := "aeiou"
d := [32]int{}
for i := range d {
d[i] = 1 << 29
}
d[0] = 0
mask := 0
for i := 1; i <= len(s); i++ {
c := s[i-1]
for j := 0; j < 5; j++ {
if c == vowels[j] {
mask ^= 1 << j
break
}
}
ans = max(ans, i-d[mask])
d[mask] = min(d[mask], i)
}
return
}
|
class Solution {
public int findTheLongestSubstring(String s) {
String vowels = "aeiou";
int[] d = new int[32];
Arrays.fill(d, 1 << 29);
d[0] = 0;
int ans = 0, mask = 0;
for (int i = 1; i <= s.length(); ++i) {
char c = s.charAt(i - 1);
for (int j = 0; j < 5; ++j) {
if (c == vowels.charAt(j)) {
mask ^= 1 << j;
break;
}
}
ans = Math.max(ans, i - d[mask]);
d[mask] = Math.min(d[mask], i);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
d = {0: -1}
ans = mask = 0
for i, c in enumerate(s):
if c in "aeiou":
mask ^= 1 << (ord(c) - ord("a"))
if mask in d:
j = d[mask]
ans = max(ans, i - j)
else:
d[mask] = i
return ans
| null | null | null | null | null |
function findTheLongestSubstring(s: string): number {
const vowels = 'aeiou';
const d: number[] = Array(32).fill(1 << 29);
d[0] = 0;
let [ans, mask] = [0, 0];
for (let i = 1; i <= s.length; i++) {
const c = s[i - 1];
for (let j = 0; j < 5; j++) {
if (c === vowels[j]) {
mask ^= 1 << j;
break;
}
}
ans = Math.max(ans, i - d[mask]);
d[mask] = Math.min(d[mask], i);
}
return ans;
}
|
Minimum Cost Path with Alternating Directions I 🔒
|
You are given two integers
m
and
n
representing the number of rows and columns of a grid, respectively.
The cost to enter cell
(i, j)
is defined as
(i + 1) * (j + 1)
.
The path will always begin by entering cell
(0, 0)
on move 1 and paying the entrance cost.
At each step, you move to an
adjacent
cell, following an alternating pattern:
On
odd-numbered
moves, you must move either
right
or
down
.
On
even-numbered
moves, you must move either
left
or
up
.
Return the
minimum
total cost required to reach
(m - 1, n - 1)
. If it is impossible, return -1.
Example 1:
Input:
m = 1, n = 1
Output:
1
Explanation:
You start at cell
(0, 0)
.
The cost to enter
(0, 0)
is
(0 + 1) * (0 + 1) = 1
.
Since you're at the destination, the total cost is 1.
Example 2:
Input:
m = 2, n = 1
Output:
3
Explanation:
You start at cell
(0, 0)
with cost
(0 + 1) * (0 + 1) = 1
.
Move 1 (odd): You can move down to
(1, 0)
with cost
(1 + 1) * (0 + 1) = 2
.
Thus, the total cost is
1 + 2 = 3
.
Constraints:
1 <= m, n <= 10
6
| null | null |
class Solution {
public:
int minCost(int m, int n) {
if (m == 1 && n == 1) {
return 1;
}
if (m == 1 && n == 2) {
return 3;
}
if (m == 2 && n == 1) {
return 3;
}
return -1;
}
};
| null | null |
func minCost(m int, n int) int {
if m == 1 && n == 1 {
return 1
}
if m == 1 && n == 2 {
return 3
}
if m == 2 && n == 1 {
return 3
}
return -1
}
|
class Solution {
public int minCost(int m, int n) {
if (m == 1 && n == 1) {
return 1;
}
if (m == 1 && n == 2) {
return 3;
}
if (m == 2 && n == 1) {
return 3;
}
return -1;
}
}
| null | null | null | null | null | null |
class Solution:
def minCost(self, m: int, n: int) -> int:
if m == 1 and n == 1:
return 1
if m == 2 and n == 1:
return 3
if m == 1 and n == 2:
return 3
return -1
| null | null | null | null | null |
function minCost(m: number, n: number): number {
if (m === 1 && n === 1) {
return 1;
}
if (m === 1 && n === 2) {
return 3;
}
if (m === 2 && n === 1) {
return 3;
}
return -1;
}
|
Course Schedule III
|
There are
n
different online courses numbered from
1
to
n
. You are given an array
courses
where
courses[i] = [duration
i
, lastDay
i
]
indicate that the
i
th
course should be taken
continuously
for
duration
i
days and must be finished before or on
lastDay
i
.
You will start on the
1
st
day and you cannot take two or more courses simultaneously.
Return
the maximum number of courses that you can take
.
Example 1:
Input:
courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
Output:
3
Explanation:
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1
st
course, it costs 100 days so you will finish it on the 100
th
day, and ready to take the next course on the 101
st
day.
Second, take the 3
rd
course, it costs 1000 days so you will finish it on the 1100
th
day, and ready to take the next course on the 1101
st
day.
Third, take the 2
nd
course, it costs 200 days so you will finish it on the 1300
th
day.
The 4
th
course cannot be taken now, since you will finish it on the 3300
th
day, which exceeds the closed date.
Example 2:
Input:
courses = [[1,2]]
Output:
1
Example 3:
Input:
courses = [[3,2],[4,3]]
Output:
0
Constraints:
1 <= courses.length <= 10
4
1 <= duration
i
, lastDay
i
<= 10
4
| null | null |
class Solution {
public:
int scheduleCourse(vector<vector<int>>& courses) {
sort(courses.begin(), courses.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});
priority_queue<int> pq;
int s = 0;
for (auto& e : courses) {
int duration = e[0], last = e[1];
pq.push(duration);
s += duration;
while (s > last) {
s -= pq.top();
pq.pop();
}
}
return pq.size();
}
};
| null | null |
func scheduleCourse(courses [][]int) int {
sort.Slice(courses, func(i, j int) bool { return courses[i][1] < courses[j][1] })
pq := &hp{}
s := 0
for _, e := range courses {
duration, last := e[0], e[1]
s += duration
pq.push(duration)
for s > last {
s -= pq.pop()
}
}
return pq.Len()
}
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) }
|
class Solution {
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses, (a, b) -> a[1] - b[1]);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
int s = 0;
for (var e : courses) {
int duration = e[0], last = e[1];
pq.offer(duration);
s += duration;
while (s > last) {
s -= pq.poll();
}
}
return pq.size();
}
}
| null | null | null | null | null | null |
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
courses.sort(key=lambda x: x[1])
pq = []
s = 0
for duration, last in courses:
heappush(pq, -duration)
s += duration
while s > last:
s += heappop(pq)
return len(pq)
| null | null | null | null | null |
function scheduleCourse(courses: number[][]): number {
courses.sort((a, b) => a[1] - b[1]);
const pq = new MaxPriorityQueue<number>();
let s = 0;
for (const [duration, last] of courses) {
pq.enqueue(duration);
s += duration;
while (s > last) {
s -= pq.dequeue();
}
}
return pq.size();
}
|
Repeated Substring Pattern
|
Given a string
s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input:
s = "abab"
Output:
true
Explanation:
It is the substring "ab" twice.
Example 2:
Input:
s = "aba"
Output:
false
Example 3:
Input:
s = "abcabcabcabc"
Output:
true
Explanation:
It is the substring "abc" four times or the substring "abcabc" twice.
Constraints:
1 <= s.length <= 10
4
s
consists of lowercase English letters.
| null | null |
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s + s).find(s, 1) < s.size();
}
};
| null | null |
func repeatedSubstringPattern(s string) bool {
return strings.Index(s[1:]+s, s) < len(s)-1
}
|
class Solution {
public boolean repeatedSubstringPattern(String s) {
String str = s + s;
return str.substring(1, str.length() - 1).contains(s);
}
}
| null | null | null | null | null | null |
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).index(s, 1) < len(s)
| null |
impl Solution {
pub fn repeated_substring_pattern(s: String) -> bool {
(s.clone() + &s)[1..s.len() * 2 - 1].contains(&s)
}
}
| null | null | null |
function repeatedSubstringPattern(s: string): boolean {
return (s + s).slice(1, (s.length << 1) - 1).includes(s);
}
|
Number of Boomerangs
|
You are given
n
points
in the plane that are all
distinct
, where
points[i] = [x
i
, y
i
]
. A
boomerang
is a tuple of points
(i, j, k)
such that the distance between
i
and
j
equals the distance between
i
and
k
(the order of the tuple matters)
.
Return
the number of boomerangs
.
Example 1:
Input:
points = [[0,0],[1,0],[2,0]]
Output:
2
Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
Example 2:
Input:
points = [[1,1],[2,2],[3,3]]
Output:
2
Example 3:
Input:
points = [[1,1]]
Output:
0
Constraints:
n == points.length
1 <= n <= 500
points[i].length == 2
-10
4
<= x
i
, y
i
<= 10
4
All the points are
unique
.
| null | null |
class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
int ans = 0;
for (auto& p1 : points) {
unordered_map<int, int> cnt;
for (auto& p2 : points) {
int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
cnt[d]++;
}
for (auto& [_, x] : cnt) {
ans += x * (x - 1);
}
}
return ans;
}
};
| null | null |
func numberOfBoomerangs(points [][]int) (ans int) {
for _, p1 := range points {
cnt := map[int]int{}
for _, p2 := range points {
d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1])
cnt[d]++
}
for _, x := range cnt {
ans += x * (x - 1)
}
}
return
}
|
class Solution {
public int numberOfBoomerangs(int[][] points) {
int ans = 0;
for (int[] p1 : points) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int[] p2 : points) {
int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
cnt.merge(d, 1, Integer::sum);
}
for (int x : cnt.values()) {
ans += x * (x - 1);
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for p1 in points:
cnt = Counter()
for p2 in points:
d = dist(p1, p2)
cnt[d] += 1
ans += sum(x * (x - 1) for x in cnt.values())
return ans
| null | null | null | null | null |
function numberOfBoomerangs(points: number[][]): number {
let ans = 0;
for (const [x1, y1] of points) {
const cnt: Map<number, number> = new Map();
for (const [x2, y2] of points) {
const d = (x1 - x2) ** 2 + (y1 - y2) ** 2;
cnt.set(d, (cnt.get(d) || 0) + 1);
}
for (const [_, x] of cnt) {
ans += x * (x - 1);
}
}
return ans;
}
|
CEO Subordinate Hierarchy 🔒
|
Table:
Employees
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| employee_id | int |
| employee_name | varchar |
| manager_id | int |
| salary | int |
+---------------+---------+
employee_id is the unique identifier for this table.
manager_id is the employee_id of the employee's manager. The CEO has a NULL manager_id.
Write a solution to find subordinates of the CEO (both
direct
and
indirect
), along with their
level in the hierarchy
and their
salary difference
from the CEO.
The result should have the following columns:
The query result format is in the following example.
subordinate_id
: The employee_id of the subordinate
subordinate_name
: The name of the subordinate
hierarchy_level
: The level of the subordinate in the hierarchy (
1
for
direct
reports,
2
for
their direct
reports, and
so on
)
salary_difference
: The difference between the subordinate's salary and the CEO's salary
Return
the result table ordered by
hierarchy_level
ascending
,
and then by
subordinate_id
ascending
.
The query result format is in the following example.
Example:
Input:
Employees
table:
+-------------+----------------+------------+---------+
| employee_id | employee_name | manager_id | salary |
+-------------+----------------+------------+---------+
| 1 | Alice | NULL | 150000 |
| 2 | Bob | 1 | 120000 |
| 3 | Charlie | 1 | 110000 |
| 4 | David | 2 | 105000 |
| 5 | Eve | 2 | 100000 |
| 6 | Frank | 3 | 95000 |
| 7 | Grace | 3 | 98000 |
| 8 | Helen | 5 | 90000 |
+-------------+----------------+------------+---------+
Output:
+----------------+------------------+------------------+-------------------+
| subordinate_id | subordinate_name | hierarchy_level | salary_difference |
+----------------+------------------+------------------+-------------------+
| 2 | Bob | 1 | -30000 |
| 3 | Charlie | 1 | -40000 |
| 4 | David | 2 | -45000 |
| 5 | Eve | 2 | -50000 |
| 6 | Frank | 2 | -55000 |
| 7 | Grace | 2 | -52000 |
| 8 | Helen | 3 | -60000 |
+----------------+------------------+------------------+-------------------+
Explanation:
Bob and Charlie are direct subordinates of Alice (CEO) and thus have a hierarchy_level of 1.
David and Eve report to Bob, while Frank and Grace report to Charlie, making them second-level subordinates (hierarchy_level 2).
Helen reports to Eve, making Helen a third-level subordinate (hierarchy_level 3).
Salary differences are calculated relative to Alice's salary of 150000.
The result is ordered by hierarchy_level ascending, and then by subordinate_id ascending.
Note:
The output is ordered first by hierarchy_level in ascending order, then by subordinate_id in ascending order.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
WITH RECURSIVE
T AS (
SELECT
employee_id,
employee_name,
0 AS hierarchy_level,
manager_id,
salary
FROM Employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.employee_id,
e.employee_name,
hierarchy_level + 1 AS hierarchy_level,
e.manager_id,
e.salary
FROM
T t
JOIN Employees e ON t.employee_id = e.manager_id
),
P AS (
SELECT salary
FROM Employees
WHERE manager_id IS NULL
)
SELECT
employee_id subordinate_id,
employee_name subordinate_name,
hierarchy_level,
t.salary - p.salary salary_difference
FROM
T t
JOIN P p
WHERE hierarchy_level != 0
ORDER BY 3, 1;
| null | null | null | null | null | null | null | null | null | null |
Employee Free Time 🔒
|
We are given a list
schedule
of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping
Intervals
, and these intervals are in sorted order.
Return the list of finite intervals representing
common, positive-length free time
for
all
employees, also in sorted order.
(Even though we are representing
Intervals
in the form
[x, y]
, the objects inside are
Intervals
, not lists or arrays. For example,
schedule[0][0].start = 1
,
schedule[0][0].end = 2
, and
schedule[0][0][0]
is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
Example 1:
Input:
schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output:
[[3,4]]
Explanation:
There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.
Example 2:
Input:
schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output:
[[5,6],[7,9]]
Constraints:
1 <= schedule.length , schedule[i].length <= 50
0 <= schedule[i].start < schedule[i].end <= 10^8
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Minimum Cost to Reach Destination in Time
|
There is a country of
n
cities numbered from
0
to
n - 1
where
all the cities are connected
by bi-directional roads. The roads are represented as a 2D integer array
edges
where
edges[i] = [x
i
, y
i
, time
i
]
denotes a road between cities
x
i
and
y
i
that takes
time
i
minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a
0-indexed
integer array
passingFees
of length
n
where
passingFees[j]
is the amount of dollars you must pay when you pass through city
j
.
In the beginning, you are at city
0
and want to reach city
n - 1
in
maxTime
minutes or less
. The
cost
of your journey is the
summation of passing fees
for each city that you passed through at some moment of your journey (
including
the source and destination cities).
Given
maxTime
,
edges
, and
passingFees
, return
the
minimum cost
to complete your journey, or
-1
if you cannot complete it within
maxTime
minutes
.
Example 1:
Input:
maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output:
11
Explanation:
The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
Example 2:
Input:
maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output:
48
Explanation:
The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
Example 3:
Input:
maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output:
-1
Explanation:
There is no way to reach city 5 from city 0 within 25 minutes.
Constraints:
1 <= maxTime <= 1000
n == passingFees.length
2 <= n <= 1000
n - 1 <= edges.length <= 1000
0 <= x
i
, y
i
<= n - 1
1 <= time
i
<= 1000
1 <= passingFees[j] <= 1000
The graph may contain multiple edges between two nodes.
The graph does not contain self loops.
| null | null |
class Solution {
public:
int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) {
int m = maxTime, n = passingFees.size();
const int inf = 1 << 30;
vector<vector<int>> f(m + 1, vector<int>(n, inf));
f[0][0] = passingFees[0];
for (int i = 1; i <= m; ++i) {
for (const auto& e : edges) {
int x = e[0], y = e[1], t = e[2];
if (t <= i) {
f[i][x] = min(f[i][x], f[i - t][y] + passingFees[x]);
f[i][y] = min(f[i][y], f[i - t][x] + passingFees[y]);
}
}
}
int ans = inf;
for (int i = 1; i <= m; ++i) {
ans = min(ans, f[i][n - 1]);
}
return ans == inf ? -1 : ans;
}
};
| null | null |
func minCost(maxTime int, edges [][]int, passingFees []int) int {
m, n := maxTime, len(passingFees)
f := make([][]int, m+1)
const inf int = 1 << 30
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = inf
}
}
f[0][0] = passingFees[0]
for i := 1; i <= m; i++ {
for _, e := range edges {
x, y, t := e[0], e[1], e[2]
if t <= i {
f[i][x] = min(f[i][x], f[i-t][y]+passingFees[x])
f[i][y] = min(f[i][y], f[i-t][x]+passingFees[y])
}
}
}
ans := inf
for i := 1; i <= m; i++ {
ans = min(ans, f[i][n-1])
}
if ans == inf {
return -1
}
return ans
}
|
class Solution {
public int minCost(int maxTime, int[][] edges, int[] passingFees) {
int m = maxTime, n = passingFees.length;
int[][] f = new int[m + 1][n];
final int inf = 1 << 30;
for (var g : f) {
Arrays.fill(g, inf);
}
f[0][0] = passingFees[0];
for (int i = 1; i <= m; ++i) {
for (var e : edges) {
int x = e[0], y = e[1], t = e[2];
if (t <= i) {
f[i][x] = Math.min(f[i][x], f[i - t][y] + passingFees[x]);
f[i][y] = Math.min(f[i][y], f[i - t][x] + passingFees[y]);
}
}
}
int ans = inf;
for (int i = 0; i <= m; ++i) {
ans = Math.min(ans, f[i][n - 1]);
}
return ans == inf ? -1 : ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minCost(
self, maxTime: int, edges: List[List[int]], passingFees: List[int]
) -> int:
m, n = maxTime, len(passingFees)
f = [[inf] * n for _ in range(m + 1)]
f[0][0] = passingFees[0]
for i in range(1, m + 1):
for x, y, t in edges:
if t <= i:
f[i][x] = min(f[i][x], f[i - t][y] + passingFees[x])
f[i][y] = min(f[i][y], f[i - t][x] + passingFees[y])
ans = min(f[i][n - 1] for i in range(m + 1))
return ans if ans < inf else -1
| null | null | null | null | null |
function minCost(maxTime: number, edges: number[][], passingFees: number[]): number {
const [m, n] = [maxTime, passingFees.length];
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n).fill(Infinity));
f[0][0] = passingFees[0];
for (let i = 1; i <= m; ++i) {
for (const [x, y, t] of edges) {
if (t <= i) {
f[i][x] = Math.min(f[i][x], f[i - t][y] + passingFees[x]);
f[i][y] = Math.min(f[i][y], f[i - t][x] + passingFees[y]);
}
}
}
let ans = Infinity;
for (let i = 1; i <= m; ++i) {
ans = Math.min(ans, f[i][n - 1]);
}
return ans === Infinity ? -1 : ans;
}
|
Maximize Sum Of Array After K Negations
|
Given an integer array
nums
and an integer
k
, modify the array in the following way:
choose an index
i
and replace
nums[i]
with
-nums[i]
.
You should apply this process exactly
k
times. You may choose the same index
i
multiple times.
Return
the largest possible sum of the array after modifying it in this way
.
Example 1:
Input:
nums = [4,2,3], k = 1
Output:
5
Explanation:
Choose index 1 and nums becomes [4,-2,3].
Example 2:
Input:
nums = [3,-1,0,2], k = 3
Output:
6
Explanation:
Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
Input:
nums = [2,-3,-1,5,-4], k = 2
Output:
13
Explanation:
Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Constraints:
1 <= nums.length <= 10
4
-100 <= nums[i] <= 100
1 <= k <= 10
4
| null | null |
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
for (int& x : nums) {
++cnt[x];
}
for (int x = -100; x < 0 && k > 0; ++x) {
if (cnt[x]) {
int m = min(cnt[x], k);
cnt[x] -= m;
cnt[-x] += m;
k -= m;
}
}
if ((k & 1) && !cnt[0]) {
for (int x = 1; x <= 100; ++x) {
if (cnt[x]) {
--cnt[x];
++cnt[-x];
break;
}
}
}
int ans = 0;
for (auto& [x, v] : cnt) {
ans += x * v;
}
return ans;
}
};
| null | null |
func largestSumAfterKNegations(nums []int, k int) (ans int) {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
for x := -100; x < 0 && k > 0; x++ {
if cnt[x] > 0 {
m := min(k, cnt[x])
cnt[x] -= m
cnt[-x] += m
k -= m
}
}
if k&1 == 1 && cnt[0] == 0 {
for x := 1; x <= 100; x++ {
if cnt[x] > 0 {
cnt[x]--
cnt[-x]++
break
}
}
}
for x, v := range cnt {
ans += x * v
}
return
}
|
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
for (int x = -100; x < 0 && k > 0; ++x) {
if (cnt.getOrDefault(x, 0) > 0) {
int m = Math.min(cnt.get(x), k);
cnt.merge(x, -m, Integer::sum);
cnt.merge(-x, m, Integer::sum);
k -= m;
}
}
if ((k & 1) == 1 && cnt.getOrDefault(0, 0) == 0) {
for (int x = 1; x <= 100; ++x) {
if (cnt.getOrDefault(x, 0) > 0) {
cnt.merge(x, -1, Integer::sum);
cnt.merge(-x, 1, Integer::sum);
break;
}
}
}
int ans = 0;
for (var e : cnt.entrySet()) {
ans += e.getKey() * e.getValue();
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
cnt = Counter(nums)
for x in range(-100, 0):
if cnt[x]:
m = min(cnt[x], k)
cnt[x] -= m
cnt[-x] += m
k -= m
if k == 0:
break
if k & 1 and cnt[0] == 0:
for x in range(1, 101):
if cnt[x]:
cnt[x] -= 1
cnt[-x] += 1
break
return sum(x * v for x, v in cnt.items())
| null | null | null | null | null |
function largestSumAfterKNegations(nums: number[], k: number): number {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
for (let x = -100; x < 0 && k > 0; ++x) {
if (cnt.get(x)! > 0) {
const m = Math.min(cnt.get(x) || 0, k);
cnt.set(x, (cnt.get(x) || 0) - m);
cnt.set(-x, (cnt.get(-x) || 0) + m);
k -= m;
}
}
if ((k & 1) === 1 && (cnt.get(0) || 0) === 0) {
for (let x = 1; x <= 100; ++x) {
if (cnt.get(x)! > 0) {
cnt.set(x, (cnt.get(x) || 0) - 1);
cnt.set(-x, (cnt.get(-x) || 0) + 1);
break;
}
}
}
return Array.from(cnt.entries()).reduce((acc, [k, v]) => acc + k * v, 0);
}
|
Substrings That Begin and End With the Same Letter 🔒
|
You are given a
0-indexed
string
s
consisting of only lowercase English letters. Return
the number of
substrings
in
s
that begin and end with the
same
character.
A
substring
is a contiguous non-empty sequence of characters within a string.
Example 1:
Input:
s = "abcba"
Output:
7
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "c", "b", and "a".
The substring of length 3 that starts and ends with the same letter is: "bcb".
The substring of length 5 that starts and ends with the same letter is: "abcba".
Example 2:
Input:
s = "abacad"
Output:
9
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "a", "c", "a", and "d".
The substrings of length 3 that start and end with the same letter are: "aba" and "aca".
The substring of length 5 that starts and ends with the same letter is: "abaca".
Example 3:
Input:
s = "a"
Output:
1
Explanation:
The substring of length 1 that starts and ends with the same letter is: "a".
Constraints:
1 <= s.length <= 10
5
s
consists only of lowercase English letters.
| null | null |
class Solution {
public:
long long numberOfSubstrings(string s) {
int cnt[26]{};
long long ans = 0;
for (char& c : s) {
ans += ++cnt[c - 'a'];
}
return ans;
}
};
| null | null |
func numberOfSubstrings(s string) (ans int64) {
cnt := [26]int{}
for _, c := range s {
c -= 'a'
cnt[c]++
ans += int64(cnt[c])
}
return ans
}
|
class Solution {
public long numberOfSubstrings(String s) {
int[] cnt = new int[26];
long ans = 0;
for (char c : s.toCharArray()) {
ans += ++cnt[c - 'a'];
}
return ans;
}
}
|
/**
* @param {string} s
* @return {number}
*/
var numberOfSubstrings = function (s) {
const cnt = {};
let ans = 0;
for (const c of s) {
cnt[c] = (cnt[c] || 0) + 1;
ans += cnt[c];
}
return ans;
};
| null | null | null | null | null |
class Solution:
def numberOfSubstrings(self, s: str) -> int:
cnt = Counter()
ans = 0
for c in s:
cnt[c] += 1
ans += cnt[c]
return ans
| null |
impl Solution {
pub fn number_of_substrings(s: String) -> i64 {
let mut cnt = [0; 26];
let mut ans = 0_i64;
for c in s.chars() {
let idx = (c as u8 - b'a') as usize;
cnt[idx] += 1;
ans += cnt[idx];
}
ans
}
}
| null | null | null |
function numberOfSubstrings(s: string): number {
const cnt: Record<string, number> = {};
let ans = 0;
for (const c of s) {
cnt[c] = (cnt[c] || 0) + 1;
ans += cnt[c];
}
return ans;
}
|
Longest Special Path II
|
You are given an undirected tree rooted at node
0
, with
n
nodes numbered from
0
to
n - 1
. This is represented by a 2D array
edges
of length
n - 1
, where
edges[i] = [u
i
, v
i
, length
i
]
indicates an edge between nodes
u
i
and
v
i
with length
length
i
. You are also given an integer array
nums
, where
nums[i]
represents the value at node
i
.
A
special path
is defined as a
downward
path from an ancestor node to a descendant node in which all node values are
distinct
, except for
at most
one value that may appear twice.
Return an array
result
of size 2, where
result[0]
is the
length
of the
longest
special path, and
result[1]
is the
minimum
number of nodes in all
possible
longest
special paths.
Example 1:
Input:
edges = [[0,1,1],[1,2,3],[1,3,1],[2,4,6],[4,7,2],[3,5,2],[3,6,5],[6,8,3]], nums = [1,1,0,3,1,2,1,1,0]
Output:
[9,3]
Explanation:
In the image below, nodes are colored by their corresponding values in
nums
.
The longest special paths are
1 -> 2 -> 4
and
1 -> 3 -> 6 -> 8
, both having a length of 9. The minimum number of nodes across all longest special paths is 3.
Example 2:
Input:
edges = [[1,0,3],[0,2,4],[0,3,5]], nums = [1,1,0,2]
Output:
[5,2]
Explanation:
The longest path is
0 -> 3
consisting of 2 nodes with a length of 5.
Constraints:
2 <= n <= 5 * 10
4
edges.length == n - 1
edges[i].length == 3
0 <= u
i
, v
i
< n
1 <= length
i
<= 10
3
nums.length == n
0 <= nums[i] <= 5 * 10
4
The input is generated such that
edges
represents a valid tree.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Maximum Sum of Subsequence With Non-adjacent Elements
|
You are given an array
nums
consisting of integers. You are also given a 2D array
queries
, where
queries[i] = [pos
i
, x
i
]
.
For query
i
, we first set
nums[pos
i
]
equal to
x
i
, then we calculate the answer to query
i
which is the
maximum
sum of a
subsequence
of
nums
where
no two adjacent elements are selected
.
Return the
sum
of the answers to all queries.
Since the final answer may be very large, return it
modulo
10
9
+ 7
.
A
subsequence
is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input:
nums = [3,5,9], queries = [[1,-2],[0,-3]]
Output:
21
Explanation:
After the 1
st
query,
nums = [3,-2,9]
and the maximum sum of a subsequence with non-adjacent elements is
3 + 9 = 12
.
After the 2
nd
query,
nums = [-3,-2,9]
and the maximum sum of a subsequence with non-adjacent elements is 9.
Example 2:
Input:
nums = [0,-1], queries = [[0,-5]]
Output:
0
Explanation:
After the 1
st
query,
nums = [-5,-1]
and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).
Constraints:
1 <= nums.length <= 5 * 10
4
-10
5
<= nums[i] <= 10
5
1 <= queries.length <= 5 * 10
4
queries[i] == [pos
i
, x
i
]
0 <= pos
i
<= nums.length - 1
-10
5
<= x
i
<= 10
5
| null | null |
class Node {
public:
int l, r;
long long s00, s01, s10, s11;
Node(int l, int r)
: l(l)
, r(r)
, s00(0)
, s01(0)
, s10(0)
, s11(0) {}
};
class SegmentTree {
public:
vector<Node*> tr;
SegmentTree(int n)
: tr(n << 2) {
build(1, 1, n);
}
void build(int u, int l, int r) {
tr[u] = new Node(l, r);
if (l == r) {
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
long long query(int u, int l, int r) {
if (tr[u]->l >= l && tr[u]->r <= r) {
return tr[u]->s11;
}
int mid = (tr[u]->l + tr[u]->r) >> 1;
long long ans = 0;
if (r <= mid) {
ans = query(u << 1, l, r);
}
if (l > mid) {
ans = max(ans, query(u << 1 | 1, l, r));
}
return ans;
}
void pushup(int u) {
Node* left = tr[u << 1];
Node* right = tr[u << 1 | 1];
tr[u]->s00 = max(left->s00 + right->s10, left->s01 + right->s00);
tr[u]->s01 = max(left->s00 + right->s11, left->s01 + right->s01);
tr[u]->s10 = max(left->s10 + right->s10, left->s11 + right->s00);
tr[u]->s11 = max(left->s10 + right->s11, left->s11 + right->s01);
}
void modify(int u, int x, int v) {
if (tr[u]->l == tr[u]->r) {
tr[u]->s11 = max(0LL, (long long) v);
return;
}
int mid = (tr[u]->l + tr[u]->r) >> 1;
if (x <= mid) {
modify(u << 1, x, v);
} else {
modify(u << 1 | 1, x, v);
}
pushup(u);
}
~SegmentTree() {
for (auto node : tr) {
delete node;
}
}
};
class Solution {
public:
int maximumSumSubsequence(vector<int>& nums, vector<vector<int>>& queries) {
int n = nums.size();
SegmentTree tree(n);
for (int i = 0; i < n; ++i) {
tree.modify(1, i + 1, nums[i]);
}
long long ans = 0;
const int mod = 1e9 + 7;
for (const auto& q : queries) {
tree.modify(1, q[0] + 1, q[1]);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return (int) ans;
}
};
| null | null |
type Node struct {
l, r int
s00, s01, s10, s11 int
}
func NewNode(l, r int) *Node {
return &Node{l: l, r: r, s00: 0, s01: 0, s10: 0, s11: 0}
}
type SegmentTree struct {
tr []*Node
}
func NewSegmentTree(n int) *SegmentTree {
tr := make([]*Node, n*4)
tree := &SegmentTree{tr: tr}
tree.build(1, 1, n)
return tree
}
func (st *SegmentTree) build(u, l, r int) {
st.tr[u] = NewNode(l, r)
if l == r {
return
}
mid := (l + r) >> 1
st.build(u<<1, l, mid)
st.build(u<<1|1, mid+1, r)
}
func (st *SegmentTree) query(u, l, r int) int {
if st.tr[u].l >= l && st.tr[u].r <= r {
return st.tr[u].s11
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
ans := 0
if r <= mid {
ans = st.query(u<<1, l, r)
}
if l > mid {
ans = max(ans, st.query(u<<1|1, l, r))
}
return ans
}
func (st *SegmentTree) pushup(u int) {
left := st.tr[u<<1]
right := st.tr[u<<1|1]
st.tr[u].s00 = max(left.s00+right.s10, left.s01+right.s00)
st.tr[u].s01 = max(left.s00+right.s11, left.s01+right.s01)
st.tr[u].s10 = max(left.s10+right.s10, left.s11+right.s00)
st.tr[u].s11 = max(left.s10+right.s11, left.s11+right.s01)
}
func (st *SegmentTree) modify(u, x, v int) {
if st.tr[u].l == st.tr[u].r {
st.tr[u].s11 = max(0, v)
return
}
mid := (st.tr[u].l + st.tr[u].r) >> 1
if x <= mid {
st.modify(u<<1, x, v)
} else {
st.modify(u<<1|1, x, v)
}
st.pushup(u)
}
func maximumSumSubsequence(nums []int, queries [][]int) (ans int) {
n := len(nums)
tree := NewSegmentTree(n)
for i, x := range nums {
tree.modify(1, i+1, x)
}
const mod int = 1e9 + 7
for _, q := range queries {
tree.modify(1, q[0]+1, q[1])
ans = (ans + tree.query(1, 1, n)) % mod
}
return
}
|
class Node {
int l, r;
long s00, s01, s10, s11;
Node(int l, int r) {
this.l = l;
this.r = r;
this.s00 = this.s01 = this.s10 = this.s11 = 0;
}
}
class SegmentTree {
Node[] tr;
SegmentTree(int n) {
tr = new Node[n * 4];
build(1, 1, n);
}
void build(int u, int l, int r) {
tr[u] = new Node(l, r);
if (l == r) {
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
long query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
return tr[u].s11;
}
int mid = (tr[u].l + tr[u].r) >> 1;
long ans = 0;
if (r <= mid) {
ans = query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, query(u << 1 | 1, l, r));
}
return ans;
}
void pushup(int u) {
Node left = tr[u << 1];
Node right = tr[u << 1 | 1];
tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
void modify(int u, int x, int v) {
if (tr[u].l == tr[u].r) {
tr[u].s11 = Math.max(0, v);
return;
}
int mid = (tr[u].l + tr[u].r) >> 1;
if (x <= mid) {
modify(u << 1, x, v);
} else {
modify(u << 1 | 1, x, v);
}
pushup(u);
}
}
class Solution {
public int maximumSumSubsequence(int[] nums, int[][] queries) {
int n = nums.length;
SegmentTree tree = new SegmentTree(n);
for (int i = 0; i < n; ++i) {
tree.modify(1, i + 1, nums[i]);
}
long ans = 0;
final int mod = (int) 1e9 + 7;
for (int[] q : queries) {
tree.modify(1, q[0] + 1, q[1]);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return (int) ans;
}
}
| null | null | null | null | null | null |
def max(a: int, b: int) -> int:
return a if a > b else b
class Node:
__slots__ = "l", "r", "s00", "s01", "s10", "s11"
def __init__(self, l: int, r: int):
self.l = l
self.r = r
self.s00 = self.s01 = self.s10 = self.s11 = 0
class SegmentTree:
__slots__ = "tr"
def __init__(self, n: int):
self.tr: List[Node | None] = [None] * (n << 2)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
mid = (l + r) >> 1
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
def query(self, u: int, l: int, r: int) -> int:
if self.tr[u].l >= l and self.tr[u].r <= r:
return self.tr[u].s11
mid = (self.tr[u].l + self.tr[u].r) >> 1
ans = 0
if r <= mid:
ans = self.query(u << 1, l, r)
if l > mid:
ans = max(ans, self.query(u << 1 | 1, l, r))
return ans
def pushup(self, u: int):
left, right = self.tr[u << 1], self.tr[u << 1 | 1]
self.tr[u].s00 = max(left.s00 + right.s10, left.s01 + right.s00)
self.tr[u].s01 = max(left.s00 + right.s11, left.s01 + right.s01)
self.tr[u].s10 = max(left.s10 + right.s10, left.s11 + right.s00)
self.tr[u].s11 = max(left.s10 + right.s11, left.s11 + right.s01)
def modify(self, u: int, x: int, v: int):
if self.tr[u].l == self.tr[u].r:
self.tr[u].s11 = max(0, v)
return
mid = (self.tr[u].l + self.tr[u].r) >> 1
if x <= mid:
self.modify(u << 1, x, v)
else:
self.modify(u << 1 | 1, x, v)
self.pushup(u)
class Solution:
def maximumSumSubsequence(self, nums: List[int], queries: List[List[int]]) -> int:
n = len(nums)
tree = SegmentTree(n)
for i, x in enumerate(nums, 1):
tree.modify(1, i, x)
ans = 0
mod = 10**9 + 7
for i, x in queries:
tree.modify(1, i + 1, x)
ans = (ans + tree.query(1, 1, n)) % mod
return ans
| null | null | null | null | null |
class Node {
s00 = 0;
s01 = 0;
s10 = 0;
s11 = 0;
constructor(
public l: number,
public r: number,
) {}
}
class SegmentTree {
tr: Node[];
constructor(n: number) {
this.tr = Array(n * 4);
this.build(1, 1, n);
}
build(u: number, l: number, r: number) {
this.tr[u] = new Node(l, r);
if (l === r) {
return;
}
const mid = (l + r) >> 1;
this.build(u << 1, l, mid);
this.build((u << 1) | 1, mid + 1, r);
}
query(u: number, l: number, r: number): number {
if (this.tr[u].l >= l && this.tr[u].r <= r) {
return this.tr[u].s11;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
let ans = 0;
if (r <= mid) {
ans = this.query(u << 1, l, r);
}
if (l > mid) {
ans = Math.max(ans, this.query((u << 1) | 1, l, r));
}
return ans;
}
pushup(u: number) {
const left = this.tr[u << 1];
const right = this.tr[(u << 1) | 1];
this.tr[u].s00 = Math.max(left.s00 + right.s10, left.s01 + right.s00);
this.tr[u].s01 = Math.max(left.s00 + right.s11, left.s01 + right.s01);
this.tr[u].s10 = Math.max(left.s10 + right.s10, left.s11 + right.s00);
this.tr[u].s11 = Math.max(left.s10 + right.s11, left.s11 + right.s01);
}
modify(u: number, x: number, v: number) {
if (this.tr[u].l === this.tr[u].r) {
this.tr[u].s11 = Math.max(0, v);
return;
}
const mid = (this.tr[u].l + this.tr[u].r) >> 1;
if (x <= mid) {
this.modify(u << 1, x, v);
} else {
this.modify((u << 1) | 1, x, v);
}
this.pushup(u);
}
}
function maximumSumSubsequence(nums: number[], queries: number[][]): number {
const n = nums.length;
const tree = new SegmentTree(n);
for (let i = 0; i < n; i++) {
tree.modify(1, i + 1, nums[i]);
}
let ans = 0;
const mod = 1e9 + 7;
for (const [i, x] of queries) {
tree.modify(1, i + 1, x);
ans = (ans + tree.query(1, 1, n)) % mod;
}
return ans;
}
|
Weather Type in Each Country 🔒
|
Table:
Countries
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| country_id | int |
| country_name | varchar |
+---------------+---------+
country_id is the primary key (column with unique values) for this table.
Each row of this table contains the ID and the name of one country.
Table:
Weather
+---------------+------+
| Column Name | Type |
+---------------+------+
| country_id | int |
| weather_state | int |
| day | date |
+---------------+------+
(country_id, day) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the weather state in a country for one day.
Write a solution to find the type of weather in each country for
November 2019
.
The type of weather is:
Cold
if the average
weather_state
is less than or equal
15
,
Hot
if the average
weather_state
is greater than or equal to
25
, and
Warm
otherwise.
Return the result table in
any order
.
The result format is in the following example.
Example 1:
Input:
Countries table:
+------------+--------------+
| country_id | country_name |
+------------+--------------+
| 2 | USA |
| 3 | Australia |
| 7 | Peru |
| 5 | China |
| 8 | Morocco |
| 9 | Spain |
+------------+--------------+
Weather table:
+------------+---------------+------------+
| country_id | weather_state | day |
+------------+---------------+------------+
| 2 | 15 | 2019-11-01 |
| 2 | 12 | 2019-10-28 |
| 2 | 12 | 2019-10-27 |
| 3 | -2 | 2019-11-10 |
| 3 | 0 | 2019-11-11 |
| 3 | 3 | 2019-11-12 |
| 5 | 16 | 2019-11-07 |
| 5 | 18 | 2019-11-09 |
| 5 | 21 | 2019-11-23 |
| 7 | 25 | 2019-11-28 |
| 7 | 22 | 2019-12-01 |
| 7 | 20 | 2019-12-02 |
| 8 | 25 | 2019-11-05 |
| 8 | 27 | 2019-11-15 |
| 8 | 31 | 2019-11-25 |
| 9 | 7 | 2019-10-23 |
| 9 | 3 | 2019-12-23 |
+------------+---------------+------------+
Output:
+--------------+--------------+
| country_name | weather_type |
+--------------+--------------+
| USA | Cold |
| Australia | Cold |
| Peru | Hot |
| Morocco | Hot |
| China | Warm |
+--------------+--------------+
Explanation:
Average weather_state in USA in November is (15) / 1 = 15 so weather type is Cold.
Average weather_state in Austraila in November is (-2 + 0 + 3) / 3 = 0.333 so weather type is Cold.
Average weather_state in Peru in November is (25) / 1 = 25 so the weather type is Hot.
Average weather_state in China in November is (16 + 18 + 21) / 3 = 18.333 so weather type is Warm.
Average weather_state in Morocco in November is (25 + 27 + 31) / 3 = 27.667 so weather type is Hot.
We know nothing about the average weather_state in Spain in November so we do not include it in the result table.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
SELECT
country_name,
CASE
WHEN AVG(weather_state) <= 15 THEN 'Cold'
WHEN AVG(weather_state) >= 25 THEN 'Hot'
ELSE 'Warm'
END AS weather_type
FROM
Weather AS w
JOIN Countries USING (country_id)
WHERE DATE_FORMAT(day, '%Y-%m') = '2019-11'
GROUP BY 1;
| null | null | null | null | null | null | null | null | null | null |
Most Expensive Item That Can Not Be Bought 🔒
|
You are given two
distinct
prime
numbers
primeOne
and
primeTwo
.
Alice and Bob are visiting a market. The market has an
infinite
number of items, for
any
positive integer
x
there exists an item whose price is
x
. Alice wants to buy some items from the market to gift to Bob. She has an
infinite
number of coins in the denomination
primeOne
and
primeTwo
. She wants to know the
most expensive
item she can
not
buy to gift to Bob.
Return
the price of the
most expensive
item which Alice can not gift to Bob
.
Example 1:
Input:
primeOne = 2, primeTwo = 5
Output:
3
Explanation:
The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5.
Example 2:
Input:
primeOne = 5, primeTwo = 7
Output:
23
Explanation:
The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought.
Constraints:
1 < primeOne, primeTwo < 10
4
primeOne
,
primeTwo
are prime numbers.
primeOne * primeTwo < 10
5
| null | null |
class Solution {
public:
int mostExpensiveItem(int primeOne, int primeTwo) {
return primeOne * primeTwo - primeOne - primeTwo;
}
};
| null | null |
func mostExpensiveItem(primeOne int, primeTwo int) int {
return primeOne*primeTwo - primeOne - primeTwo
}
|
class Solution {
public int mostExpensiveItem(int primeOne, int primeTwo) {
return primeOne * primeTwo - primeOne - primeTwo;
}
}
| null | null | null | null | null | null |
class Solution:
def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int:
return primeOne * primeTwo - primeOne - primeTwo
| null |
impl Solution {
pub fn most_expensive_item(prime_one: i32, prime_two: i32) -> i32 {
prime_one * prime_two - prime_one - prime_two
}
}
| null | null | null |
function mostExpensiveItem(primeOne: number, primeTwo: number): number {
return primeOne * primeTwo - primeOne - primeTwo;
}
|
Interval List Intersections
|
You are given two lists of closed intervals,
firstList
and
secondList
, where
firstList[i] = [start
i
, end
i
]
and
secondList[j] = [start
j
, end
j
]
. Each list of intervals is pairwise
disjoint
and in
sorted order
.
Return
the intersection of these two interval lists
.
A
closed interval
[a, b]
(with
a <= b
) denotes the set of real numbers
x
with
a <= x <= b
.
The
intersection
of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of
[1, 3]
and
[2, 4]
is
[2, 3]
.
Example 1:
Input:
firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output:
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Example 2:
Input:
firstList = [[1,3],[5,9]], secondList = []
Output:
[]
Constraints:
0 <= firstList.length, secondList.length <= 1000
firstList.length + secondList.length >= 1
0 <= start
i
< end
i
<= 10
9
end
i
< start
i+1
0 <= start
j
< end
j
<= 10
9
end
j
< start
j+1
| null | null |
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
vector<vector<int>> ans;
int m = firstList.size(), n = secondList.size();
for (int i = 0, j = 0; i < m && j < n;) {
int l = max(firstList[i][0], secondList[j][0]);
int r = min(firstList[i][1], secondList[j][1]);
if (l <= r) ans.push_back({l, r});
if (firstList[i][1] < secondList[j][1])
++i;
else
++j;
}
return ans;
}
};
| null | null |
func intervalIntersection(firstList [][]int, secondList [][]int) [][]int {
m, n := len(firstList), len(secondList)
var ans [][]int
for i, j := 0, 0; i < m && j < n; {
l := max(firstList[i][0], secondList[j][0])
r := min(firstList[i][1], secondList[j][1])
if l <= r {
ans = append(ans, []int{l, r})
}
if firstList[i][1] < secondList[j][1] {
i++
} else {
j++
}
}
return ans
}
|
class Solution {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
List<int[]> ans = new ArrayList<>();
int m = firstList.length, n = secondList.length;
for (int i = 0, j = 0; i < m && j < n;) {
int l = Math.max(firstList[i][0], secondList[j][0]);
int r = Math.min(firstList[i][1], secondList[j][1]);
if (l <= r) {
ans.add(new int[] {l, r});
}
if (firstList[i][1] < secondList[j][1]) {
++i;
} else {
++j;
}
}
return ans.toArray(new int[ans.size()][]);
}
}
| null | null | null | null | null | null |
class Solution:
def intervalIntersection(
self, firstList: List[List[int]], secondList: List[List[int]]
) -> List[List[int]]:
i = j = 0
ans = []
while i < len(firstList) and j < len(secondList):
s1, e1, s2, e2 = *firstList[i], *secondList[j]
l, r = max(s1, s2), min(e1, e2)
if l <= r:
ans.append([l, r])
if e1 < e2:
i += 1
else:
j += 1
return ans
| null |
impl Solution {
pub fn interval_intersection(
first_list: Vec<Vec<i32>>,
second_list: Vec<Vec<i32>>,
) -> Vec<Vec<i32>> {
let n = first_list.len();
let m = second_list.len();
let mut res = Vec::new();
let (mut i, mut j) = (0, 0);
while i < n && j < m {
let start = first_list[i][0].max(second_list[j][0]);
let end = first_list[i][1].min(second_list[j][1]);
if start <= end {
res.push(vec![start, end]);
}
if first_list[i][1] < second_list[j][1] {
i += 1;
} else {
j += 1;
}
}
res
}
}
| null | null | null |
function intervalIntersection(firstList: number[][], secondList: number[][]): number[][] {
const n = firstList.length;
const m = secondList.length;
const res = [];
let i = 0;
let j = 0;
while (i < n && j < m) {
const start = Math.max(firstList[i][0], secondList[j][0]);
const end = Math.min(firstList[i][1], secondList[j][1]);
if (start <= end) {
res.push([start, end]);
}
if (firstList[i][1] < secondList[j][1]) {
i++;
} else {
j++;
}
}
return res;
}
|
Palindrome Removal 🔒
|
You are given an integer array
arr
.
In one move, you can select a
palindromic
subarray
arr[i], arr[i + 1], ..., arr[j]
where
i <= j
, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal.
Return
the minimum number of moves needed to remove all numbers from the array
.
Example 1:
Input:
arr = [1,2]
Output:
2
Example 2:
Input:
arr = [1,3,4,1,5]
Output:
3
Explanation:
Remove [4] then remove [1,3,1] then remove [5].
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 20
| null | null |
class Solution {
public:
int minimumMoves(vector<int>& arr) {
int n = arr.size();
int f[n][n];
memset(f, 0, sizeof f);
for (int i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (int i = n - 2; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (i + 1 == j) {
f[i][j] = arr[i] == arr[j] ? 1 : 2;
} else {
int t = arr[i] == arr[j] ? f[i + 1][j - 1] : 1 << 30;
for (int k = i; k < j; ++k) {
t = min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}
};
| null | null |
func minimumMoves(arr []int) int {
n := len(arr)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
f[i][i] = 1
}
for i := n - 2; i >= 0; i-- {
for j := i + 1; j < n; j++ {
if i+1 == j {
f[i][j] = 2
if arr[i] == arr[j] {
f[i][j] = 1
}
} else {
t := 1 << 30
if arr[i] == arr[j] {
t = f[i+1][j-1]
}
for k := i; k < j; k++ {
t = min(t, f[i][k]+f[k+1][j])
}
f[i][j] = t
}
}
}
return f[0][n-1]
}
|
class Solution {
public int minimumMoves(int[] arr) {
int n = arr.length;
int[][] f = new int[n][n];
for (int i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (int i = n - 2; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (i + 1 == j) {
f[i][j] = arr[i] == arr[j] ? 1 : 2;
} else {
int t = arr[i] == arr[j] ? f[i + 1][j - 1] : 1 << 30;
for (int k = i; k < j; ++k) {
t = Math.min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}
}
| null | null | null | null | null | null |
class Solution:
def minimumMoves(self, arr: List[int]) -> int:
n = len(arr)
f = [[0] * n for _ in range(n)]
for i in range(n):
f[i][i] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if i + 1 == j:
f[i][j] = 1 if arr[i] == arr[j] else 2
else:
t = f[i + 1][j - 1] if arr[i] == arr[j] else inf
for k in range(i, j):
t = min(t, f[i][k] + f[k + 1][j])
f[i][j] = t
return f[0][n - 1]
| null | null | null | null | null |
function minimumMoves(arr: number[]): number {
const n = arr.length;
const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (let i = n - 2; i >= 0; --i) {
for (let j = i + 1; j < n; ++j) {
if (i + 1 === j) {
f[i][j] = arr[i] === arr[j] ? 1 : 2;
} else {
let t = arr[i] === arr[j] ? f[i + 1][j - 1] : Infinity;
for (let k = i; k < j; ++k) {
t = Math.min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}
|
Design Cancellable Function
|
Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function
cancellable
that accepts a generator object and returns an array of two values: a
cancel function
and a
promise
.
You may assume the generator function will only yield promises. It is your function's responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that error back to the generator.
If the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string
"Cancelled"
(Not an
Error
object). If the error was caught, the returned promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.
When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.
An example of how your code would be used:
function* tasks() {
const val = yield new Promise(resolve => resolve(2 + 2));
yield new Promise(resolve => setTimeout(resolve, 100));
return val + 1; // calculation shouldn't be done.
}
const [cancel, promise] = cancellable(tasks());
setTimeout(cancel, 50);
promise.catch(console.log); // logs "Cancelled" at t=50ms
If instead
cancel()
was not called or was called after
t=100ms
, the promise would have resolved
5
.
Example 1:
Input:
generatorFunction = function*() {
return 42;
}
cancelledAt = 100
Output:
{"resolved": 42}
Explanation:
const generator = generatorFunction();
const [cancel, promise] = cancellable(generator);
setTimeout(cancel, 100);
promise.then(console.log); // resolves 42 at t=0ms
The generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.
Example 2:
Input:
generatorFunction = function*() {
const msg = yield new Promise(res => res("Hello"));
throw `Error: ${msg}`;
}
cancelledAt = null
Output:
{"rejected": "Error: Hello"}
Explanation:
A promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.
Example 3:
Input:
generatorFunction = function*() {
yield new Promise(res => setTimeout(res, 200));
return "Success";
}
cancelledAt = 100
Output:
{"rejected": "Cancelled"}
Explanation:
While the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.
Example 4:
Input:
generatorFunction = function*() {
let result = 0;
yield new Promise(res => setTimeout(res, 100));
result += yield new Promise(res => res(1));
yield new Promise(res => setTimeout(res, 100));
result += yield new Promise(res => res(1));
return result;
}
cancelledAt = null
Output:
{"resolved": 2}
Explanation:
4 promises are yielded. Two of those promises have their values added to the result. After 200ms, the generator finishes with a value of 2, and that value is resolved by the returned promise.
Example 5:
Input:
generatorFunction = function*() {
let result = 0;
try {
yield new Promise(res => setTimeout(res, 100));
result += yield new Promise(res => res(1));
yield new Promise(res => setTimeout(res, 100));
result += yield new Promise(res => res(1));
} catch(e) {
return result;
}
return result;
}
cancelledAt = 150
Output:
{"resolved": 1}
Explanation:
The first two yielded promises resolve and cause the result to increment. However, at t=150ms, the generator is cancelled. The error sent to the generator is caught and the result is returned and finally resolved by the returned promise.
Example 6:
Input:
generatorFunction = function*() {
try {
yield new Promise((resolve, reject) => reject("Promise Rejected"));
} catch(e) {
let a = yield new Promise(resolve => resolve(2));
let b = yield new Promise(resolve => resolve(2));
return a + b;
};
}
cancelledAt = null
Output:
{"resolved": 4}
Explanation:
The first yielded promise immediately rejects. This error is caught. Because the generator hasn't been cancelled, execution continues as usual. It ends up resolving 2 + 2 = 4.
Constraints:
cancelledAt == null or 0 <= cancelledAt <= 1000
generatorFunction
returns a generator object
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
function cancellable<T>(generator: Generator<Promise<any>, T, unknown>): [() => void, Promise<T>] {
let cancel: () => void = () => {};
const cancelPromise = new Promise((resolve, reject) => {
cancel = () => reject('Cancelled');
});
cancelPromise.catch(() => {});
const promise = (async () => {
let next = generator.next();
while (!next.done) {
try {
next = generator.next(await Promise.race([next.value, cancelPromise]));
} catch (e) {
next = generator.throw(e);
}
}
return next.value;
})();
return [cancel, promise];
}
/**
* function* tasks() {
* const val = yield new Promise(resolve => resolve(2 + 2));
* yield new Promise(resolve => setTimeout(resolve, 100));
* return val + 1;
* }
* const [cancel, promise] = cancellable(tasks());
* setTimeout(cancel, 50);
* promise.catch(console.log); // logs "Cancelled" at t=50ms
*/
|
Find Minimum Time to Reach Last Room I
|
There is a dungeon with
n x m
rooms arranged as a grid.
You are given a 2D array
moveTime
of size
n x m
, where
moveTime[i][j]
represents the
minimum
time in seconds
after
which the room opens and can be moved to. You start from the room
(0, 0)
at time
t = 0
and can move to an
adjacent
room. Moving between adjacent rooms takes
exactly
one second.
Return the
minimum
time to reach the room
(n - 1, m - 1)
.
Two rooms are
adjacent
if they share a common wall, either
horizontally
or
vertically
.
Example 1:
Input:
moveTime = [[0,4],[4,4]]
Output:
6
Explanation:
The minimum time required is 6 seconds.
At time
t == 4
, move from room
(0, 0)
to room
(1, 0)
in one second.
At time
t == 5
, move from room
(1, 0)
to room
(1, 1)
in one second.
Example 2:
Input:
moveTime = [[0,0,0],[0,0,0]]
Output:
3
Explanation:
The minimum time required is 3 seconds.
At time
t == 0
, move from room
(0, 0)
to room
(1, 0)
in one second.
At time
t == 1
, move from room
(1, 0)
to room
(1, 1)
in one second.
At time
t == 2
, move from room
(1, 1)
to room
(1, 2)
in one second.
Example 3:
Input:
moveTime = [[0,1],[1,2]]
Output:
3
Constraints:
2 <= n == moveTime.length <= 50
2 <= m == moveTime[i].length <= 50
0 <= moveTime[i][j] <= 10
9
| null | null |
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int n = moveTime.size();
int m = moveTime[0].size();
vector<vector<int>> dist(n, vector<int>(m, INT_MAX));
dist[0][0] = 0;
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<>> pq;
pq.push({0, 0, 0});
int dirs[5] = {-1, 0, 1, 0, -1};
while (1) {
auto [d, i, j] = pq.top();
pq.pop();
if (i == n - 1 && j == m - 1) {
return d;
}
if (d > dist[i][j]) {
continue;
}
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k];
int y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < m) {
int t = max(moveTime[x][y], dist[i][j]) + 1;
if (dist[x][y] > t) {
dist[x][y] = t;
pq.push({t, x, y});
}
}
}
}
}
};
| null | null |
func minTimeToReach(moveTime [][]int) int {
n, m := len(moveTime), len(moveTime[0])
dist := make([][]int, n)
for i := range dist {
dist[i] = make([]int, m)
for j := range dist[i] {
dist[i][j] = math.MaxInt32
}
}
dist[0][0] = 0
pq := &hp{}
heap.Init(pq)
heap.Push(pq, tuple{0, 0, 0})
dirs := []int{-1, 0, 1, 0, -1}
for {
p := heap.Pop(pq).(tuple)
d, i, j := p.dis, p.x, p.y
if i == n-1 && j == m-1 {
return d
}
if d > dist[i][j] {
continue
}
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < n && y >= 0 && y < m {
t := max(moveTime[x][y], dist[i][j]) + 1
if dist[x][y] > t {
dist[x][y] = t
heap.Push(pq, tuple{t, x, y})
}
}
}
}
}
type tuple struct{ dis, x, y int }
type hp []tuple
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].dis < h[j].dis }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) }
func (h *hp) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
|
class Solution {
public int minTimeToReach(int[][] moveTime) {
int n = moveTime.length;
int m = moveTime[0].length;
int[][] dist = new int[n][m];
for (var row : dist) {
Arrays.fill(row, Integer.MAX_VALUE);
}
dist[0][0] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[] {0, 0, 0});
int[] dirs = {-1, 0, 1, 0, -1};
while (true) {
int[] p = pq.poll();
int d = p[0], i = p[1], j = p[2];
if (i == n - 1 && j == m - 1) {
return d;
}
if (d > dist[i][j]) {
continue;
}
for (int k = 0; k < 4; k++) {
int x = i + dirs[k];
int y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < m) {
int t = Math.max(moveTime[x][y], dist[i][j]) + 1;
if (dist[x][y] > t) {
dist[x][y] = t;
pq.offer(new int[] {t, x, y});
}
}
}
}
}
}
| null | null | null | null | null | null |
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
n, m = len(moveTime), len(moveTime[0])
dist = [[inf] * m for _ in range(n)]
dist[0][0] = 0
pq = [(0, 0, 0)]
dirs = (-1, 0, 1, 0, -1)
while 1:
d, i, j = heappop(pq)
if i == n - 1 and j == m - 1:
return d
if d > dist[i][j]:
continue
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < m:
t = max(moveTime[x][y], dist[i][j]) + 1
if dist[x][y] > t:
dist[x][y] = t
heappush(pq, (t, x, y))
| null | null | null | null | null |
function minTimeToReach(moveTime: number[][]): number {
const n = moveTime.length;
const m = moveTime[0].length;
const dist = Array.from({ length: n }, () => Array(m).fill(Infinity));
dist[0][0] = 0;
type Node = [number, number, number];
const pq = new PriorityQueue<Node>((a, b) => a[0] - b[0]);
pq.enqueue([0, 0, 0]);
const dirs = [-1, 0, 1, 0, -1];
while (!pq.isEmpty()) {
const [d, i, j] = pq.dequeue();
if (d > dist[i][j]) continue;
if (i === n - 1 && j === m - 1) return d;
for (let k = 0; k < 4; ++k) {
const x = i + dirs[k];
const y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < m) {
const t = Math.max(moveTime[x][y], d) + 1;
if (t < dist[x][y]) {
dist[x][y] = t;
pq.enqueue([t, x, y]);
}
}
}
}
return -1;
}
|
Longest Word in Dictionary
|
Given an array of strings
words
representing an English Dictionary, return
the longest word in
words
that can be built one character at a time by other words in
words
.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input:
words = ["w","wo","wor","worl","world"]
Output:
"world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input:
words = ["a","banana","app","appl","ap","apply","apple"]
Output:
"apple"
Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i]
consists of lowercase English letters.
| null | null |
class Trie {
public:
Trie* children[26] = {nullptr};
bool isEnd = false;
void insert(const string& w) {
Trie* node = this;
for (char c : w) {
int idx = c - 'a';
if (node->children[idx] == nullptr) {
node->children[idx] = new Trie();
}
node = node->children[idx];
}
node->isEnd = true;
}
bool search(const string& w) {
Trie* node = this;
for (char c : w) {
int idx = c - 'a';
if (node->children[idx] == nullptr || !node->children[idx]->isEnd) {
return false;
}
node = node->children[idx];
}
return true;
}
};
class Solution {
public:
string longestWord(vector<string>& words) {
Trie trie;
for (const string& w : words) {
trie.insert(w);
}
string ans = "";
for (const string& w : words) {
if (trie.search(w) && (ans.length() < w.length() || (ans.length() == w.length() && w < ans))) {
ans = w;
}
}
return ans;
}
};
| null | null |
type Trie struct {
children [26]*Trie
isEnd bool
}
func (t *Trie) insert(w string) {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil {
node.children[idx] = &Trie{}
}
node = node.children[idx]
}
node.isEnd = true
}
func (t *Trie) search(w string) bool {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil || !node.children[idx].isEnd {
return false
}
node = node.children[idx]
}
return true
}
func longestWord(words []string) string {
trie := &Trie{}
for _, w := range words {
trie.insert(w)
}
ans := ""
for _, w := range words {
if trie.search(w) && (len(ans) < len(w) || (len(ans) == len(w) && w < ans)) {
ans = w
}
}
return ans
}
|
class Trie {
private Trie[] children = new Trie[26];
private boolean isEnd = false;
public void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.isEnd = true;
}
public boolean search(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null || !node.children[idx].isEnd) {
return false;
}
node = node.children[idx];
}
return true;
}
}
class Solution {
public String longestWord(String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
String ans = "";
for (String w : words) {
if (trie.search(w)
&& (ans.length() < w.length()
|| (ans.length() == w.length() && w.compareTo(ans) < 0))) {
ans = w;
}
}
return ans;
}
}
|
/**
* @param {string[]} words
* @return {string}
*/
var longestWord = function (words) {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
let ans = '';
for (const w of words) {
if (trie.search(w) && (ans.length < w.length || (ans.length === w.length && w < ans))) {
ans = w;
}
}
return ans;
};
class Trie {
constructor() {
this.children = Array(26).fill(null);
this.isEnd = false;
}
insert(w) {
let node = this;
for (let i = 0; i < w.length; i++) {
const idx = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.isEnd = true;
}
search(w) {
let node = this;
for (let i = 0; i < w.length; i++) {
const idx = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null || !node.children[idx].isEnd) {
return false;
}
node = node.children[idx];
}
return true;
}
}
| null | null | null | null | null |
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
self.is_end = False
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, w: str) -> bool:
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
return False
node = node.children[idx]
if not node.is_end:
return False
return True
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
for w in words:
trie.insert(w)
ans = ""
for w in words:
if trie.search(w) and (
len(ans) < len(w) or (len(ans) == len(w) and ans > w)
):
ans = w
return ans
| null |
struct Trie {
children: [Option<Box<Trie>>; 26],
is_end: bool,
}
impl Trie {
fn new() -> Self {
Trie {
children: Default::default(),
is_end: false,
}
}
fn insert(&mut self, w: &str) {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() {
node.children[idx] = Some(Box::new(Trie::new()));
}
node = node.children[idx].as_mut().unwrap();
}
node.is_end = true;
}
fn search(&self, w: &str) -> bool {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() || !node.children[idx].as_ref().unwrap().is_end {
return false;
}
node = node.children[idx].as_ref().unwrap();
}
true
}
}
impl Solution {
pub fn longest_word(words: Vec<String>) -> String {
let mut trie = Trie::new();
for w in &words {
trie.insert(w);
}
let mut ans = String::new();
for w in words {
if trie.search(&w) && (ans.len() < w.len() || (ans.len() == w.len() && w < ans)) {
ans = w;
}
}
ans
}
}
| null | null | null |
class Trie {
children: (Trie | null)[] = new Array(26).fill(null);
isEnd: boolean = false;
insert(w: string): void {
let node: Trie = this;
for (let i = 0; i < w.length; i++) {
const idx: number = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null) {
node.children[idx] = new Trie();
}
node = node.children[idx]!;
}
node.isEnd = true;
}
search(w: string): boolean {
let node: Trie = this;
for (let i = 0; i < w.length; i++) {
const idx: number = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null || !node.children[idx]!.isEnd) {
return false;
}
node = node.children[idx]!;
}
return true;
}
}
function longestWord(words: string[]): string {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
let ans = '';
for (const w of words) {
if (trie.search(w) && (ans.length < w.length || (ans.length === w.length && w < ans))) {
ans = w;
}
}
return ans;
}
|
Lemonade Change
|
At a lemonade stand, each lemonade costs
$5
. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a
$5
,
$10
, or
$20
bill. You must provide the correct change to each customer so that the net transaction is that the customer pays
$5
.
Note that you do not have any change in hand at first.
Given an integer array
bills
where
bills[i]
is the bill the
i
th
customer pays, return
true
if you can provide every customer with the correct change, or
false
otherwise
.
Example 1:
Input:
bills = [5,5,5,10,20]
Output:
true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Example 2:
Input:
bills = [5,5,10,10,20]
Output:
false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.
Constraints:
1 <= bills.length <= 10
5
bills[i]
is either
5
,
10
, or
20
.
| null | null |
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 10;
for (int v : bills) {
if (v == 5) {
++five;
} else if (v == 10) {
++ten;
--five;
} else {
if (ten) {
--ten;
--five;
} else {
five -= 3;
}
}
if (five < 0) {
return false;
}
}
return true;
}
};
| null | null |
func lemonadeChange(bills []int) bool {
five, ten := 0, 0
for _, v := range bills {
if v == 5 {
five++
} else if v == 10 {
ten++
five--
} else {
if ten > 0 {
ten--
five--
} else {
five -= 3
}
}
if five < 0 {
return false
}
}
return true
}
|
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0, ten = 0;
for (int v : bills) {
switch (v) {
case 5 -> ++five;
case 10 -> {
++ten;
--five;
}
case 20 -> {
if (ten > 0) {
--ten;
--five;
} else {
five -= 3;
}
}
}
if (five < 0) {
return false;
}
}
return true;
}
}
|
const lemonadeChange = (bills, f = 0, t = 0) =>
bills.every(
x => (
(!(x ^ 5) && ++f) ||
(!(x ^ 10) && (--f, ++t)) ||
(!(x ^ 20) && (t ? (f--, t--) : (f -= 3), 1)),
f >= 0
),
);
| null | null | null | null | null |
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five = ten = 0
for v in bills:
if v == 5:
five += 1
elif v == 10:
ten += 1
five -= 1
else:
if ten:
ten -= 1
five -= 1
else:
five -= 3
if five < 0:
return False
return True
| null |
impl Solution {
pub fn lemonade_change(bills: Vec<i32>) -> bool {
let (mut five, mut ten) = (0, 0);
for bill in bills.iter() {
match bill {
5 => {
five += 1;
}
10 => {
five -= 1;
ten += 1;
}
_ => {
if ten != 0 {
ten -= 1;
five -= 1;
} else {
five -= 3;
}
}
}
if five < 0 {
return false;
}
}
true
}
}
| null | null | null |
const lemonadeChange = (bills: number[], f = 0, t = 0): boolean =>
bills.every(
x => (
(!(x ^ 5) && ++f) ||
(!(x ^ 10) && (--f, ++t)) ||
(!(x ^ 20) && (t ? (f--, t--) : (f -= 3), 1)),
f >= 0
),
);
|
Count Mentions Per User
|
You are given an integer
numberOfUsers
representing the total number of users and an array
events
of size
n x 3
.
Each
events[i]
can be either of the following two types:
Message Event:
["MESSAGE", "timestamp
i
", "mentions_string
i
"]
This event indicates that a set of users was mentioned in a message at
timestamp
i
.
The
mentions_string
i
string can contain one of the following tokens:
id<number>
: where
<number>
is an integer in range
[0,numberOfUsers - 1]
. There can be
multiple
ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.
ALL
: mentions
all
users.
HERE
: mentions all
online
users.
Offline Event:
["OFFLINE", "timestamp
i
", "id
i
"]
This event indicates that the user
id
i
had become offline at
timestamp
i
for
60 time units
. The user will automatically be online again at time
timestamp
i
+ 60
.
Return an array
mentions
where
mentions[i]
represents the number of mentions the user with id
i
has across all
MESSAGE
events.
All users are initially online, and if a user goes offline or comes back online, their status change is processed
before
handling any message event that occurs at the same timestamp.
Note
that a user can be mentioned
multiple
times in a
single
message event, and each mention should be counted
separately
.
Example 1:
Input:
numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","71","HERE"]]
Output:
[2,2]
Explanation:
Initially, all users are online.
At timestamp 10,
id1
and
id0
are mentioned.
mentions = [1,1]
At timestamp 11,
id0
goes
offline.
At timestamp 71,
id0
comes back
online
and
"HERE"
is mentioned.
mentions = [2,2]
Example 2:
Input:
numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","12","ALL"]]
Output:
[2,2]
Explanation:
Initially, all users are online.
At timestamp 10,
id1
and
id0
are mentioned.
mentions = [1,1]
At timestamp 11,
id0
goes
offline.
At timestamp 12,
"ALL"
is mentioned. This includes offline users, so both
id0
and
id1
are mentioned.
mentions = [2,2]
Example 3:
Input:
numberOfUsers = 2, events = [["OFFLINE","10","0"],["MESSAGE","12","HERE"]]
Output:
[0,1]
Explanation:
Initially, all users are online.
At timestamp 10,
id0
goes
offline.
At timestamp 12,
"HERE"
is mentioned. Because
id0
is still offline, they will not be mentioned.
mentions = [0,1]
Constraints:
1 <= numberOfUsers <= 100
1 <= events.length <= 100
events[i].length == 3
events[i][0]
will be one of
MESSAGE
or
OFFLINE
.
1 <= int(events[i][1]) <= 10
5
The number of
id<number>
mentions in any
"MESSAGE"
event is between
1
and
100
.
0 <= <number> <= numberOfUsers - 1
It is
guaranteed
that the user id referenced in the
OFFLINE
event is
online
at the time the event occurs.
| null | null |
class Solution {
public:
vector<int> countMentions(int numberOfUsers, vector<vector<string>>& events) {
ranges::sort(events, [](const vector<string>& a, const vector<string>& b) {
int x = stoi(a[1]);
int y = stoi(b[1]);
if (x == y) {
return a[0][2] < b[0][2];
}
return x < y;
});
vector<int> ans(numberOfUsers, 0);
vector<int> onlineT(numberOfUsers, 0);
int lazy = 0;
for (const auto& e : events) {
string etype = e[0];
int cur = stoi(e[1]);
string s = e[2];
if (etype[0] == 'O') {
onlineT[stoi(s)] = cur + 60;
} else if (s[0] == 'A') {
lazy++;
} else if (s[0] == 'H') {
for (int i = 0; i < numberOfUsers; ++i) {
if (onlineT[i] <= cur) {
++ans[i];
}
}
} else {
stringstream ss(s);
string token;
while (ss >> token) {
ans[stoi(token.substr(2))]++;
}
}
}
if (lazy > 0) {
for (int i = 0; i < numberOfUsers; ++i) {
ans[i] += lazy;
}
}
return ans;
}
};
| null | null |
func countMentions(numberOfUsers int, events [][]string) []int {
sort.Slice(events, func(i, j int) bool {
x, _ := strconv.Atoi(events[i][1])
y, _ := strconv.Atoi(events[j][1])
if x == y {
return events[i][0][2] < events[j][0][2]
}
return x < y
})
ans := make([]int, numberOfUsers)
onlineT := make([]int, numberOfUsers)
lazy := 0
for _, e := range events {
etype := e[0]
cur, _ := strconv.Atoi(e[1])
s := e[2]
if etype[0] == 'O' {
userID, _ := strconv.Atoi(s)
onlineT[userID] = cur + 60
} else if s[0] == 'A' {
lazy++
} else if s[0] == 'H' {
for i := 0; i < numberOfUsers; i++ {
if onlineT[i] <= cur {
ans[i]++
}
}
} else {
mentions := strings.Split(s, " ")
for _, m := range mentions {
userID, _ := strconv.Atoi(m[2:])
ans[userID]++
}
}
}
if lazy > 0 {
for i := 0; i < numberOfUsers; i++ {
ans[i] += lazy
}
}
return ans
}
|
class Solution {
public int[] countMentions(int numberOfUsers, List<List<String>> events) {
events.sort((a, b) -> {
int x = Integer.parseInt(a.get(1));
int y = Integer.parseInt(b.get(1));
if (x == y) {
return a.get(0).charAt(2) - b.get(0).charAt(2);
}
return x - y;
});
int[] ans = new int[numberOfUsers];
int[] onlineT = new int[numberOfUsers];
int lazy = 0;
for (var e : events) {
String etype = e.get(0);
int cur = Integer.parseInt(e.get(1));
String s = e.get(2);
if (etype.charAt(0) == 'O') {
onlineT[Integer.parseInt(s)] = cur + 60;
} else if (s.charAt(0) == 'A') {
++lazy;
} else if (s.charAt(0) == 'H') {
for (int i = 0; i < numberOfUsers; ++i) {
if (onlineT[i] <= cur) {
++ans[i];
}
}
} else {
for (var a : s.split(" ")) {
++ans[Integer.parseInt(a.substring(2))];
}
}
}
if (lazy > 0) {
for (int i = 0; i < numberOfUsers; ++i) {
ans[i] += lazy;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countMentions(self, numberOfUsers: int, events: List[List[str]]) -> List[int]:
events.sort(key=lambda e: (int(e[1]), e[0][2]))
ans = [0] * numberOfUsers
online_t = [0] * numberOfUsers
lazy = 0
for etype, ts, s in events:
cur = int(ts)
if etype[0] == "O":
online_t[int(s)] = cur + 60
elif s[0] == "A":
lazy += 1
elif s[0] == "H":
for i, t in enumerate(online_t):
if t <= cur:
ans[i] += 1
else:
for a in s.split():
ans[int(a[2:])] += 1
if lazy:
for i in range(numberOfUsers):
ans[i] += lazy
return ans
| null | null | null | null | null |
function countMentions(numberOfUsers: number, events: string[][]): number[] {
events.sort((a, b) => {
const x = +a[1];
const y = +b[1];
if (x === y) {
return a[0].charAt(2) < b[0].charAt(2) ? -1 : 1;
}
return x - y;
});
const ans: number[] = Array(numberOfUsers).fill(0);
const onlineT: number[] = Array(numberOfUsers).fill(0);
let lazy = 0;
for (const [etype, ts, s] of events) {
const cur = +ts;
if (etype.charAt(0) === 'O') {
const userID = +s;
onlineT[userID] = cur + 60;
} else if (s.charAt(0) === 'A') {
lazy++;
} else if (s.charAt(0) === 'H') {
for (let i = 0; i < numberOfUsers; i++) {
if (onlineT[i] <= cur) {
ans[i]++;
}
}
} else {
const mentions = s.split(' ');
for (const m of mentions) {
const userID = +m.slice(2);
ans[userID]++;
}
}
}
if (lazy > 0) {
for (let i = 0; i < numberOfUsers; i++) {
ans[i] += lazy;
}
}
return ans;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.