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
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Interval Cancellation
|
Given a function
fn
, an array of arguments
args
, and an interval time
t
, return a cancel function
cancelFn
.
After a delay of
cancelTimeMs
, the returned cancel function
cancelFn
will be invoked.
setTimeout(cancelFn, cancelTimeMs)
The function
fn
should be called with
args
immediately and then called again every
t
milliseconds until
cancelFn
is called at
cancelTimeMs
ms.
Example 1:
Input:
fn = (x) => x * 2, args = [4], t = 35
Output:
[
{"time": 0, "returned": 8},
{"time": 35, "returned": 8},
{"time": 70, "returned": 8},
{"time": 105, "returned": 8},
{"time": 140, "returned": 8},
{"time": 175, "returned": 8}
]
Explanation:
const cancelTimeMs = 190;
const cancelFn = cancellable((x) => x * 2, [4], 35);
setTimeout(cancelFn, cancelTimeMs);
Every 35ms, fn(4) is called. Until t=190ms, then it is cancelled.
1st fn call is at 0ms. fn(4) returns 8.
2nd fn call is at 35ms. fn(4) returns 8.
3rd fn call is at 70ms. fn(4) returns 8.
4th fn call is at 105ms. fn(4) returns 8.
5th fn call is at 140ms. fn(4) returns 8.
6th fn call is at 175ms. fn(4) returns 8.
Cancelled at 190ms
Example 2:
Input:
fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 30
Output:
[
{"time": 0, "returned": 10},
{"time": 30, "returned": 10},
{"time": 60, "returned": 10},
{"time": 90, "returned": 10},
{"time": 120, "returned": 10},
{"time": 150, "returned": 10}
]
Explanation:
const cancelTimeMs = 165;
const cancelFn = cancellable((x1, x2) => (x1 * x2), [2, 5], 30)
setTimeout(cancelFn, cancelTimeMs)
Every 30ms, fn(2, 5) is called. Until t=165ms, then it is cancelled.
1st fn call is at 0ms
2nd fn call is at 30ms
3rd fn call is at 60ms
4th fn call is at 90ms
5th fn call is at 120ms
6th fn call is at 150ms
Cancelled at 165ms
Example 3:
Input:
fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50
Output:
[
{"time": 0, "returned": 9},
{"time": 50, "returned": 9},
{"time": 100, "returned": 9},
{"time": 150, "returned": 9}
]
Explanation:
const cancelTimeMs = 180;
const cancelFn = cancellable((x1, x2, x3) => (x1 + x2 + x3), [5, 1, 3], 50)
setTimeout(cancelFn, cancelTimeMs)
Every 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled.
1st fn call is at 0ms
2nd fn call is at 50ms
3rd fn call is at 100ms
4th fn call is at 150ms
Cancelled at 180ms
Constraints:
fn
is a function
args
is a valid JSON array
1 <= args.length <= 10
30 <= t <= 100
10 <=
cancelTimeMs
<= 500
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
function cancellable(fn: Function, args: any[], t: number): Function {
fn(...args);
const time = setInterval(() => fn(...args), t);
return () => clearInterval(time);
}
/**
* const result = []
*
* const fn = (x) => x * 2
* const args = [4], t = 20, cancelT = 110
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [
* // {"time":0,"returned":8},
* // {"time":20,"returned":8},
* // {"time":40,"returned":8},
* // {"time":60,"returned":8},
* // {"time":80,"returned":8},
* // {"time":100,"returned":8}
* // ]
* }, cancelT)
*/
|
Number of Ways to Split Array
|
You are given a
0-indexed
integer array
nums
of length
n
.
nums
contains a
valid split
at index
i
if the following are true:
The sum of the first
i + 1
elements is
greater than or equal to
the sum of the last
n - i - 1
elements.
There is
at least one
element to the right of
i
. That is,
0 <= i < n - 1
.
Return
the number of
valid splits
in
nums
.
Example 1:
Input:
nums = [10,4,-8,7]
Output:
2
Explanation:
There are three ways of splitting nums into two non-empty parts:
- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.
Example 2:
Input:
nums = [2,3,1,0]
Output:
2
Explanation:
There are two valid splits in nums:
- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.
Constraints:
2 <= nums.length <= 10
5
-10
5
<= nums[i] <= 10
5
| null | null |
class Solution {
public:
int waysToSplitArray(vector<int>& nums) {
long long s = accumulate(nums.begin(), nums.end(), 0LL);
long long t = 0;
int ans = 0;
for (int i = 0; i + 1 < nums.size(); ++i) {
t += nums[i];
ans += t >= s - t;
}
return ans;
}
};
| null | null |
func waysToSplitArray(nums []int) (ans int) {
var s, t int
for _, x := range nums {
s += x
}
for _, x := range nums[:len(nums)-1] {
t += x
if t >= s-t {
ans++
}
}
return
}
|
class Solution {
public int waysToSplitArray(int[] nums) {
long s = 0;
for (int x : nums) {
s += x;
}
long t = 0;
int ans = 0;
for (int i = 0; i + 1 < nums.length; ++i) {
t += nums[i];
ans += t >= s - t ? 1 : 0;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
s = sum(nums)
ans = t = 0
for x in nums[:-1]:
t += x
ans += t >= s - t
return ans
| null | null | null | null | null |
function waysToSplitArray(nums: number[]): number {
const s = nums.reduce((acc, cur) => acc + cur, 0);
let [ans, t] = [0, 0];
for (const x of nums.slice(0, -1)) {
t += x;
if (t >= s - t) {
++ans;
}
}
return ans;
}
|
Construct the Minimum Bitwise Array I
|
You are given an array
nums
consisting of
n
prime
integers.
You need to construct an array
ans
of length
n
, such that, for each index
i
, the bitwise
OR
of
ans[i]
and
ans[i] + 1
is equal to
nums[i]
, i.e.
ans[i] OR (ans[i] + 1) == nums[i]
.
Additionally, you must
minimize
each value of
ans[i]
in the resulting array.
If it is
not possible
to find such a value for
ans[i]
that satisfies the
condition
, then set
ans[i] = -1
.
Example 1:
Input:
nums = [2,3,5,7]
Output:
[-1,1,4,3]
Explanation:
For
i = 0
, as there is no value for
ans[0]
that satisfies
ans[0] OR (ans[0] + 1) = 2
, so
ans[0] = -1
.
For
i = 1
, the smallest
ans[1]
that satisfies
ans[1] OR (ans[1] + 1) = 3
is
1
, because
1 OR (1 + 1) = 3
.
For
i = 2
, the smallest
ans[2]
that satisfies
ans[2] OR (ans[2] + 1) = 5
is
4
, because
4 OR (4 + 1) = 5
.
For
i = 3
, the smallest
ans[3]
that satisfies
ans[3] OR (ans[3] + 1) = 7
is
3
, because
3 OR (3 + 1) = 7
.
Example 2:
Input:
nums = [11,13,31]
Output:
[9,12,15]
Explanation:
For
i = 0
, the smallest
ans[0]
that satisfies
ans[0] OR (ans[0] + 1) = 11
is
9
, because
9 OR (9 + 1) = 11
.
For
i = 1
, the smallest
ans[1]
that satisfies
ans[1] OR (ans[1] + 1) = 13
is
12
, because
12 OR (12 + 1) = 13
.
For
i = 2
, the smallest
ans[2]
that satisfies
ans[2] OR (ans[2] + 1) = 31
is
15
, because
15 OR (15 + 1) = 31
.
Constraints:
1 <= nums.length <= 100
2 <= nums[i] <= 1000
nums[i]
is a prime number.
| null | null |
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector<int> ans;
for (int x : nums) {
if (x == 2) {
ans.push_back(-1);
} else {
for (int i = 1; i < 32; ++i) {
if (x >> i & 1 ^ 1) {
ans.push_back(x ^ 1 << (i - 1));
break;
}
}
}
}
return ans;
}
};
| null | null |
func minBitwiseArray(nums []int) (ans []int) {
for _, x := range nums {
if x == 2 {
ans = append(ans, -1)
} else {
for i := 1; i < 32; i++ {
if x>>i&1 == 0 {
ans = append(ans, x^1<<(i-1))
break
}
}
}
}
return
}
|
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int n = nums.size();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int x = nums.get(i);
if (x == 2) {
ans[i] = -1;
} else {
for (int j = 1; j < 32; ++j) {
if ((x >> j & 1) == 0) {
ans[i] = x ^ 1 << (j - 1);
break;
}
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
break
return ans
| null | null | null | null | null |
function minBitwiseArray(nums: number[]): number[] {
const ans: number[] = [];
for (const x of nums) {
if (x === 2) {
ans.push(-1);
} else {
for (let i = 1; i < 32; ++i) {
if (((x >> i) & 1) ^ 1) {
ans.push(x ^ (1 << (i - 1)));
break;
}
}
}
}
return ans;
}
|
Reach End of Array With Max Score
|
You are given an integer array
nums
of length
n
.
Your goal is to start at index
0
and reach index
n - 1
. You can only jump to indices
greater
than your current index.
The score for a jump from index
i
to index
j
is calculated as
(j - i) * nums[i]
.
Return the
maximum
possible
total score
by the time you reach the last index.
Example 1:
Input:
nums = [1,3,1,5]
Output:
7
Explanation:
First, jump to index 1 and then jump to the last index. The final score is
1 * 1 + 2 * 3 = 7
.
Example 2:
Input:
nums = [4,3,1,3,2]
Output:
16
Explanation:
Jump directly to the last index. The final score is
4 * 4 = 16
.
Constraints:
1 <= nums.length <= 10
5
1 <= nums[i] <= 10
5
| null | null |
class Solution {
public:
long long findMaximumScore(vector<int>& nums) {
long long ans = 0;
int mx = 0;
for (int i = 0; i + 1 < nums.size(); ++i) {
mx = max(mx, nums[i]);
ans += mx;
}
return ans;
}
};
| null | null |
func findMaximumScore(nums []int) (ans int64) {
mx := 0
for _, x := range nums[:len(nums)-1] {
mx = max(mx, x)
ans += int64(mx)
}
return
}
|
class Solution {
public long findMaximumScore(List<Integer> nums) {
long ans = 0;
int mx = 0;
for (int i = 0; i + 1 < nums.size(); ++i) {
mx = Math.max(mx, nums.get(i));
ans += mx;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findMaximumScore(self, nums: List[int]) -> int:
ans = mx = 0
for x in nums[:-1]:
mx = max(mx, x)
ans += mx
return ans
| null | null | null | null | null |
function findMaximumScore(nums: number[]): number {
let [ans, mx]: [number, number] = [0, 0];
for (const x of nums.slice(0, -1)) {
mx = Math.max(mx, x);
ans += mx;
}
return ans;
}
|
Minimize OR of Remaining Elements Using Operations
|
You are given a
0-indexed
integer array
nums
and an integer
k
.
In one operation, you can pick any index
i
of
nums
such that
0 <= i < nums.length - 1
and replace
nums[i]
and
nums[i + 1]
with a single occurrence of
nums[i] & nums[i + 1]
, where
&
represents the bitwise
AND
operator.
Return
the
minimum
possible value of the bitwise
OR
of the remaining elements of
nums
after applying
at most
k
operations
.
Example 1:
Input:
nums = [3,5,3,2,7], k = 2
Output:
3
Explanation:
Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].
2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].
The bitwise-or of the final array is 3.
It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
Example 2:
Input:
nums = [7,3,15,14,2,8], k = 4
Output:
2
Explanation:
Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8].
2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].
3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].
4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].
The bitwise-or of the final array is 2.
It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
Example 3:
Input:
nums = [10,7,10,3,9,14,9,4], k = 1
Output:
15
Explanation:
Without applying any operations, the bitwise-or of nums is 15.
It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] < 2
30
0 <= k < nums.length
| null | null |
class Solution {
public:
int minOrAfterOperations(vector<int>& nums, int k) {
int ans = 0, rans = 0;
for (int i = 29; i >= 0; i--) {
int test = ans + (1 << i);
int cnt = 0;
int val = 0;
for (auto it : nums) {
if (val == 0) {
val = test & it;
} else {
val &= test & it;
}
if (val) {
cnt++;
}
}
if (cnt > k) {
rans += (1 << i);
} else {
ans += (1 << i);
}
}
return rans;
}
};
| null | null |
func minOrAfterOperations(nums []int, k int) int {
ans := 0
rans := 0
for i := 29; i >= 0; i-- {
test := ans + (1 << i)
cnt := 0
val := 0
for _, num := range nums {
if val == 0 {
val = test & num
} else {
val &= test & num
}
if val != 0 {
cnt++
}
}
if cnt > k {
rans += (1 << i)
} else {
ans += (1 << i)
}
}
return rans
}
|
class Solution {
public int minOrAfterOperations(int[] nums, int k) {
int ans = 0, rans = 0;
for (int i = 29; i >= 0; i--) {
int test = ans + (1 << i);
int cnt = 0;
int val = 0;
for (int num : nums) {
if (val == 0) {
val = test & num;
} else {
val &= test & num;
}
if (val != 0) {
cnt++;
}
}
if (cnt > k) {
rans += (1 << i);
} else {
ans += (1 << i);
}
}
return rans;
}
}
| null | null | null | null | null | null |
class Solution:
def minOrAfterOperations(self, nums: List[int], k: int) -> int:
ans = 0
rans = 0
for i in range(29, -1, -1):
test = ans + (1 << i)
cnt = 0
val = 0
for num in nums:
if val == 0:
val = test & num
else:
val &= test & num
if val:
cnt += 1
if cnt > k:
rans += 1 << i
else:
ans += 1 << i
return rans
| null | null | null | null | null | null |
Triples with Bitwise AND Equal To Zero
|
Given an integer array nums, return
the number of
AND triples
.
An
AND triple
is a triple of indices
(i, j, k)
such that:
0 <= i < nums.length
0 <= j < nums.length
0 <= k < nums.length
nums[i] & nums[j] & nums[k] == 0
, where
&
represents the bitwise-AND operator.
Example 1:
Input:
nums = [2,1,3]
Output:
12
Explanation:
We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
Example 2:
Input:
nums = [0,0,0]
Output:
27
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 2
16
| null | null |
class Solution {
public:
int countTriplets(vector<int>& nums) {
int mx = ranges::max(nums);
int cnt[mx + 1];
memset(cnt, 0, sizeof cnt);
for (int& x : nums) {
for (int& y : nums) {
cnt[x & y]++;
}
}
int ans = 0;
for (int xy = 0; xy <= mx; ++xy) {
for (int& z : nums) {
if ((xy & z) == 0) {
ans += cnt[xy];
}
}
}
return ans;
}
};
| null | null |
func countTriplets(nums []int) (ans int) {
mx := slices.Max(nums)
cnt := make([]int, mx+1)
for _, x := range nums {
for _, y := range nums {
cnt[x&y]++
}
}
for xy := 0; xy <= mx; xy++ {
for _, z := range nums {
if xy&z == 0 {
ans += cnt[xy]
}
}
}
return
}
|
class Solution {
public int countTriplets(int[] nums) {
int mx = 0;
for (int x : nums) {
mx = Math.max(mx, x);
}
int[] cnt = new int[mx + 1];
for (int x : nums) {
for (int y : nums) {
cnt[x & y]++;
}
}
int ans = 0;
for (int xy = 0; xy <= mx; ++xy) {
for (int z : nums) {
if ((xy & z) == 0) {
ans += cnt[xy];
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countTriplets(self, nums: List[int]) -> int:
cnt = Counter(x & y for x in nums for y in nums)
return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0)
| null | null | null | null | null |
function countTriplets(nums: number[]): number {
const mx = Math.max(...nums);
const cnt: number[] = Array(mx + 1).fill(0);
for (const x of nums) {
for (const y of nums) {
cnt[x & y]++;
}
}
let ans = 0;
for (let xy = 0; xy <= mx; ++xy) {
for (const z of nums) {
if ((xy & z) === 0) {
ans += cnt[xy];
}
}
}
return ans;
}
|
Painting the Walls
|
You are given two
0-indexed
integer arrays,
cost
and
time
, of size
n
representing the costs and the time taken to paint
n
different walls respectively. There are two painters available:
A
paid painter
that paints the
i
th
wall in
time[i]
units of time and takes
cost[i]
units of money.
A
free painter
that paints
any
wall in
1
unit of time at a cost of
0
. But the free painter can only be used if the paid painter is already
occupied
.
Return
the minimum amount of money required to paint the
n
walls.
Example 1:
Input:
cost = [1,2,3,2], time = [1,2,3,2]
Output:
3
Explanation:
The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
Example 2:
Input:
cost = [2,3,4,2], time = [1,1,1,1]
Output:
4
Explanation:
The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
Constraints:
1 <= cost.length <= 500
cost.length == time.length
1 <= cost[i] <= 10
6
1 <= time[i] <= 500
| null | null |
class Solution {
public:
int paintWalls(vector<int>& cost, vector<int>& time) {
int n = cost.size();
int f[n][n << 1 | 1];
memset(f, -1, sizeof(f));
function<int(int, int)> dfs = [&](int i, int j) -> int {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return 1 << 30;
}
if (f[i][j] == -1) {
f[i][j] = min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1));
}
return f[i][j];
};
return dfs(0, n);
}
};
| null | null |
func paintWalls(cost []int, time []int) int {
n := len(cost)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n<<1|1)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if n-i <= j-n {
return 0
}
if i >= n {
return 1 << 30
}
if f[i][j] == -1 {
f[i][j] = min(dfs(i+1, j+time[i])+cost[i], dfs(i+1, j-1))
}
return f[i][j]
}
return dfs(0, n)
}
|
class Solution {
private int n;
private int[] cost;
private int[] time;
private Integer[][] f;
public int paintWalls(int[] cost, int[] time) {
n = cost.length;
this.cost = cost;
this.time = time;
f = new Integer[n][n << 1 | 1];
return dfs(0, n);
}
private int dfs(int i, int j) {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return 1 << 30;
}
if (f[i][j] == null) {
f[i][j] = Math.min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1));
}
return f[i][j];
}
}
| null | null | null | null | null | null |
class Solution:
def paintWalls(self, cost: List[int], time: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if n - i <= j:
return 0
if i >= n:
return inf
return min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1))
n = len(cost)
return dfs(0, 0)
| null |
impl Solution {
#[allow(dead_code)]
pub fn paint_walls(cost: Vec<i32>, time: Vec<i32>) -> i32 {
let n = cost.len();
let mut record_vec: Vec<Vec<i32>> = vec![vec![-1; n << 1 | 1]; n];
Self::dfs(&mut record_vec, 0, n as i32, n as i32, &time, &cost)
}
#[allow(dead_code)]
fn dfs(
record_vec: &mut Vec<Vec<i32>>,
i: i32,
j: i32,
n: i32,
time: &Vec<i32>,
cost: &Vec<i32>,
) -> i32 {
if n - i <= j - n {
// All the remaining walls can be printed at no cost
// Just return 0
return 0;
}
if i >= n {
// No way this case can be achieved
// Just return +INF
return 1 << 30;
}
if record_vec[i as usize][j as usize] == -1 {
// This record hasn't been written
record_vec[i as usize][j as usize] = std::cmp::min(
Self::dfs(record_vec, i + 1, j + time[i as usize], n, time, cost)
+ cost[i as usize],
Self::dfs(record_vec, i + 1, j - 1, n, time, cost),
);
}
record_vec[i as usize][j as usize]
}
}
| null | null | null | null |
Meeting Rooms 🔒
|
Given an array of meeting time
intervals
where
intervals[i] = [start
i
, end
i
]
, determine if a person could attend all meetings.
Example 1:
Input:
intervals = [[0,30],[5,10],[15,20]]
Output:
false
Example 2:
Input:
intervals = [[7,10],[2,4]]
Output:
true
Constraints:
0 <= intervals.length <= 10
4
intervals[i].length == 2
0 <= start
i
< end
i
<= 10
6
| null | null |
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
ranges::sort(intervals, [](const auto& a, const auto& b) {
return a[0] < b[0];
});
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i - 1][1] > intervals[i][0]) {
return false;
}
}
return true;
}
};
| null | null |
func canAttendMeetings(intervals [][]int) bool {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
for i := 1; i < len(intervals); i++ {
if intervals[i][0] < intervals[i-1][1] {
return false
}
}
return true
}
|
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
for (int i = 1; i < intervals.length; ++i) {
if (intervals[i - 1][1] > intervals[i][0]) {
return false;
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort()
return all(a[1] <= b[0] for a, b in pairwise(intervals))
| null |
impl Solution {
pub fn can_attend_meetings(mut intervals: Vec<Vec<i32>>) -> bool {
intervals.sort_by(|a, b| a[0].cmp(&b[0]));
for i in 1..intervals.len() {
if intervals[i - 1][1] > intervals[i][0] {
return false;
}
}
true
}
}
| null | null | null |
function canAttendMeetings(intervals: number[][]): boolean {
intervals.sort((a, b) => a[0] - b[0]);
for (let i = 1; i < intervals.length; ++i) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
|
Find The Original Array of Prefix Xor
|
You are given an
integer
array
pref
of size
n
. Find and return
the array
arr
of size
n
that satisfies
:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]
.
Note that
^
denotes the
bitwise-xor
operation.
It can be proven that the answer is
unique
.
Example 1:
Input:
pref = [5,2,0,3,1]
Output:
[5,7,2,3,2]
Explanation:
From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2:
Input:
pref = [13]
Output:
[13]
Explanation:
We have pref[0] = arr[0] = 13.
Constraints:
1 <= pref.length <= 10
5
0 <= pref[i] <= 10
6
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findArray(int* pref, int prefSize, int* returnSize) {
int* res = (int*) malloc(sizeof(int) * prefSize);
res[0] = pref[0];
for (int i = 1; i < prefSize; i++) {
res[i] = pref[i - 1] ^ pref[i];
}
*returnSize = prefSize;
return res;
}
| null |
class Solution {
public:
vector<int> findArray(vector<int>& pref) {
int n = pref.size();
vector<int> ans = {pref[0]};
for (int i = 1; i < n; ++i) {
ans.push_back(pref[i - 1] ^ pref[i]);
}
return ans;
}
};
| null | null |
func findArray(pref []int) []int {
n := len(pref)
ans := []int{pref[0]}
for i := 1; i < n; i++ {
ans = append(ans, pref[i-1]^pref[i])
}
return ans
}
|
class Solution {
public int[] findArray(int[] pref) {
int n = pref.length;
int[] ans = new int[n];
ans[0] = pref[0];
for (int i = 1; i < n; ++i) {
ans[i] = pref[i - 1] ^ pref[i];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findArray(self, pref: List[int]) -> List[int]:
return [a ^ b for a, b in pairwise([0] + pref)]
| null |
impl Solution {
pub fn find_array(pref: Vec<i32>) -> Vec<i32> {
let n = pref.len();
let mut res = vec![0; n];
res[0] = pref[0];
for i in 1..n {
res[i] = pref[i] ^ pref[i - 1];
}
res
}
}
| null | null | null |
function findArray(pref: number[]): number[] {
let ans = pref.slice();
for (let i = 1; i < pref.length; i++) {
ans[i] = pref[i - 1] ^ pref[i];
}
return ans;
}
|
Maximum Number of Matching Indices After Right Shifts 🔒
|
You are given two integer arrays,
nums1
and
nums2
, of the same length.
An index
i
is considered
matching
if
nums1[i] == nums2[i]
.
Return the
maximum
number of
matching
indices after performing any number of
right shifts
on
nums1
.
A
right shift
is defined as shifting the element at index
i
to index
(i + 1) % n
, for all indices.
Example 1:
Input:
nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]
Output:
6
Explanation:
If we right shift
nums1
2 times, it becomes
[1, 2, 3, 1, 2, 3]
. Every index matches, so the output is 6.
Example 2:
Input:
nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]
Output:
3
Explanation:
If we right shift
nums1
3 times, it becomes
[5, 3, 1, 1, 4, 2]
. Indices 1, 2, and 4 match, so the output is 3.
Constraints:
nums1.length == nums2.length
1 <= nums1.length, nums2.length <= 3000
1 <= nums1[i], nums2[i] <= 10
9
| null | null |
class Solution {
public:
int maximumMatchingIndices(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int ans = 0;
for (int k = 0; k < n; ++k) {
int t = 0;
for (int i = 0; i < n; ++i) {
if (nums1[(i + k) % n] == nums2[i]) {
++t;
}
}
ans = max(ans, t);
}
return ans;
}
};
| null | null |
func maximumMatchingIndices(nums1 []int, nums2 []int) (ans int) {
n := len(nums1)
for k := range nums1 {
t := 0
for i, x := range nums2 {
if nums1[(i+k)%n] == x {
t++
}
}
ans = max(ans, t)
}
return
}
|
class Solution {
public int maximumMatchingIndices(int[] nums1, int[] nums2) {
int n = nums1.length;
int ans = 0;
for (int k = 0; k < n; ++k) {
int t = 0;
for (int i = 0; i < n; ++i) {
if (nums1[(i + k) % n] == nums2[i]) {
++t;
}
}
ans = Math.max(ans, t);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumMatchingIndices(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
ans = 0
for k in range(n):
t = sum(nums1[(i + k) % n] == x for i, x in enumerate(nums2))
ans = max(ans, t)
return ans
| null | null | null | null | null |
function maximumMatchingIndices(nums1: number[], nums2: number[]): number {
const n = nums1.length;
let ans: number = 0;
for (let k = 0; k < n; ++k) {
let t: number = 0;
for (let i = 0; i < n; ++i) {
if (nums1[(i + k) % n] === nums2[i]) {
++t;
}
}
ans = Math.max(ans, t);
}
return ans;
}
|
Maximum Profitable Triplets With Increasing Prices I 🔒
|
Given the
0-indexed
arrays
prices
and
profits
of length
n
. There are
n
items in an store where the
i
th
item has a price of
prices[i]
and a profit of
profits[i]
.
We have to pick three items with the following condition:
prices[i] < prices[j] < prices[k]
where
i < j < k
.
If we pick items with indices
i
,
j
and
k
satisfying the above condition, the profit would be
profits[i] + profits[j] + profits[k]
.
Return
the
maximum profit
we can get, and
-1
if it's not possible to pick three items with the given condition.
Example 1:
Input:
prices = [10,2,3,4], profits = [100,2,7,10]
Output:
19
Explanation:
We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.
Example 2:
Input:
prices = [1,2,3,4,5], profits = [1,5,3,4,6]
Output:
15
Explanation:
We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.
Example 3:
Input:
prices = [4,3,2,1], profits = [33,20,19,87]
Output:
-1
Explanation:
We can't select any triplet of indices such that the condition holds, so we return -1.
Constraints:
3 <= prices.length == profits.length <= 2000
1 <= prices[i] <= 10
6
1 <= profits[i] <= 10
6
| null | null |
class BinaryIndexedTree {
private:
int n;
vector<int> c;
public:
BinaryIndexedTree(int n) {
this->n = n;
c.resize(n + 1, 0);
}
void update(int x, int v) {
while (x <= n) {
c[x] = max(c[x], v);
x += x & -x;
}
}
int query(int x) {
int mx = 0;
while (x > 0) {
mx = max(mx, c[x]);
x -= x & -x;
}
return mx;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
int n = prices.size();
vector<int> left(n);
vector<int> right(n);
vector<int> s = prices;
sort(s.begin(), s.end());
s.erase(unique(s.begin(), s.end()), s.end());
int m = s.size();
BinaryIndexedTree tree1(m + 1);
BinaryIndexedTree tree2(m + 1);
for (int i = 0; i < n; ++i) {
int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1;
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (int i = n - 1; i >= 0; --i) {
int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1);
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
int ans = -1;
for (int i = 0; i < n; ++i) {
if (left[i] > 0 && right[i] > 0) {
ans = max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
};
| null | null |
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
c := make([]int, n+1)
return BinaryIndexedTree{n: n, c: c}
}
func (bit *BinaryIndexedTree) update(x, v int) {
for x <= bit.n {
bit.c[x] = max(bit.c[x], v)
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) int {
mx := 0
for x > 0 {
mx = max(mx, bit.c[x])
x -= x & -x
}
return mx
}
func maxProfit(prices []int, profits []int) int {
n := len(prices)
left := make([]int, n)
right := make([]int, n)
s := make([]int, n)
copy(s, prices)
sort.Ints(s)
m := 0
for i, x := range s {
if i == 0 || x != s[i-1] {
s[m] = x
m++
}
}
tree1 := NewBinaryIndexedTree(m + 1)
tree2 := NewBinaryIndexedTree(m + 1)
for i, x := range prices {
x = sort.SearchInts(s[:m], x) + 1
left[i] = tree1.query(x - 1)
tree1.update(x, profits[i])
}
for i := n - 1; i >= 0; i-- {
x := m + 1 - (sort.SearchInts(s[:m], prices[i]) + 1)
right[i] = tree2.query(x - 1)
tree2.update(x, profits[i])
}
ans := -1
for i := 0; i < n; i++ {
if left[i] > 0 && right[i] > 0 {
ans = max(ans, left[i]+profits[i]+right[i])
}
}
return ans
}
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int v) {
while (x <= n) {
c[x] = Math.max(c[x], v);
x += x & -x;
}
}
public int query(int x) {
int mx = 0;
while (x > 0) {
mx = Math.max(mx, c[x]);
x -= x & -x;
}
return mx;
}
}
class Solution {
public int maxProfit(int[] prices, int[] profits) {
int n = prices.length;
int[] left = new int[n];
int[] right = new int[n];
int[] s = prices.clone();
Arrays.sort(s);
int m = 0;
for (int i = 0; i < n; ++i) {
if (i == 0 || s[i] != s[i - 1]) {
s[m++] = s[i];
}
}
BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1);
BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1);
for (int i = 0; i < n; ++i) {
int x = search(s, prices[i], m);
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (int i = n - 1; i >= 0; --i) {
int x = m + 1 - search(s, prices[i], m);
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
int ans = -1;
for (int i = 0; i < n; ++i) {
if (left[i] > 0 && right[i] > 0) {
ans = Math.max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
private int search(int[] nums, int x, int r) {
int l = 0;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l + 1;
}
}
| null | null | null | null | null | null |
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = 0
while x:
mx = max(mx, self.c[x])
x -= x & -x
return mx
class Solution:
def maxProfit(self, prices: List[int], profits: List[int]) -> int:
n = len(prices)
left = [0] * n
right = [0] * n
s = sorted(set(prices))
m = len(s)
tree1 = BinaryIndexedTree(m + 1)
tree2 = BinaryIndexedTree(m + 1)
for i, x in enumerate(prices):
x = bisect_left(s, x) + 1
left[i] = tree1.query(x - 1)
tree1.update(x, profits[i])
for i in range(n - 1, -1, -1):
x = m + 1 - (bisect_left(s, prices[i]) + 1)
right[i] = tree2.query(x - 1)
tree2.update(x, profits[i])
return max(
(l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1
)
| null |
struct BinaryIndexedTree {
n: usize,
c: Vec<i32>,
}
impl BinaryIndexedTree {
fn new(n: usize) -> BinaryIndexedTree {
BinaryIndexedTree {
n,
c: vec![0; n + 1],
}
}
fn update(&mut self, x: usize, v: i32) {
let mut x = x;
while x <= self.n {
self.c[x] = self.c[x].max(v);
x += x & x.wrapping_neg();
}
}
fn query(&self, x: usize) -> i32 {
let mut x = x;
let mut mx = 0;
while x > 0 {
mx = mx.max(self.c[x]);
x -= x & x.wrapping_neg();
}
mx
}
}
impl Solution {
pub fn max_profit(prices: Vec<i32>, profits: Vec<i32>) -> i32 {
let n = prices.len();
let mut left = vec![0; n];
let mut right = vec![0; n];
let m = prices.iter().cloned().max().unwrap_or(0);
let mut tree1 = BinaryIndexedTree::new((m as usize) + 1);
let mut tree2 = BinaryIndexedTree::new((m as usize) + 1);
for i in 0..n {
let x = prices[i] as usize;
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for i in (0..n).rev() {
let x = (m + 1 - prices[i]) as usize;
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
let mut ans = -1;
for i in 0..n {
if left[i] > 0 && right[i] > 0 {
ans = ans.max(left[i] + profits[i] + right[i]);
}
}
ans
}
}
| null | null | null |
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] = Math.max(this.c[x], v);
x += x & -x;
}
}
query(x: number): number {
let mx = 0;
while (x > 0) {
mx = Math.max(mx, this.c[x]);
x -= x & -x;
}
return mx;
}
}
function maxProfit(prices: number[], profits: number[]): number {
const n: number = prices.length;
const left: number[] = Array(n).fill(0);
const right: number[] = Array(n).fill(0);
const s = [...prices].sort((a, b) => a - b);
let m = 0;
for (let i = 0; i < n; ++i) {
if (i === 0 || s[i] !== s[i - 1]) {
s[m++] = s[i];
}
}
s.length = m;
const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1);
const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1);
const search = (nums: number[], x: number): number => {
let [l, r] = [0, nums.length];
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
for (let i = 0; i < n; ++i) {
const x = search(s, prices[i]) + 1;
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (let i = n - 1; i >= 0; i--) {
const x: number = m + 1 - (search(s, prices[i]) + 1);
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
let ans: number = -1;
for (let i = 0; i < n; i++) {
if (left[i] > 0 && right[i] > 0) {
ans = Math.max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
|
Paint House IV
|
You are given an
even
integer
n
representing the number of houses arranged in a straight line, and a 2D array
cost
of size
n x 3
, where
cost[i][j]
represents the cost of painting house
i
with color
j + 1
.
The houses will look
beautiful
if they satisfy the following conditions:
No
two
adjacent houses are painted the same color.
Houses
equidistant
from the ends of the row are
not
painted the same color. For example, if
n = 6
, houses at positions
(0, 5)
,
(1, 4)
, and
(2, 3)
are considered equidistant.
Return the
minimum
cost to paint the houses such that they look
beautiful
.
Example 1:
Input:
n = 4, cost = [[3,5,7],[6,2,9],[4,8,1],[7,3,5]]
Output:
9
Explanation:
The optimal painting sequence is
[1, 2, 3, 2]
with corresponding costs
[3, 2, 1, 3]
. This satisfies the following conditions:
No adjacent houses have the same color.
Houses at positions 0 and 3 (equidistant from the ends) are not painted the same color
(1 != 2)
.
Houses at positions 1 and 2 (equidistant from the ends) are not painted the same color
(2 != 3)
.
The minimum cost to paint the houses so that they look beautiful is
3 + 2 + 1 + 3 = 9
.
Example 2:
Input:
n = 6, cost = [[2,4,6],[5,3,8],[7,1,9],[4,6,2],[3,5,7],[8,2,4]]
Output:
18
Explanation:
The optimal painting sequence is
[1, 3, 2, 3, 1, 2]
with corresponding costs
[2, 8, 1, 2, 3, 2]
. This satisfies the following conditions:
No adjacent houses have the same color.
Houses at positions 0 and 5 (equidistant from the ends) are not painted the same color
(1 != 2)
.
Houses at positions 1 and 4 (equidistant from the ends) are not painted the same color
(3 != 1)
.
Houses at positions 2 and 3 (equidistant from the ends) are not painted the same color
(2 != 3)
.
The minimum cost to paint the houses so that they look beautiful is
2 + 8 + 1 + 2 + 3 + 2 = 18
.
Constraints:
2 <= n <= 10
5
n
is even.
cost.length == n
cost[i].length == 3
0 <= cost[i][j] <= 10
5
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Find the Maximum Number of Elements in Subset
|
You are given an array of
positive
integers
nums
.
You need to select a
subset
of
nums
which satisfies the following condition:
You can place the selected elements in a
0-indexed
array such that it follows the pattern:
[x, x
2
, x
4
, ..., x
k/2
, x
k
, x
k/2
, ..., x
4
, x
2
, x]
(
Note
that
k
can be be any
non-negative
power of
2
). For example,
[2, 4, 16, 4, 2]
and
[3, 9, 3]
follow the pattern while
[2, 4, 8, 4, 2]
does not.
Return
the
maximum
number of elements in a subset that satisfies these conditions.
Example 1:
Input:
nums = [5,4,1,2,2]
Output:
3
Explanation:
We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2
2
== 4. Hence the answer is 3.
Example 2:
Input:
nums = [1,3,2,4]
Output:
1
Explanation:
We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer.
Constraints:
2 <= nums.length <= 10
5
1 <= nums[i] <= 10
9
| null | null |
class Solution {
public:
int maximumLength(vector<int>& nums) {
unordered_map<long long, int> cnt;
for (int x : nums) {
++cnt[x];
}
int ans = cnt[1] - (cnt[1] % 2 ^ 1);
cnt.erase(1);
for (auto [v, _] : cnt) {
int t = 0;
long long x = v;
while (cnt.count(x) && cnt[x] > 1) {
x = x * x;
t += 2;
}
t += cnt.count(x) ? 1 : -1;
ans = max(ans, t);
}
return ans;
}
};
| null | null |
func maximumLength(nums []int) (ans int) {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
ans = cnt[1] - (cnt[1]%2 ^ 1)
delete(cnt, 1)
for x := range cnt {
t := 0
for cnt[x] > 1 {
x = x * x
t += 2
}
if cnt[x] > 0 {
t += 1
} else {
t -= 1
}
ans = max(ans, t)
}
return
}
|
class Solution {
public int maximumLength(int[] nums) {
Map<Long, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge((long) x, 1, Integer::sum);
}
Integer t = cnt.remove(1L);
int ans = t == null ? 0 : t - (t % 2 ^ 1);
for (long x : cnt.keySet()) {
t = 0;
while (cnt.getOrDefault(x, 0) > 1) {
x = x * x;
t += 2;
}
t += cnt.getOrDefault(x, -1);
ans = Math.max(ans, t);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumLength(self, nums: List[int]) -> int:
cnt = Counter(nums)
ans = cnt[1] - (cnt[1] % 2 ^ 1)
del cnt[1]
for x in cnt:
t = 0
while cnt[x] > 1:
x = x * x
t += 2
t += 1 if cnt[x] else -1
ans = max(ans, t)
return ans
| null | null | null | null | null |
function maximumLength(nums: number[]): number {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) ?? 0) + 1);
}
let ans = cnt.has(1) ? cnt.get(1)! - (cnt.get(1)! % 2 ^ 1) : 0;
cnt.delete(1);
for (let [x, _] of cnt) {
let t = 0;
while (cnt.has(x) && cnt.get(x)! > 1) {
x = x * x;
t += 2;
}
t += cnt.has(x) ? 1 : -1;
ans = Math.max(ans, t);
}
return ans;
}
|
Longest Substring with At Least K Repeating Characters
|
Given a string
s
and an integer
k
, return
the length of the longest substring of
s
such that the frequency of each character in this substring is greater than or equal to
k
.
if no such substring exists, return 0.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
Explanation:
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
Explanation:
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Constraints:
1 <= s.length <= 10
4
s
consists of only lowercase English letters.
1 <= k <= 10
5
| null | null |
class Solution {
public:
int longestSubstring(string s, int k) {
function<int(int, int)> dfs = [&](int l, int r) -> int {
int cnt[26] = {0};
for (int i = l; i <= r; ++i) {
cnt[s[i] - 'a']++;
}
char split = 0;
for (int i = 0; i < 26; ++i) {
if (cnt[i] > 0 && cnt[i] < k) {
split = 'a' + i;
break;
}
}
if (split == 0) {
return r - l + 1;
}
int i = l;
int ans = 0;
while (i <= r) {
while (i <= r && s[i] == split) {
++i;
}
if (i >= r) {
break;
}
int j = i;
while (j <= r && s[j] != split) {
++j;
}
int t = dfs(i, j - 1);
ans = max(ans, t);
i = j;
}
return ans;
};
return dfs(0, s.size() - 1);
}
};
| null | null |
func longestSubstring(s string, k int) int {
var dfs func(l, r int) int
dfs = func(l, r int) int {
cnt := [26]int{}
for i := l; i <= r; i++ {
cnt[s[i]-'a']++
}
var split byte
for i, v := range cnt {
if v > 0 && v < k {
split = byte(i + 'a')
break
}
}
if split == 0 {
return r - l + 1
}
i := l
ans := 0
for i <= r {
for i <= r && s[i] == split {
i++
}
if i > r {
break
}
j := i
for j <= r && s[j] != split {
j++
}
t := dfs(i, j-1)
ans = max(ans, t)
i = j
}
return ans
}
return dfs(0, len(s)-1)
}
|
class Solution {
private String s;
private int k;
public int longestSubstring(String s, int k) {
this.s = s;
this.k = k;
return dfs(0, s.length() - 1);
}
private int dfs(int l, int r) {
int[] cnt = new int[26];
for (int i = l; i <= r; ++i) {
++cnt[s.charAt(i) - 'a'];
}
char split = 0;
for (int i = 0; i < 26; ++i) {
if (cnt[i] > 0 && cnt[i] < k) {
split = (char) (i + 'a');
break;
}
}
if (split == 0) {
return r - l + 1;
}
int i = l;
int ans = 0;
while (i <= r) {
while (i <= r && s.charAt(i) == split) {
++i;
}
if (i > r) {
break;
}
int j = i;
while (j <= r && s.charAt(j) != split) {
++j;
}
int t = dfs(i, j - 1);
ans = Math.max(ans, t);
i = j;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
def dfs(l, r):
cnt = Counter(s[l : r + 1])
split = next((c for c, v in cnt.items() if v < k), '')
if not split:
return r - l + 1
i = l
ans = 0
while i <= r:
while i <= r and s[i] == split:
i += 1
if i >= r:
break
j = i
while j <= r and s[j] != split:
j += 1
t = dfs(i, j - 1)
ans = max(ans, t)
i = j
return ans
return dfs(0, len(s) - 1)
| null | null | null | null | null | null |
Next Greater Element I
|
The
next greater element
of some element
x
in an array is the
first greater
element that is
to the right
of
x
in the same array.
You are given two
distinct 0-indexed
integer arrays
nums1
and
nums2
, where
nums1
is a subset of
nums2
.
For each
0 <= i < nums1.length
, find the index
j
such that
nums1[i] == nums2[j]
and determine the
next greater element
of
nums2[j]
in
nums2
. If there is no next greater element, then the answer for this query is
-1
.
Return
an array
ans
of length
nums1.length
such that
ans[i]
is the
next greater element
as described above.
Example 1:
Input:
nums1 = [4,1,2], nums2 = [1,3,4,2]
Output:
[-1,3,-1]
Explanation:
The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,
4
,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [
1
,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,
2
]. There is no next greater element, so the answer is -1.
Example 2:
Input:
nums1 = [2,4], nums2 = [1,2,3,4]
Output:
[3,-1]
Explanation:
The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,
2
,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,
4
]. There is no next greater element, so the answer is -1.
Constraints:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 10
4
All integers in
nums1
and
nums2
are
unique
.
All the integers of
nums1
also appear in
nums2
.
Follow up:
Could you find an
O(nums1.length + nums2.length)
solution?
| null | null |
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int> stk;
unordered_map<int, int> d;
ranges::reverse(nums2);
for (int x : nums2) {
while (!stk.empty() && stk.top() < x) {
stk.pop();
}
if (!stk.empty()) {
d[x] = stk.top();
}
stk.push(x);
}
vector<int> ans;
for (int x : nums1) {
ans.push_back(d.contains(x) ? d[x] : -1);
}
return ans;
}
};
| null | null |
func nextGreaterElement(nums1 []int, nums2 []int) (ans []int) {
stk := []int{}
d := map[int]int{}
for i := len(nums2) - 1; i >= 0; i-- {
x := nums2[i]
for len(stk) > 0 && stk[len(stk)-1] < x {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
d[x] = stk[len(stk)-1]
}
stk = append(stk, x)
}
for _, x := range nums1 {
if v, ok := d[x]; ok {
ans = append(ans, v)
} else {
ans = append(ans, -1)
}
}
return
}
|
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stk = new ArrayDeque<>();
int m = nums1.length, n = nums2.length;
Map<Integer, Integer> d = new HashMap(n);
for (int i = n - 1; i >= 0; --i) {
int x = nums2[i];
while (!stk.isEmpty() && stk.peek() < x) {
stk.pop();
}
if (!stk.isEmpty()) {
d.put(x, stk.peek());
}
stk.push(x);
}
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
ans[i] = d.getOrDefault(nums1[i], -1);
}
return ans;
}
}
|
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var nextGreaterElement = function (nums1, nums2) {
const stk = [];
const d = {};
for (const x of nums2.reverse()) {
while (stk.length && stk.at(-1) < x) {
stk.pop();
}
d[x] = stk.length ? stk.at(-1) : -1;
stk.push(x);
}
return nums1.map(x => d[x]);
};
| null | null | null | null | null |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stk = []
d = {}
for x in nums2[::-1]:
while stk and stk[-1] < x:
stk.pop()
if stk:
d[x] = stk[-1]
stk.append(x)
return [d.get(x, -1) for x in nums1]
| null |
use std::collections::HashMap;
impl Solution {
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut stk = Vec::new();
let mut d = HashMap::new();
for &x in nums2.iter().rev() {
while let Some(&top) = stk.last() {
if top <= x {
stk.pop();
} else {
break;
}
}
if let Some(&top) = stk.last() {
d.insert(x, top);
}
stk.push(x);
}
nums1
.into_iter()
.map(|x| *d.get(&x).unwrap_or(&-1))
.collect()
}
}
| null | null | null |
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
const stk: number[] = [];
const d: Record<number, number> = {};
for (const x of nums2.reverse()) {
while (stk.length && stk.at(-1)! < x) {
stk.pop();
}
d[x] = stk.length ? stk.at(-1)! : -1;
stk.push(x);
}
return nums1.map(x => d[x]);
}
|
Insert Delete GetRandom O(1) - Duplicates allowed
|
RandomizedCollection
is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
Implement the
RandomizedCollection
class:
RandomizedCollection()
Initializes the empty
RandomizedCollection
object.
bool insert(int val)
Inserts an item
val
into the multiset, even if the item is already present. Returns
true
if the item is not present,
false
otherwise.
bool remove(int val)
Removes an item
val
from the multiset if present. Returns
true
if the item is present,
false
otherwise. Note that if
val
has multiple occurrences in the multiset, we only remove one of them.
int getRandom()
Returns a random element from the current multiset of elements. The probability of each element being returned is
linearly related
to the number of the same values the multiset contains.
You must implement the functions of the class such that each function works on
average
O(1)
time complexity.
Note:
The test cases are generated such that
getRandom
will only be called if there is
at least one
item in the
RandomizedCollection
.
Example 1:
Input
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
[[], [1], [1], [2], [], [1], []]
Output
[null, true, false, true, 2, true, 1]
Explanation
RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1); // return true since the collection does not contain 1.
// Inserts 1 into the collection.
randomizedCollection.insert(1); // return false since the collection contains 1.
// Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2); // return true since the collection does not contain 2.
// Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom(); // getRandom should:
// - return 1 with probability 2/3, or
// - return 2 with probability 1/3.
randomizedCollection.remove(1); // return true since the collection contains 1.
// Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
Constraints:
-2
31
<= val <= 2
31
- 1
At most
2 * 10
5
calls
in total
will be made to
insert
,
remove
, and
getRandom
.
There will be
at least one
element in the data structure when
getRandom
is called.
| null | null | null | null | null | null |
class RandomizedCollection {
private Map<Integer, Set<Integer>> m;
private List<Integer> l;
private Random rnd;
/** Initialize your data structure here. */
public RandomizedCollection() {
m = new HashMap<>();
l = new ArrayList<>();
rnd = new Random();
}
/**
* Inserts a value to the collection. Returns true if the collection did not already contain
* the specified element.
*/
public boolean insert(int val) {
m.computeIfAbsent(val, k -> new HashSet<>()).add(l.size());
l.add(val);
return m.get(val).size() == 1;
}
/**
* Removes a value from the collection. Returns true if the collection contained the specified
* element.
*/
public boolean remove(int val) {
if (!m.containsKey(val)) {
return false;
}
Set<Integer> idxSet = m.get(val);
int idx = idxSet.iterator().next();
int lastIdx = l.size() - 1;
l.set(idx, l.get(lastIdx));
idxSet.remove(idx);
Set<Integer> lastIdxSet = m.get(l.get(lastIdx));
lastIdxSet.remove(lastIdx);
if (idx < lastIdx) {
lastIdxSet.add(idx);
}
if (idxSet.isEmpty()) {
m.remove(val);
}
l.remove(lastIdx);
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
int size = l.size();
return size == 0 ? -1 : l.get(rnd.nextInt(size));
}
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
| null | null | null | null | null | null |
class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.m = {}
self.l = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
"""
idx_set = self.m.get(val, set())
idx_set.add(len(self.l))
self.m[val] = idx_set
self.l.append(val)
return len(idx_set) == 1
def remove(self, val: int) -> bool:
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
"""
if val not in self.m:
return False
idx_set = self.m[val]
idx = list(idx_set)[0]
last_idx = len(self.l) - 1
self.l[idx] = self.l[last_idx]
idx_set.remove(idx)
last_idx_set = self.m[self.l[last_idx]]
if last_idx in last_idx_set:
last_idx_set.remove(last_idx)
if idx < last_idx:
last_idx_set.add(idx)
if not idx_set:
self.m.pop(val)
self.l.pop()
return True
def getRandom(self) -> int:
"""
Get a random element from the collection.
"""
return -1 if len(self.l) == 0 else random.choice(self.l)
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| null | null | null | null | null | null |
LRU Cache
|
Design a data structure that follows the constraints of a
Least Recently Used (LRU) cache
.
Implement the
LRUCache
class:
LRUCache(int capacity)
Initialize the LRU cache with
positive
size
capacity
.
int get(int key)
Return the value of the
key
if the key exists, otherwise return
-1
.
void put(int key, int value)
Update the value of the
key
if the
key
exists. Otherwise, add the
key-value
pair to the cache. If the number of keys exceeds the
capacity
from this operation,
evict
the least recently used key.
The functions
get
and
put
must each run in
O(1)
average time complexity.
Example 1:
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Constraints:
1 <= capacity <= 3000
0 <= key <= 10
4
0 <= value <= 10
5
At most
2 * 10
5
calls will be made to
get
and
put
.
| null |
public class LRUCache {
private int size;
private int capacity;
private Dictionary<int, Node> cache = new Dictionary<int, Node>();
private Node head = new Node();
private Node tail = new Node();
public LRUCache(int capacity) {
this.capacity = capacity;
head.Next = tail;
tail.Prev = head;
}
public int Get(int key) {
if (!cache.ContainsKey(key)) {
return -1;
}
Node node = cache[key];
RemoveNode(node);
AddToHead(node);
return node.Val;
}
public void Put(int key, int value) {
if (cache.ContainsKey(key)) {
Node node = cache[key];
RemoveNode(node);
node.Val = value;
AddToHead(node);
} else {
Node node = new Node(key, value);
cache[key] = node;
AddToHead(node);
if (++size > capacity) {
node = tail.Prev;
cache.Remove(node.Key);
RemoveNode(node);
--size;
}
}
}
private void RemoveNode(Node node) {
node.Prev.Next = node.Next;
node.Next.Prev = node.Prev;
}
private void AddToHead(Node node) {
node.Next = head.Next;
node.Prev = head;
head.Next = node;
node.Next.Prev = node;
}
// Node class to represent each entry in the cache.
private class Node {
public int Key;
public int Val;
public Node Prev;
public Node Next;
public Node() {}
public Node(int key, int val) {
Key = key;
Val = val;
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.Get(key);
* obj.Put(key,value);
*/
|
class LRUCache {
private:
struct Node {
int key, val;
Node* prev;
Node* next;
Node(int key, int val)
: key(key)
, val(val)
, prev(nullptr)
, next(nullptr) {}
};
int size;
int capacity;
Node* head;
Node* tail;
unordered_map<int, Node*> cache;
void removeNode(Node* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
void addToHead(Node* node) {
node->next = head->next;
node->prev = head;
head->next->prev = node;
head->next = node;
}
public:
LRUCache(int capacity)
: size(0)
, capacity(capacity) {
head = new Node(0, 0);
tail = new Node(0, 0);
head->next = tail;
tail->prev = head;
}
int get(int key) {
if (!cache.contains(key)) {
return -1;
}
Node* node = cache[key];
removeNode(node);
addToHead(node);
return node->val;
}
void put(int key, int value) {
if (cache.contains(key)) {
Node* node = cache[key];
removeNode(node);
node->val = value;
addToHead(node);
} else {
Node* node = new Node(key, value);
cache[key] = node;
addToHead(node);
if (++size > capacity) {
node = tail->prev;
cache.erase(node->key);
removeNode(node);
--size;
}
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
| null | null |
type Node struct {
key, val int
prev, next *Node
}
type LRUCache struct {
size, capacity int
head, tail *Node
cache map[int]*Node
}
func Constructor(capacity int) LRUCache {
head := &Node{}
tail := &Node{}
head.next = tail
tail.prev = head
return LRUCache{
capacity: capacity,
head: head,
tail: tail,
cache: make(map[int]*Node),
}
}
func (this *LRUCache) Get(key int) int {
if node, exists := this.cache[key]; exists {
this.removeNode(node)
this.addToHead(node)
return node.val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if node, exists := this.cache[key]; exists {
this.removeNode(node)
node.val = value
this.addToHead(node)
} else {
node := &Node{key: key, val: value}
this.cache[key] = node
this.addToHead(node)
if this.size++; this.size > this.capacity {
node = this.tail.prev
delete(this.cache, node.key)
this.removeNode(node)
this.size--
}
}
}
func (this *LRUCache) removeNode(node *Node) {
node.prev.next = node.next
node.next.prev = node.prev
}
func (this *LRUCache) addToHead(node *Node) {
node.next = this.head.next
node.prev = this.head
this.head.next = node
node.next.prev = node
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
|
class Node {
int key, val;
Node prev, next;
Node() {
}
Node(int key, int val) {
this.key = key;
this.val = val;
}
}
class LRUCache {
private int size;
private int capacity;
private Node head = new Node();
private Node tail = new Node();
private Map<Integer, Node> cache = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!cache.containsKey(key)) {
return -1;
}
Node node = cache.get(key);
removeNode(node);
addToHead(node);
return node.val;
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
removeNode(node);
node.val = value;
addToHead(node);
} else {
Node node = new Node(key, value);
cache.put(key, node);
addToHead(node);
if (++size > capacity) {
node = tail.prev;
cache.remove(node.key);
removeNode(node);
--size;
}
}
}
private void removeNode(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void addToHead(Node node) {
node.next = head.next;
node.prev = head;
head.next = node;
node.next.prev = node;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
|
/**
* @param {number} capacity
*/
var LRUCache = function (capacity) {
this.size = 0;
this.capacity = capacity;
this.cache = new Map();
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
if (!this.cache.has(key)) {
return -1;
}
const node = this.cache.get(key);
this.removeNode(node);
this.addToHead(node);
return node.val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
if (this.cache.has(key)) {
const node = this.cache.get(key);
this.removeNode(node);
node.val = value;
this.addToHead(node);
} else {
const node = new Node(key, value);
this.cache.set(key, node);
this.addToHead(node);
if (++this.size > this.capacity) {
const nodeToRemove = this.tail.prev;
this.cache.delete(nodeToRemove.key);
this.removeNode(nodeToRemove);
--this.size;
}
}
};
LRUCache.prototype.removeNode = function (node) {
if (!node) return;
node.prev.next = node.next;
node.next.prev = node.prev;
};
LRUCache.prototype.addToHead = function (node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
};
/**
* @constructor
* @param {number} key
* @param {number} val
*/
function Node(key, val) {
this.key = key;
this.val = val;
this.prev = null;
this.next = null;
}
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
| null | null | null | null | null |
class Node:
def __init__(self, key: int = 0, val: int = 0):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.size = 0
self.capacity = capacity
self.cache = {}
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if key not in self.cache:
return -1
node = self.cache[key]
self.remove_node(node)
self.add_to_head(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.cache:
node = self.cache[key]
self.remove_node(node)
node.val = value
self.add_to_head(node)
else:
node = Node(key, value)
self.cache[key] = node
self.add_to_head(node)
self.size += 1
if self.size > self.capacity:
node = self.tail.prev
self.cache.pop(node.key)
self.remove_node(node)
self.size -= 1
def remove_node(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def add_to_head(self, node):
node.next = self.head.next
node.prev = self.head
self.head.next = node
node.next.prev = node
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
| null |
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
struct Node {
key: i32,
value: i32,
prev: Option<Rc<RefCell<Node>>>,
next: Option<Rc<RefCell<Node>>>,
}
impl Node {
#[inline]
fn new(key: i32, value: i32) -> Self {
Self {
key,
value,
prev: None,
next: None,
}
}
}
struct LRUCache {
capacity: usize,
cache: HashMap<i32, Rc<RefCell<Node>>>,
head: Option<Rc<RefCell<Node>>>,
tail: Option<Rc<RefCell<Node>>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl LRUCache {
fn new(capacity: i32) -> Self {
Self {
capacity: capacity as usize,
cache: HashMap::new(),
head: None,
tail: None,
}
}
fn get(&mut self, key: i32) -> i32 {
match self.cache.get(&key) {
Some(node) => {
let node = Rc::clone(node);
self.remove(&node);
self.push_front(&node);
let value = node.borrow().value;
value
}
None => -1,
}
}
fn put(&mut self, key: i32, value: i32) {
match self.cache.get(&key) {
Some(node) => {
let node = Rc::clone(node);
node.borrow_mut().value = value;
self.remove(&node);
self.push_front(&node);
}
None => {
let node = Rc::new(RefCell::new(Node::new(key, value)));
self.cache.insert(key, Rc::clone(&node));
self.push_front(&node);
if self.cache.len() > self.capacity {
let back_key = self.pop_back().unwrap().borrow().key;
self.cache.remove(&back_key);
}
}
};
}
fn push_front(&mut self, node: &Rc<RefCell<Node>>) {
match self.head.take() {
Some(head) => {
head.borrow_mut().prev = Some(Rc::clone(node));
node.borrow_mut().prev = None;
node.borrow_mut().next = Some(head);
self.head = Some(Rc::clone(node));
}
None => {
self.head = Some(Rc::clone(node));
self.tail = Some(Rc::clone(node));
}
};
}
fn remove(&mut self, node: &Rc<RefCell<Node>>) {
match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) {
(None, None) => {
self.head = None;
self.tail = None;
}
(None, Some(next)) => {
self.head = Some(Rc::clone(next));
next.borrow_mut().prev = None;
}
(Some(prev), None) => {
self.tail = Some(Rc::clone(prev));
prev.borrow_mut().next = None;
}
(Some(prev), Some(next)) => {
next.borrow_mut().prev = Some(Rc::clone(prev));
prev.borrow_mut().next = Some(Rc::clone(next));
}
};
}
fn pop_back(&mut self) -> Option<Rc<RefCell<Node>>> {
match self.tail.take() {
Some(tail) => {
self.remove(&tail);
Some(tail)
}
None => None,
}
}
}
| null | null | null |
class Node {
key: number;
val: number;
prev: Node | null;
next: Node | null;
constructor(key: number, val: number) {
this.key = key;
this.val = val;
this.prev = null;
this.next = null;
}
}
class LRUCache {
private size: number;
private capacity: number;
private head: Node;
private tail: Node;
private cache: Map<number, Node>;
constructor(capacity: number) {
this.size = 0;
this.capacity = capacity;
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
this.cache = new Map();
}
get(key: number): number {
if (!this.cache.has(key)) {
return -1;
}
const node = this.cache.get(key)!;
this.removeNode(node);
this.addToHead(node);
return node.val;
}
put(key: number, value: number): void {
if (this.cache.has(key)) {
const node = this.cache.get(key)!;
this.removeNode(node);
node.val = value;
this.addToHead(node);
} else {
const node = new Node(key, value);
this.cache.set(key, node);
this.addToHead(node);
if (++this.size > this.capacity) {
const nodeToRemove = this.tail.prev!;
this.cache.delete(nodeToRemove.key);
this.removeNode(nodeToRemove);
--this.size;
}
}
}
private removeNode(node: Node): void {
if (!node) return;
node.prev!.next = node.next;
node.next!.prev = node.prev;
}
private addToHead(node: Node): void {
node.next = this.head.next;
node.prev = this.head;
this.head.next!.prev = node;
this.head.next = node;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
|
Alphabet Board Path
|
On an alphabet board, we start at position
(0, 0)
, corresponding to character
board[0][0]
.
Here,
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
, as shown in the diagram below.
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;
'D'
moves our position down one row, if the position exists on the board;
'L'
moves our position left one column, if the position exists on the board;
'R'
moves our position right one column, if the position exists on the board;
'!'
adds the character
board[r][c]
at our current position
(r, c)
to the answer.
(Here, the only positions that exist on the board are positions with letters on them.)
Return a sequence of moves that makes our answer equal to
target
in the minimum number of moves. You may return any path that does so.
Example 1:
Input:
target = "leet"
Output:
"DDR!UURRR!!DDD!"
Example 2:
Input:
target = "code"
Output:
"RR!DDRR!UUL!R!"
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.
| null | null |
class Solution {
public:
string alphabetBoardPath(string target) {
string ans;
int i = 0, j = 0;
for (char& c : target) {
int v = c - 'a';
int x = v / 5, y = v % 5;
while (j > y) {
--j;
ans += 'L';
}
while (i > x) {
--i;
ans += 'U';
}
while (j < y) {
++j;
ans += 'R';
}
while (i < x) {
++i;
ans += 'D';
}
ans += '!';
}
return ans;
}
};
| null | null |
func alphabetBoardPath(target string) string {
ans := []byte{}
var i, j int
for _, c := range target {
v := int(c - 'a')
x, y := v/5, v%5
for j > y {
j--
ans = append(ans, 'L')
}
for i > x {
i--
ans = append(ans, 'U')
}
for j < y {
j++
ans = append(ans, 'R')
}
for i < x {
i++
ans = append(ans, 'D')
}
ans = append(ans, '!')
}
return string(ans)
}
|
class Solution {
public String alphabetBoardPath(String target) {
StringBuilder ans = new StringBuilder();
int i = 0, j = 0;
for (int k = 0; k < target.length(); ++k) {
int v = target.charAt(k) - 'a';
int x = v / 5, y = v % 5;
while (j > y) {
--j;
ans.append('L');
}
while (i > x) {
--i;
ans.append('U');
}
while (j < y) {
++j;
ans.append('R');
}
while (i < x) {
++i;
ans.append('D');
}
ans.append("!");
}
return ans.toString();
}
}
| null | null | null | null | null | null |
class Solution:
def alphabetBoardPath(self, target: str) -> str:
i = j = 0
ans = []
for c in target:
v = ord(c) - ord("a")
x, y = v // 5, v % 5
while j > y:
j -= 1
ans.append("L")
while i > x:
i -= 1
ans.append("U")
while j < y:
j += 1
ans.append("R")
while i < x:
i += 1
ans.append("D")
ans.append("!")
return "".join(ans)
| null | null | null | null | null | null |
Count Subarrays With Fixed Bounds
|
You are given an integer array
nums
and two integers
minK
and
maxK
.
A
fixed-bound subarray
of
nums
is a subarray that satisfies the following conditions:
The
minimum
value in the subarray is equal to
minK
.
The
maximum
value in the subarray is equal to
maxK
.
Return
the
number
of fixed-bound subarrays
.
A
subarray
is a
contiguous
part of an array.
Example 1:
Input:
nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output:
2
Explanation:
The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input:
nums = [1,1,1,1], minK = 1, maxK = 1
Output:
10
Explanation:
Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
2 <= nums.length <= 10
5
1 <= nums[i], minK, maxK <= 10
6
|
long long countSubarrays(int* nums, int numsSize, int minK, int maxK) {
long long ans = 0;
int j1 = -1, j2 = -1, k = -1;
for (int i = 0; i < numsSize; ++i) {
if (nums[i] < minK || nums[i] > maxK) k = i;
if (nums[i] == minK) j1 = i;
if (nums[i] == maxK) j2 = i;
int m = j1 < j2 ? j1 : j2;
if (m > k) ans += (long long) (m - k);
}
return ans;
}
| null |
class Solution {
public:
long long countSubarrays(vector<int>& nums, int minK, int maxK) {
long long ans = 0;
int j1 = -1, j2 = -1, k = -1;
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
if (nums[i] < minK || nums[i] > maxK) {
k = i;
}
if (nums[i] == minK) {
j1 = i;
}
if (nums[i] == maxK) {
j2 = i;
}
ans += max(0, min(j1, j2) - k);
}
return ans;
}
};
| null | null |
func countSubarrays(nums []int, minK int, maxK int) int64 {
ans := 0
j1, j2, k := -1, -1, -1
for i, v := range nums {
if v < minK || v > maxK {
k = i
}
if v == minK {
j1 = i
}
if v == maxK {
j2 = i
}
ans += max(0, min(j1, j2)-k)
}
return int64(ans)
}
|
class Solution {
public long countSubarrays(int[] nums, int minK, int maxK) {
long ans = 0;
int j1 = -1, j2 = -1, k = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] < minK || nums[i] > maxK) {
k = i;
}
if (nums[i] == minK) {
j1 = i;
}
if (nums[i] == maxK) {
j2 = i;
}
ans += Math.max(0, Math.min(j1, j2) - k);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
j1 = j2 = k = -1
ans = 0
for i, v in enumerate(nums):
if v < minK or v > maxK:
k = i
if v == minK:
j1 = i
if v == maxK:
j2 = i
ans += max(0, min(j1, j2) - k)
return ans
| null |
impl Solution {
pub fn count_subarrays(nums: Vec<i32>, min_k: i32, max_k: i32) -> i64 {
let mut ans: i64 = 0;
let mut j1: i64 = -1;
let mut j2: i64 = -1;
let mut k: i64 = -1;
for (i, &v) in nums.iter().enumerate() {
let i = i as i64;
if v < min_k || v > max_k {
k = i;
}
if v == min_k {
j1 = i;
}
if v == max_k {
j2 = i;
}
let m = j1.min(j2);
if m > k {
ans += m - k;
}
}
ans
}
}
| null | null | null |
function countSubarrays(nums: number[], minK: number, maxK: number): number {
let ans = 0;
let [j1, j2, k] = [-1, -1, -1];
for (let i = 0; i < nums.length; ++i) {
if (nums[i] < minK || nums[i] > maxK) k = i;
if (nums[i] === minK) j1 = i;
if (nums[i] === maxK) j2 = i;
ans += Math.max(0, Math.min(j1, j2) - k);
}
return ans;
}
|
Customer Purchasing Behavior Analysis 🔒
|
Table:
Transactions
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| transaction_id | int |
| customer_id | int |
| product_id | int |
| transaction_date | date |
| amount | decimal |
+------------------+---------+
transaction_id is the unique identifier for this table.
Each row of this table contains information about a transaction, including the customer ID, product ID, date, and amount spent.
Table:
Products
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| category | varchar |
| price | decimal |
+-------------+---------+
product_id is the unique identifier for this table.
Each row of this table contains information about a product, including its category and price.
Write a solution to analyze customer purchasing behavior. For
each customer
, calculate:
The total amount spent.
The number of transactions.
The number of
unique
product categories purchased.
The average amount spent.
The
most frequently
purchased product category (if there is a tie, choose the one with the most recent transaction).
A
loyalty score
defined as: (Number of transactions * 10) + (Total amount spent / 100).
Round
total_amount
,
avg_transaction_amount
, and
loyalty_score
to
2
decimal places.
Return
the result table ordered by
loyalty_score
in
descending
order
,
then by
customer_id
in
ascending
order
.
The query result format is in the following example.
Example:
Input:
Transactions
table:
+----------------+-------------+------------+------------------+--------+
| transaction_id | customer_id | product_id | transaction_date | amount |
+----------------+-------------+------------+------------------+--------+
| 1 | 101 | 1 | 2023-01-01 | 100.00 |
| 2 | 101 | 2 | 2023-01-15 | 150.00 |
| 3 | 102 | 1 | 2023-01-01 | 100.00 |
| 4 | 102 | 3 | 2023-01-22 | 200.00 |
| 5 | 101 | 3 | 2023-02-10 | 200.00 |
+----------------+-------------+------------+------------------+--------+
Products
table:
+------------+----------+--------+
| product_id | category | price |
+------------+----------+--------+
| 1 | A | 100.00 |
| 2 | B | 150.00 |
| 3 | C | 200.00 |
+------------+----------+--------+
Output:
+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
| customer_id | total_amount | transaction_count | unique_categories | avg_transaction_amount | top_category | loyalty_score |
+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
| 101 | 450.00 | 3 | 3 | 150.00 | C | 34.50 |
| 102 | 300.00 | 2 | 2 | 150.00 | C | 23.00 |
+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
Explanation:
For customer 101:
Total amount spent: 100.00 + 150.00 + 200.00 = 450.00
Number of transactions: 3
Unique categories: A, B, C (3 categories)
Average transaction amount: 450.00 / 3 = 150.00
Top category: C (Customer 101 made 1 purchase each in categories A, B, and C. Since the count is the same for all categories, we choose the most recent transaction, which is category C on 2023-02-10)
Loyalty score: (3 * 10) + (450.00 / 100) = 34.50
For customer 102:
Total amount spent: 100.00 + 200.00 = 300.00
Number of transactions: 2
Unique categories: A, C (2 categories)
Average transaction amount: 300.00 / 2 = 150.00
Top category: C (Customer 102 made 1 purchase each in categories A and C. Since the count is the same for both categories, we choose the most recent transaction, which is category C on 2023-01-22)
Loyalty score: (2 * 10) + (300.00 / 100) = 23.00
Note:
The output is ordered by loyalty_score in descending order, then by customer_id in ascending order.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
WITH
T AS (
SELECT *
FROM
Transactions
JOIN Products USING (product_id)
),
P AS (
SELECT
customer_id,
category,
COUNT(1) cnt,
MAX(transaction_date) max_date
FROM T
GROUP BY 1, 2
),
R AS (
SELECT
customer_id,
category,
RANK() OVER (
PARTITION BY customer_id
ORDER BY cnt DESC, max_date DESC
) rk
FROM P
)
SELECT
t.customer_id,
ROUND(SUM(amount), 2) total_amount,
COUNT(1) transaction_count,
COUNT(DISTINCT t.category) unique_categories,
ROUND(AVG(amount), 2) avg_transaction_amount,
r.category top_category,
ROUND(COUNT(1) * 10 + SUM(amount) / 100, 2) loyalty_score
FROM
T t
JOIN R r ON t.customer_id = r.customer_id AND r.rk = 1
GROUP BY 1
ORDER BY 7 DESC, 1;
| null | null | null | null | null | null | null | null | null | null |
Maximum Number of Ways to Partition an Array
|
You are given a
0-indexed
integer array
nums
of length
n
. The number of ways to
partition
nums
is the number of
pivot
indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer
k
. You can choose to change the value of
one
element of
nums
to
k
, or to leave the array
unchanged
.
Return
the
maximum
possible number of ways to
partition
nums
to satisfy both conditions after changing
at most
one element
.
Example 1:
Input:
nums = [2,-1,2], k = 3
Output:
1
Explanation:
One optimal approach is to change nums[0] to k. The array becomes [
3
,-1,2].
There is one way to partition the array:
- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.
Example 2:
Input:
nums = [0,0,0], k = 1
Output:
2
Explanation:
The optimal approach is to leave the array unchanged.
There are two ways to partition the array:
- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.
- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.
Example 3:
Input:
nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33
Output:
4
Explanation:
One optimal approach is to change nums[2] to k. The array becomes [22,4,
-33
,-20,-15,15,-16,7,19,-10,0,-13,-14].
There are four ways to partition the array.
Constraints:
n == nums.length
2 <= n <= 10
5
-10
5
<= k, nums[i] <= 10
5
| null | null |
class Solution {
public:
int waysToPartition(vector<int>& nums, int k) {
int n = nums.size();
long long s[n];
s[0] = nums[0];
unordered_map<long long, int> right;
for (int i = 0; i < n - 1; ++i) {
right[s[i]]++;
s[i + 1] = s[i] + nums[i + 1];
}
int ans = 0;
if (s[n - 1] % 2 == 0) {
ans = right[s[n - 1] / 2];
}
unordered_map<long long, int> left;
for (int i = 0; i < n; ++i) {
int d = k - nums[i];
if ((s[n - 1] + d) % 2 == 0) {
int t = left[(s[n - 1] + d) / 2] + right[(s[n - 1] - d) / 2];
ans = max(ans, t);
}
left[s[i]]++;
right[s[i]]--;
}
return ans;
}
};
| null | null |
func waysToPartition(nums []int, k int) (ans int) {
n := len(nums)
s := make([]int, n)
s[0] = nums[0]
right := map[int]int{}
for i := range nums[:n-1] {
right[s[i]]++
s[i+1] = s[i] + nums[i+1]
}
if s[n-1]%2 == 0 {
ans = right[s[n-1]/2]
}
left := map[int]int{}
for i, x := range nums {
d := k - x
if (s[n-1]+d)%2 == 0 {
t := left[(s[n-1]+d)/2] + right[(s[n-1]-d)/2]
if ans < t {
ans = t
}
}
left[s[i]]++
right[s[i]]--
}
return
}
|
class Solution {
public int waysToPartition(int[] nums, int k) {
int n = nums.length;
int[] s = new int[n];
s[0] = nums[0];
Map<Integer, Integer> right = new HashMap<>();
for (int i = 0; i < n - 1; ++i) {
right.merge(s[i], 1, Integer::sum);
s[i + 1] = s[i] + nums[i + 1];
}
int ans = 0;
if (s[n - 1] % 2 == 0) {
ans = right.getOrDefault(s[n - 1] / 2, 0);
}
Map<Integer, Integer> left = new HashMap<>();
for (int i = 0; i < n; ++i) {
int d = k - nums[i];
if ((s[n - 1] + d) % 2 == 0) {
int t = left.getOrDefault((s[n - 1] + d) / 2, 0)
+ right.getOrDefault((s[n - 1] - d) / 2, 0);
ans = Math.max(ans, t);
}
left.merge(s[i], 1, Integer::sum);
right.merge(s[i], -1, Integer::sum);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
n = len(nums)
s = [nums[0]] * n
right = defaultdict(int)
for i in range(1, n):
s[i] = s[i - 1] + nums[i]
right[s[i - 1]] += 1
ans = 0
if s[-1] % 2 == 0:
ans = right[s[-1] // 2]
left = defaultdict(int)
for v, x in zip(s, nums):
d = k - x
if (s[-1] + d) % 2 == 0:
t = left[(s[-1] + d) // 2] + right[(s[-1] - d) // 2]
if ans < t:
ans = t
left[v] += 1
right[v] -= 1
return ans
| null | null | null | null | null | null |
Integer to Roman
|
Seven different symbols represent Roman numerals with the following values:
Symbol
Value
I
1
V
5
X
10
L
50
C
100
D
500
M
1000
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
If the value starts with 4 or 9 use the
subtractive form
representing one symbol subtracted from the following symbol, for example, 4 is 1 (
I
) less than 5 (
V
):
IV
and 9 is 1 (
I
) less than 10 (
X
):
IX
. Only the following subtractive forms are used: 4 (
IV
), 9 (
IX
), 40 (
XL
), 90 (
XC
), 400 (
CD
) and 900 (
CM
).
Only powers of 10 (
I
,
X
,
C
,
M
) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (
V
), 50 (
L
), or 500 (
D
) multiple times. If you need to append a symbol 4 times use the
subtractive form
.
Given an integer, convert it to a Roman numeral.
Example 1:
Input:
num = 3749
Output:
"MMMDCCXLIX"
Explanation:
3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)
700 = DCC as 500 (D) + 100 (C) + 100 (C)
40 = XL as 10 (X) less of 50 (L)
9 = IX as 1 (I) less of 10 (X)
Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places
Example 2:
Input:
num = 58
Output:
"LVIII"
Explanation:
50 = L
8 = VIII
Example 3:
Input:
num = 1994
Output:
"MCMXCIV"
Explanation:
1000 = M
900 = CM
90 = XC
4 = IV
Constraints:
1 <= num <= 3999
|
static const char* cs[] = {
"M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I"};
static const int vs[] = {
1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1};
char* intToRoman(int num) {
static char ans[20];
ans[0] = '\0';
for (int i = 0; i < 13; ++i) {
while (num >= vs[i]) {
num -= vs[i];
strcat(ans, cs[i]);
}
}
return ans;
}
|
public class Solution {
public string IntToRoman(int num) {
List<string> cs = new List<string>{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
List<int> vs = new List<int>{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
StringBuilder ans = new StringBuilder();
for (int i = 0; i < cs.Count; i++) {
while (num >= vs[i]) {
ans.Append(cs[i]);
num -= vs[i];
}
}
return ans.ToString();
}
}
|
class Solution {
public:
string intToRoman(int num) {
vector<string> cs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
vector<int> vs = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string ans;
for (int i = 0; i < cs.size(); ++i) {
while (num >= vs[i]) {
num -= vs[i];
ans += cs[i];
}
}
return ans;
}
};
| null | null |
func intToRoman(num int) string {
cs := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
vs := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
ans := &strings.Builder{}
for i, v := range vs {
for num >= v {
num -= v
ans.WriteString(cs[i])
}
}
return ans.String()
}
|
class Solution {
public String intToRoman(int num) {
List<String> cs
= List.of("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I");
List<Integer> vs = List.of(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);
StringBuilder ans = new StringBuilder();
for (int i = 0, n = cs.size(); i < n; ++i) {
while (num >= vs.get(i)) {
num -= vs.get(i);
ans.append(cs.get(i));
}
}
return ans.toString();
}
}
| null | null | null | null |
class Solution {
/**
* @param Integer $num
* @return String
*/
function intToRoman($num) {
$cs = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
$vs = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
$ans = '';
foreach ($vs as $i => $v) {
while ($num >= $v) {
$num -= $v;
$ans .= $cs[$i];
}
}
return $ans;
}
}
| null |
class Solution:
def intToRoman(self, num: int) -> str:
cs = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
vs = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
ans = []
for c, v in zip(cs, vs):
while num >= v:
num -= v
ans.append(c)
return ''.join(ans)
| null |
impl Solution {
pub fn int_to_roman(num: i32) -> String {
let cs = [
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I",
];
let vs = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let mut num = num;
let mut ans = String::new();
for (i, &v) in vs.iter().enumerate() {
while num >= v {
num -= v;
ans.push_str(cs[i]);
}
}
ans
}
}
| null | null | null |
function intToRoman(num: number): string {
const cs: string[] = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
const vs: number[] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const ans: string[] = [];
for (let i = 0; i < vs.length; ++i) {
while (num >= vs[i]) {
num -= vs[i];
ans.push(cs[i]);
}
}
return ans.join('');
}
|
Swap Nodes in Pairs
|
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input:
head = [1,2,3,4]
Output:
[2,1,4,3]
Explanation:
Example 2:
Input:
head = []
Output:
[]
Example 3:
Input:
head = [1]
Output:
[1]
Example 4:
Input:
head = [1,2,3]
Output:
[2,1,3]
Constraints:
The number of nodes in the list is in the range
[0, 100]
.
0 <= Node.val <= 100
| null |
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode SwapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur is not null && cur.next is not null) {
ListNode t = cur.next;
cur.next = t.next;
t.next = cur;
pre.next = t;
pre = cur;
cur = cur.next;
}
return dummy.next;
}
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* pre = dummy;
ListNode* cur = head;
while (cur && cur->next) {
ListNode* t = cur->next;
cur->next = t->next;
t->next = cur;
pre->next = t;
pre = cur;
cur = cur->next;
}
return dummy->next;
}
};
| null | null |
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{Next: head}
pre, cur := dummy, head
for cur != nil && cur.Next != nil {
t := cur.Next
cur.Next = t.Next
t.Next = cur
pre.Next = t
pre, cur = cur, cur.Next
}
return dummy.Next
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode t = cur.next;
cur.next = t.next;
t.next = cur;
pre.next = t;
pre = cur;
cur = cur.next;
}
return dummy.next;
}
}
|
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
const dummy = new ListNode(0, head);
let [pre, cur] = [dummy, head];
while (cur && cur.next) {
const t = cur.next;
cur.next = t.next;
t.next = cur;
pre.next = t;
[pre, cur] = [cur, cur.next];
}
return dummy.next;
};
| null | null | null |
# Definition for singly-linked list.
# class ListNode {
# public $val;
# public $next;
# public function __construct($val = 0, $next = null)
# {
# $this->val = $val;
# $this->next = $next;
# }
# }
class Solution {
/**
* @param ListNode $head
* @return ListNode
*/
function swapPairs($head) {
$dummy = new ListNode(0);
$dummy->next = $head;
$prev = $dummy;
while ($head !== null && $head->next !== null) {
$first = $head;
$second = $head->next;
$first->next = $second->next;
$second->next = $first;
$prev->next = $second;
$prev = $first;
$head = $first->next;
}
return $dummy->next;
}
}
| null |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(next=head)
pre, cur = dummy, head
while cur and cur.next:
t = cur.next
cur.next = t.next
t.next = cur
pre.next = t
pre, cur = cur, cur.next
return dummy.next
|
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @return {ListNode}
def swap_pairs(head)
dummy = ListNode.new(0, head)
pre = dummy
cur = head
while !cur.nil? && !cur.next.nil?
t = cur.next
cur.next = t.next
t.next = cur
pre.next = t
pre = cur
cur = cur.next
end
dummy.next
end
|
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode { val: 0, next: head }));
let mut cur = dummy.as_mut().unwrap();
while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() {
cur.next = {
let mut b = cur.next.as_mut().unwrap().next.take();
cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take();
let a = cur.next.take();
b.as_mut().unwrap().next = a;
b
};
cur = cur.next.as_mut().unwrap().next.as_mut().unwrap();
}
dummy.unwrap().next
}
}
| null | null | null |
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function swapPairs(head: ListNode | null): ListNode | null {
const dummy = new ListNode(0, head);
let [pre, cur] = [dummy, head];
while (cur && cur.next) {
const t = cur.next;
cur.next = t.next;
t.next = cur;
pre.next = t;
[pre, cur] = [cur, cur.next];
}
return dummy.next;
}
|
Check if Array Is Sorted and Rotated
|
Given an array
nums
, return
true
if the array was originally sorted in non-decreasing order, then rotated
some
number of positions (including zero)
. Otherwise, return
false
.
There may be
duplicates
in the original array.
Note:
An array
A
rotated by
x
positions results in an array
B
of the same length such that
B[i] == A[(i+x) % A.length]
for every valid index
i
.
Example 1:
Input:
nums = [3,4,5,1,2]
Output:
true
Explanation:
[1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2].
Example 2:
Input:
nums = [2,1,3,4]
Output:
false
Explanation:
There is no sorted array once rotated that can make nums.
Example 3:
Input:
nums = [1,2,3]
Output:
true
Explanation:
[1,2,3] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
|
bool check(int* nums, int numsSize) {
int count = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] > nums[(i + 1) % numsSize]) {
count++;
}
}
return count <= 1;
}
| null |
class Solution {
public:
bool check(vector<int>& nums) {
int cnt = 0;
for (int i = 0, n = nums.size(); i < n; ++i) {
cnt += nums[i] > (nums[(i + 1) % n]);
}
return cnt <= 1;
}
};
| null | null |
func check(nums []int) bool {
cnt := 0
for i, v := range nums {
if v > nums[(i+1)%len(nums)] {
cnt++
}
}
return cnt <= 1
}
|
class Solution {
public boolean check(int[] nums) {
int cnt = 0;
for (int i = 0, n = nums.length; i < n; ++i) {
if (nums[i] > nums[(i + 1) % n]) {
++cnt;
}
}
return cnt <= 1;
}
}
| null | null | null | null | null | null |
class Solution:
def check(self, nums: List[int]) -> bool:
return sum(nums[i - 1] > v for i, v in enumerate(nums)) <= 1
| null |
impl Solution {
pub fn check(nums: Vec<i32>) -> bool {
let n = nums.len();
let mut count = 0;
for i in 0..n {
if nums[i] > nums[(i + 1) % n] {
count += 1;
}
}
count <= 1
}
}
| null | null | null |
function check(nums: number[]): boolean {
const n = nums.length;
return nums.reduce((r, v, i) => r + (v > nums[(i + 1) % n] ? 1 : 0), 0) <= 1;
}
|
Maximize Greatness of an Array
|
You are given a 0-indexed integer array
nums
. You are allowed to permute
nums
into a new array
perm
of your choosing.
We define the
greatness
of
nums
be the number of indices
0 <= i < nums.length
for which
perm[i] > nums[i]
.
Return
the
maximum
possible greatness you can achieve after permuting
nums
.
Example 1:
Input:
nums = [1,3,5,2,1,3,1]
Output:
4
Explanation:
One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.
Example 2:
Input:
nums = [1,2,3,4]
Output:
3
Explanation:
We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] <= 10
9
| null | null |
class Solution {
public:
int maximizeGreatness(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i = 0;
for (int x : nums) {
i += x > nums[i];
}
return i;
}
};
| null | null |
func maximizeGreatness(nums []int) int {
sort.Ints(nums)
i := 0
for _, x := range nums {
if x > nums[i] {
i++
}
}
return i
}
|
class Solution {
public int maximizeGreatness(int[] nums) {
Arrays.sort(nums);
int i = 0;
for (int x : nums) {
if (x > nums[i]) {
++i;
}
}
return i;
}
}
| null | null | null | null | null | null |
class Solution:
def maximizeGreatness(self, nums: List[int]) -> int:
nums.sort()
i = 0
for x in nums:
i += x > nums[i]
return i
| null | null | null | null | null |
function maximizeGreatness(nums: number[]): number {
nums.sort((a, b) => a - b);
let i = 0;
for (const x of nums) {
if (x > nums[i]) {
i += 1;
}
}
return i;
}
|
Count Substrings That Can Be Rearranged to Contain a String I
|
You are given two strings
word1
and
word2
.
A string
x
is called
valid
if
x
can be rearranged to have
word2
as a
prefix
.
Return the total number of
valid
substrings
of
word1
.
Example 1:
Input:
word1 = "bcca", word2 = "abc"
Output:
1
Explanation:
The only valid substring is
"bcca"
which can be rearranged to
"abcc"
having
"abc"
as a prefix.
Example 2:
Input:
word1 = "abcabc", word2 = "abc"
Output:
10
Explanation:
All the substrings except substrings of size 1 and size 2 are valid.
Example 3:
Input:
word1 = "abcabc", word2 = "aaabc"
Output:
0
Constraints:
1 <= word1.length <= 10
5
1 <= word2.length <= 10
4
word1
and
word2
consist only of lowercase English letters.
| null | null |
class Solution {
public:
long long validSubstringCount(string word1, string word2) {
if (word1.size() < word2.size()) {
return 0;
}
int cnt[26]{};
int need = 0;
for (char& c : word2) {
if (++cnt[c - 'a'] == 1) {
++need;
}
}
long long ans = 0;
int win[26]{};
int l = 0;
for (char& c : word1) {
int i = c - 'a';
if (++win[i] == cnt[i]) {
--need;
}
while (need == 0) {
i = word1[l] - 'a';
if (win[i] == cnt[i]) {
++need;
}
--win[i];
++l;
}
ans += l;
}
return ans;
}
};
| null | null |
func validSubstringCount(word1 string, word2 string) (ans int64) {
if len(word1) < len(word2) {
return 0
}
cnt := [26]int{}
need := 0
for _, c := range word2 {
cnt[c-'a']++
if cnt[c-'a'] == 1 {
need++
}
}
win := [26]int{}
l := 0
for _, c := range word1 {
i := int(c - 'a')
win[i]++
if win[i] == cnt[i] {
need--
}
for need == 0 {
i = int(word1[l] - 'a')
if win[i] == cnt[i] {
need++
}
win[i]--
l++
}
ans += int64(l)
}
return
}
|
class Solution {
public long validSubstringCount(String word1, String word2) {
if (word1.length() < word2.length()) {
return 0;
}
int[] cnt = new int[26];
int need = 0;
for (int i = 0; i < word2.length(); ++i) {
if (++cnt[word2.charAt(i) - 'a'] == 1) {
++need;
}
}
long ans = 0;
int[] win = new int[26];
for (int l = 0, r = 0; r < word1.length(); ++r) {
int c = word1.charAt(r) - 'a';
if (++win[c] == cnt[c]) {
--need;
}
while (need == 0) {
c = word1.charAt(l) - 'a';
if (win[c] == cnt[c]) {
++need;
}
--win[c];
++l;
}
ans += l;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:
if len(word1) < len(word2):
return 0
cnt = Counter(word2)
need = len(cnt)
ans = l = 0
win = Counter()
for c in word1:
win[c] += 1
if win[c] == cnt[c]:
need -= 1
while need == 0:
if win[word1[l]] == cnt[word1[l]]:
need += 1
win[word1[l]] -= 1
l += 1
ans += l
return ans
| null | null | null | null | null |
function validSubstringCount(word1: string, word2: string): number {
if (word1.length < word2.length) {
return 0;
}
const cnt: number[] = Array(26).fill(0);
let need: number = 0;
for (const c of word2) {
if (++cnt[c.charCodeAt(0) - 97] === 1) {
++need;
}
}
const win: number[] = Array(26).fill(0);
let [ans, l] = [0, 0];
for (const c of word1) {
const i = c.charCodeAt(0) - 97;
if (++win[i] === cnt[i]) {
--need;
}
while (need === 0) {
const j = word1[l].charCodeAt(0) - 97;
if (win[j] === cnt[j]) {
++need;
}
--win[j];
++l;
}
ans += l;
}
return ans;
}
|
Filter Restaurants by Vegan-Friendly, Price and Distance
|
Given the array
restaurants
where
restaurants[i] = [id
i
, rating
i
, veganFriendly
i
, price
i
, distance
i
]
. You have to filter the restaurants using three filters.
The
veganFriendly
filter will be either
true
(meaning you should only include restaurants with
veganFriendly
i
set to true) or
false
(meaning you can include any restaurant). In addition, you have the filters
maxPrice
and
maxDistance
which are the maximum value for price and distance of restaurants you should consider respectively.
Return the array of restaurant
IDs
after filtering, ordered by
rating
from highest to lowest. For restaurants with the same rating, order them by
id
from highest to lowest. For simplicity
veganFriendly
i
and
veganFriendly
take value
1
when it is
true
, and
0
when it is
false
.
Example 1:
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
Output:
[3,1,5]
Explanation:
The restaurants are:
Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1]
After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).
Example 2:
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
Output:
[4,3,2,1,5]
Explanation:
The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.
Example 3:
Input:
restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
Output:
[4,5]
Constraints:
1 <= restaurants.length <= 10^4
restaurants[i].length == 5
1 <= id
i
, rating
i
, price
i
, distance
i
<= 10^5
1 <= maxPrice, maxDistance <= 10^5
veganFriendly
i
and
veganFriendly
are 0 or 1.
All
id
i
are distinct.
| null | null |
class Solution {
public:
vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
sort(restaurants.begin(), restaurants.end(), [](const vector<int>& a, const vector<int>& b) {
if (a[1] != b[1]) {
return a[1] > b[1];
}
return a[0] > b[0];
});
vector<int> ans;
for (auto& r : restaurants) {
if (r[2] >= veganFriendly && r[3] <= maxPrice && r[4] <= maxDistance) {
ans.push_back(r[0]);
}
}
return ans;
}
};
| null | null |
func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, maxDistance int) (ans []int) {
sort.Slice(restaurants, func(i, j int) bool {
a, b := restaurants[i], restaurants[j]
if a[1] != b[1] {
return a[1] > b[1]
}
return a[0] > b[0]
})
for _, r := range restaurants {
if r[2] >= veganFriendly && r[3] <= maxPrice && r[4] <= maxDistance {
ans = append(ans, r[0])
}
}
return
}
|
class Solution {
public List<Integer> filterRestaurants(
int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
Arrays.sort(restaurants, (a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]);
List<Integer> ans = new ArrayList<>();
for (int[] r : restaurants) {
if (r[2] >= veganFriendly && r[3] <= maxPrice && r[4] <= maxDistance) {
ans.add(r[0]);
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def filterRestaurants(
self,
restaurants: List[List[int]],
veganFriendly: int,
maxPrice: int,
maxDistance: int,
) -> List[int]:
restaurants.sort(key=lambda x: (-x[1], -x[0]))
ans = []
for idx, _, vegan, price, dist in restaurants:
if vegan >= veganFriendly and price <= maxPrice and dist <= maxDistance:
ans.append(idx)
return ans
| null | null | null | null | null |
function filterRestaurants(
restaurants: number[][],
veganFriendly: number,
maxPrice: number,
maxDistance: number,
): number[] {
restaurants.sort((a, b) => (a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]));
const ans: number[] = [];
for (const [id, _, vegan, price, distance] of restaurants) {
if (vegan >= veganFriendly && price <= maxPrice && distance <= maxDistance) {
ans.push(id);
}
}
return ans;
}
|
Path Sum III
|
Given the
root
of a binary tree and an integer
targetSum
, return
the number of paths where the sum of the values along the path equals
targetSum
.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
Input:
root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output:
3
Explanation:
The paths that sum to 8 are shown.
Example 2:
Input:
root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output:
3
Constraints:
The number of nodes in the tree is in the range
[0, 1000]
.
-10
9
<= Node.val <= 10
9
-1000 <= targetSum <= 1000
| null |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int PathSum(TreeNode root, int targetSum) {
Dictionary<long, int> cnt = new Dictionary<long, int>();
int Dfs(TreeNode node, long s) {
if (node == null) {
return 0;
}
s += node.val;
int ans = cnt.GetValueOrDefault(s - targetSum, 0);
cnt[s] = cnt.GetValueOrDefault(s, 0) + 1;
ans += Dfs(node.left, s);
ans += Dfs(node.right, s);
cnt[s]--;
return ans;
}
cnt[0] = 1;
return Dfs(root, 0);
}
}
|
/**
* 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 pathSum(TreeNode* root, int targetSum) {
unordered_map<long long, int> cnt;
cnt[0] = 1;
auto dfs = [&](this auto&& dfs, TreeNode* node, long long s) -> int {
if (!node) {
return 0;
}
s += node->val;
int ans = cnt[s - targetSum];
++cnt[s];
ans += dfs(node->left, s) + dfs(node->right, s);
--cnt[s];
return ans;
};
return dfs(root, 0);
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) int {
cnt := map[int]int{0: 1}
var dfs func(*TreeNode, int) int
dfs = func(node *TreeNode, s int) int {
if node == nil {
return 0
}
s += node.Val
ans := cnt[s-targetSum]
cnt[s]++
ans += dfs(node.Left, s) + dfs(node.Right, s)
cnt[s]--
return ans
}
return dfs(root, 0)
}
|
/**
* 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 Map<Long, Integer> cnt = new HashMap<>();
private int targetSum;
public int pathSum(TreeNode root, int targetSum) {
cnt.put(0L, 1);
this.targetSum = targetSum;
return dfs(root, 0);
}
private int dfs(TreeNode node, long s) {
if (node == null) {
return 0;
}
s += node.val;
int ans = cnt.getOrDefault(s - targetSum, 0);
cnt.merge(s, 1, Integer::sum);
ans += dfs(node.left, s);
ans += dfs(node.right, s);
cnt.merge(s, -1, Integer::sum);
return ans;
}
}
|
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {number}
*/
var pathSum = function (root, targetSum) {
const cnt = new Map();
const dfs = (node, s) => {
if (!node) {
return 0;
}
s += node.val;
let ans = cnt.get(s - targetSum) || 0;
cnt.set(s, (cnt.get(s) || 0) + 1);
ans += dfs(node.left, s);
ans += dfs(node.right, s);
cnt.set(s, cnt.get(s) - 1);
return ans;
};
cnt.set(0, 1);
return dfs(root, 0);
};
| 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
def dfs(node, s):
if node is None:
return 0
s += node.val
ans = cnt[s - targetSum]
cnt[s] += 1
ans += dfs(node.left, s)
ans += dfs(node.right, s)
cnt[s] -= 1
return ans
cnt = Counter({0: 1})
return dfs(root, 0)
| 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::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
impl Solution {
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> i32 {
let mut cnt = HashMap::new();
cnt.insert(0, 1);
fn dfs(node: Option<Rc<RefCell<TreeNode>>>, s: i64, target: i64, cnt: &mut HashMap<i64, i32>) -> i32 {
if let Some(n) = node {
let n = n.borrow();
let s = s + n.val as i64;
let ans = cnt.get(&(s - target)).copied().unwrap_or(0);
*cnt.entry(s).or_insert(0) += 1;
let ans = ans + dfs(n.left.clone(), s, target, cnt) + dfs(n.right.clone(), s, target, cnt);
*cnt.get_mut(&s).unwrap() -= 1;
ans
} else {
0
}
}
dfs(root, 0, target_sum as i64, &mut cnt)
}
}
| 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 pathSum(root: TreeNode | null, targetSum: number): number {
const cnt: Map<number, number> = new Map();
const dfs = (node: TreeNode | null, s: number): number => {
if (!node) {
return 0;
}
s += node.val;
let ans = cnt.get(s - targetSum) ?? 0;
cnt.set(s, (cnt.get(s) ?? 0) + 1);
ans += dfs(node.left, s);
ans += dfs(node.right, s);
cnt.set(s, (cnt.get(s) ?? 0) - 1);
return ans;
};
cnt.set(0, 1);
return dfs(root, 0);
}
|
Orderly Queue
|
You are given a string
s
and an integer
k
. You can choose one of the first
k
letters of
s
and append it at the end of the string.
Return
the lexicographically smallest string you could have after applying the mentioned step any number of moves
.
Example 1:
Input:
s = "cba", k = 1
Output:
"acb"
Explanation:
In the first move, we move the 1
st
character 'c' to the end, obtaining the string "bac".
In the second move, we move the 1
st
character 'b' to the end, obtaining the final result "acb".
Example 2:
Input:
s = "baaca", k = 3
Output:
"aaabc"
Explanation:
In the first move, we move the 1
st
character 'b' to the end, obtaining the string "aacab".
In the second move, we move the 3
rd
character 'c' to the end, obtaining the final result "aaabc".
Constraints:
1 <= k <= s.length <= 1000
s
consist of lowercase English letters.
| null | null |
class Solution {
public:
string orderlyQueue(string s, int k) {
if (k == 1) {
string ans = s;
for (int i = 0; i < s.size() - 1; ++i) {
s = s.substr(1) + s[0];
if (s < ans) ans = s;
}
return ans;
}
sort(s.begin(), s.end());
return s;
}
};
| null | null |
func orderlyQueue(s string, k int) string {
if k == 1 {
ans := s
for i := 0; i < len(s)-1; i++ {
s = s[1:] + s[:1]
if s < ans {
ans = s
}
}
return ans
}
t := []byte(s)
sort.Slice(t, func(i, j int) bool { return t[i] < t[j] })
return string(t)
}
|
class Solution {
public String orderlyQueue(String s, int k) {
if (k == 1) {
String ans = s;
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < s.length() - 1; ++i) {
sb.append(sb.charAt(0)).deleteCharAt(0);
if (sb.toString().compareTo(ans) < 0) {
ans = sb.toString();
}
}
return ans;
}
char[] cs = s.toCharArray();
Arrays.sort(cs);
return String.valueOf(cs);
}
}
| null | null | null | null | null | null |
class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k == 1:
ans = s
for _ in range(len(s) - 1):
s = s[1:] + s[0]
ans = min(ans, s)
return ans
return "".join(sorted(s))
| null | null | null | null | null |
function orderlyQueue(s: string, k: number): string {
if (k > 1) {
return [...s].sort().join('');
}
const n = s.length;
let min = s;
for (let i = 1; i < n; i++) {
const t = s.slice(i) + s.slice(0, i);
if (t < min) {
min = t;
}
}
return min;
}
|
Maximum Number of Groups Getting Fresh Donuts
|
There is a donuts shop that bakes donuts in batches of
batchSize
. They have a rule where they must serve
all
of the donuts of a batch before serving any donuts of the next batch. You are given an integer
batchSize
and an integer array
groups
, where
groups[i]
denotes that there is a group of
groups[i]
customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
You can freely rearrange the ordering of the groups. Return
the
maximum
possible number of happy groups after rearranging the groups.
Example 1:
Input:
batchSize = 3, groups = [1,2,3,4,5,6]
Output:
4
Explanation:
You can arrange the groups as [6,2,4,5,1,3]. Then the 1
st
, 2
nd
, 4
th
, and 6
th
groups will be happy.
Example 2:
Input:
batchSize = 4, groups = [1,3,2,5,2,2,1,6]
Output:
4
Constraints:
1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 10
9
| null | null |
class Solution {
public:
int maxHappyGroups(int batchSize, vector<int>& groups) {
using ll = long long;
unordered_map<ll, int> f;
ll state = 0;
int ans = 0;
for (auto& v : groups) {
int i = v % batchSize;
ans += i == 0;
if (i) {
state += 1ll << (i * 5);
}
}
function<int(ll, int)> dfs = [&](ll state, int mod) {
if (f.count(state)) {
return f[state];
}
int res = 0;
int x = mod == 0;
for (int i = 1; i < batchSize; ++i) {
if (state >> (i * 5) & 31) {
int t = dfs(state - (1ll << (i * 5)), (mod + i) % batchSize);
res = max(res, t + x);
}
}
return f[state] = res;
};
ans += dfs(state, 0);
return ans;
}
};
| null | null |
func maxHappyGroups(batchSize int, groups []int) (ans int) {
state := 0
for _, v := range groups {
i := v % batchSize
if i == 0 {
ans++
} else {
state += 1 << (i * 5)
}
}
f := map[int]int{}
var dfs func(int, int) int
dfs = func(state, mod int) int {
if v, ok := f[state]; ok {
return v
}
res := 0
x := 0
if mod == 0 {
x = 1
}
for i := 1; i < batchSize; i++ {
if state>>(i*5)&31 != 0 {
t := dfs(state-1<<(i*5), (mod+i)%batchSize)
res = max(res, t+x)
}
}
f[state] = res
return res
}
ans += dfs(state, 0)
return
}
|
class Solution {
private Map<Long, Integer> f = new HashMap<>();
private int size;
public int maxHappyGroups(int batchSize, int[] groups) {
size = batchSize;
int ans = 0;
long state = 0;
for (int g : groups) {
int i = g % size;
if (i == 0) {
++ans;
} else {
state += 1l << (i * 5);
}
}
ans += dfs(state, 0);
return ans;
}
private int dfs(long state, int mod) {
if (f.containsKey(state)) {
return f.get(state);
}
int res = 0;
for (int i = 1; i < size; ++i) {
if ((state >> (i * 5) & 31) != 0) {
int t = dfs(state - (1l << (i * 5)), (mod + i) % size);
res = Math.max(res, t + (mod == 0 ? 1 : 0));
}
}
f.put(state, res);
return res;
}
}
| null | null | null | null | null | null |
class Solution:
def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:
@cache
def dfs(state, x):
if state == mask:
return 0
vis = [False] * batchSize
res = 0
for i, v in enumerate(g):
if state >> i & 1 == 0 and not vis[v]:
vis[v] = True
y = (x + v) % batchSize
res = max(res, dfs(state | 1 << i, y))
return res + (x == 0)
g = [v % batchSize for v in groups if v % batchSize]
mask = (1 << len(g)) - 1
return len(groups) - len(g) + dfs(0, 0)
| null | null | null | null | null | null |
Find K-Length Substrings With No Repeated Characters 🔒
|
Given a string
s
and an integer
k
, return
the number of substrings in
s
of length
k
with no repeated characters
.
Example 1:
Input:
s = "havefunonleetcode", k = 5
Output:
6
Explanation:
There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
Example 2:
Input:
s = "home", k = 5
Output:
0
Explanation:
Notice k can be larger than the length of s. In this case, it is not possible to find any substring.
Constraints:
1 <= s.length <= 10
4
s
consists of lowercase English letters.
1 <= k <= 10
4
| null | null |
class Solution {
public:
int numKLenSubstrNoRepeats(string s, int k) {
int n = s.size();
if (n < k) {
return 0;
}
unordered_map<char, int> cnt;
for (int i = 0; i < k; ++i) {
++cnt[s[i]];
}
int ans = cnt.size() == k;
for (int i = k; i < n; ++i) {
++cnt[s[i]];
if (--cnt[s[i - k]] == 0) {
cnt.erase(s[i - k]);
}
ans += cnt.size() == k;
}
return ans;
}
};
| null | null |
func numKLenSubstrNoRepeats(s string, k int) (ans int) {
n := len(s)
if n < k {
return
}
cnt := map[byte]int{}
for i := 0; i < k; i++ {
cnt[s[i]]++
}
if len(cnt) == k {
ans++
}
for i := k; i < n; i++ {
cnt[s[i]]++
cnt[s[i-k]]--
if cnt[s[i-k]] == 0 {
delete(cnt, s[i-k])
}
if len(cnt) == k {
ans++
}
}
return
}
|
class Solution {
public int numKLenSubstrNoRepeats(String s, int k) {
int n = s.length();
if (n < k) {
return 0;
}
Map<Character, Integer> cnt = new HashMap<>(k);
for (int i = 0; i < k; ++i) {
cnt.merge(s.charAt(i), 1, Integer::sum);
}
int ans = cnt.size() == k ? 1 : 0;
for (int i = k; i < n; ++i) {
cnt.merge(s.charAt(i), 1, Integer::sum);
if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) {
cnt.remove(s.charAt(i - k));
}
ans += cnt.size() == k ? 1 : 0;
}
return ans;
}
}
| null | null | null | null |
class Solution {
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function numKLenSubstrNoRepeats($s, $k) {
$n = strlen($s);
if ($n < $k) {
return 0;
}
$cnt = [];
for ($i = 0; $i < $k; ++$i) {
if (!isset($cnt[$s[$i]])) {
$cnt[$s[$i]] = 1;
} else {
$cnt[$s[$i]]++;
}
}
$ans = count($cnt) == $k ? 1 : 0;
for ($i = $k; $i < $n; ++$i) {
if (!isset($cnt[$s[$i]])) {
$cnt[$s[$i]] = 1;
} else {
$cnt[$s[$i]]++;
}
if ($cnt[$s[$i - $k]] - 1 == 0) {
unset($cnt[$s[$i - $k]]);
} else {
$cnt[$s[$i - $k]]--;
}
$ans += count($cnt) == $k ? 1 : 0;
}
return $ans;
}
}
| null |
class Solution:
def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:
cnt = Counter(s[:k])
ans = int(len(cnt) == k)
for i in range(k, len(s)):
cnt[s[i]] += 1
cnt[s[i - k]] -= 1
if cnt[s[i - k]] == 0:
cnt.pop(s[i - k])
ans += int(len(cnt) == k)
return ans
| null | null | null | null | null |
function numKLenSubstrNoRepeats(s: string, k: number): number {
const n = s.length;
if (n < k) {
return 0;
}
const cnt: Map<string, number> = new Map();
for (let i = 0; i < k; ++i) {
cnt.set(s[i], (cnt.get(s[i]) ?? 0) + 1);
}
let ans = cnt.size === k ? 1 : 0;
for (let i = k; i < n; ++i) {
cnt.set(s[i], (cnt.get(s[i]) ?? 0) + 1);
cnt.set(s[i - k], (cnt.get(s[i - k]) ?? 0) - 1);
if (cnt.get(s[i - k]) === 0) {
cnt.delete(s[i - k]);
}
ans += cnt.size === k ? 1 : 0;
}
return ans;
}
|
Find All Possible Stable Binary Arrays I
|
You are given 3 positive integers
zero
,
one
, and
limit
.
A
binary array
arr
is called
stable
if:
The number of occurrences of 0 in
arr
is
exactly
zero
.
The number of occurrences of 1 in
arr
is
exactly
one
.
Each
subarray
of
arr
with a size greater than
limit
must contain
both
0 and 1.
Return the
total
number of
stable
binary arrays.
Since the answer may be very large, return it
modulo
10
9
+ 7
.
Example 1:
Input:
zero = 1, one = 1, limit = 2
Output:
2
Explanation:
The two possible stable binary arrays are
[1,0]
and
[0,1]
, as both arrays have a single 0 and a single 1, and no subarray has a length greater than 2.
Example 2:
Input:
zero = 1, one = 2, limit = 1
Output:
1
Explanation:
The only possible stable binary array is
[1,0,1]
.
Note that the binary arrays
[1,1,0]
and
[0,1,1]
have subarrays of length 2 with identical elements, hence, they are not stable.
Example 3:
Input:
zero = 3, one = 3, limit = 2
Output:
14
Explanation:
All the possible stable binary arrays are
[0,0,1,0,1,1]
,
[0,0,1,1,0,1]
,
[0,1,0,0,1,1]
,
[0,1,0,1,0,1]
,
[0,1,0,1,1,0]
,
[0,1,1,0,0,1]
,
[0,1,1,0,1,0]
,
[1,0,0,1,0,1]
,
[1,0,0,1,1,0]
,
[1,0,1,0,0,1]
,
[1,0,1,0,1,0]
,
[1,0,1,1,0,0]
,
[1,1,0,0,1,0]
, and
[1,1,0,1,0,0]
.
Constraints:
1 <= zero, one, limit <= 200
| null | null |
class Solution {
public:
int numberOfStableArrays(int zero, int one, int limit) {
const int mod = 1e9 + 7;
using ll = long long;
ll f[zero + 1][one + 1][2];
memset(f, 0, sizeof(f));
for (int i = 1; i <= min(zero, limit); ++i) {
f[i][0][0] = 1;
}
for (int j = 1; j <= min(one, limit); ++j) {
f[0][j][1] = 1;
}
for (int i = 1; i <= zero; ++i) {
for (int j = 1; j <= one; ++j) {
ll x = i - limit - 1 < 0 ? 0 : f[i - limit - 1][j][1];
ll y = j - limit - 1 < 0 ? 0 : f[i][j - limit - 1][0];
f[i][j][0] = (f[i - 1][j][0] + f[i - 1][j][1] - x + mod) % mod;
f[i][j][1] = (f[i][j - 1][0] + f[i][j - 1][1] - y + mod) % mod;
}
}
return (f[zero][one][0] + f[zero][one][1]) % mod;
}
};
| null | null |
func numberOfStableArrays(zero int, one int, limit int) int {
const mod int = 1e9 + 7
f := make([][][2]int, zero+1)
for i := range f {
f[i] = make([][2]int, one+1)
}
for i := 1; i <= min(zero, limit); i++ {
f[i][0][0] = 1
}
for j := 1; j <= min(one, limit); j++ {
f[0][j][1] = 1
}
for i := 1; i <= zero; i++ {
for j := 1; j <= one; j++ {
f[i][j][0] = (f[i-1][j][0] + f[i-1][j][1]) % mod
if i-limit-1 >= 0 {
f[i][j][0] = (f[i][j][0] - f[i-limit-1][j][1] + mod) % mod
}
f[i][j][1] = (f[i][j-1][0] + f[i][j-1][1]) % mod
if j-limit-1 >= 0 {
f[i][j][1] = (f[i][j][1] - f[i][j-limit-1][0] + mod) % mod
}
}
}
return (f[zero][one][0] + f[zero][one][1]) % mod
}
|
class Solution {
public int numberOfStableArrays(int zero, int one, int limit) {
final int mod = (int) 1e9 + 7;
long[][][] f = new long[zero + 1][one + 1][2];
for (int i = 1; i <= Math.min(zero, limit); ++i) {
f[i][0][0] = 1;
}
for (int j = 1; j <= Math.min(one, limit); ++j) {
f[0][j][1] = 1;
}
for (int i = 1; i <= zero; ++i) {
for (int j = 1; j <= one; ++j) {
long x = i - limit - 1 < 0 ? 0 : f[i - limit - 1][j][1];
long y = j - limit - 1 < 0 ? 0 : f[i][j - limit - 1][0];
f[i][j][0] = (f[i - 1][j][0] + f[i - 1][j][1] - x + mod) % mod;
f[i][j][1] = (f[i][j - 1][0] + f[i][j - 1][1] - y + mod) % mod;
}
}
return (int) ((f[zero][one][0] + f[zero][one][1]) % mod);
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int:
mod = 10**9 + 7
f = [[[0, 0] for _ in range(one + 1)] for _ in range(zero + 1)]
for i in range(1, min(limit, zero) + 1):
f[i][0][0] = 1
for j in range(1, min(limit, one) + 1):
f[0][j][1] = 1
for i in range(1, zero + 1):
for j in range(1, one + 1):
x = 0 if i - limit - 1 < 0 else f[i - limit - 1][j][1]
y = 0 if j - limit - 1 < 0 else f[i][j - limit - 1][0]
f[i][j][0] = (f[i - 1][j][0] + f[i - 1][j][1] - x) % mod
f[i][j][1] = (f[i][j - 1][0] + f[i][j - 1][1] - y) % mod
return sum(f[zero][one]) % mod
| null | null | null | null | null |
function numberOfStableArrays(zero: number, one: number, limit: number): number {
const mod = 1e9 + 7;
const f: number[][][] = Array.from({ length: zero + 1 }, () =>
Array.from({ length: one + 1 }, () => [0, 0]),
);
for (let i = 1; i <= Math.min(limit, zero); i++) {
f[i][0][0] = 1;
}
for (let j = 1; j <= Math.min(limit, one); j++) {
f[0][j][1] = 1;
}
for (let i = 1; i <= zero; i++) {
for (let j = 1; j <= one; j++) {
const x = i - limit - 1 < 0 ? 0 : f[i - limit - 1][j][1];
const y = j - limit - 1 < 0 ? 0 : f[i][j - limit - 1][0];
f[i][j][0] = (f[i - 1][j][0] + f[i - 1][j][1] - x + mod) % mod;
f[i][j][1] = (f[i][j - 1][0] + f[i][j - 1][1] - y + mod) % mod;
}
}
return (f[zero][one][0] + f[zero][one][1]) % mod;
}
|
Minimum Number of Vertices to Reach All Nodes
|
Given a
directed acyclic graph
, with
n
vertices numbered from
0
to
n-1
, and an array
edges
where
edges[i] = [from
i
, to
i
]
represents a directed edge from node
from
i
to node
to
i
.
Find
the smallest set of vertices from which all nodes in the graph are reachable
. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Input:
n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output:
[0,3]
Explanation:
It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Example 2:
Input:
n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output:
[0,2,3]
Explanation:
Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
Constraints:
2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= from
i,
to
i
< n
All pairs
(from
i
, to
i
)
are distinct.
| null | null |
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
vector<int> cnt(n);
for (auto& e : edges) {
++cnt[e[1]];
}
vector<int> ans;
for (int i = 0; i < n; ++i) {
if (cnt[i] == 0) {
ans.push_back(i);
}
}
return ans;
}
};
| null | null |
func findSmallestSetOfVertices(n int, edges [][]int) (ans []int) {
cnt := make([]int, n)
for _, e := range edges {
cnt[e[1]]++
}
for i, c := range cnt {
if c == 0 {
ans = append(ans, i)
}
}
return
}
|
class Solution {
public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) {
var cnt = new int[n];
for (var e : edges) {
++cnt[e.get(1)];
}
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; ++i) {
if (cnt[i] == 0) {
ans.add(i);
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
cnt = Counter(t for _, t in edges)
return [i for i in range(n) if cnt[i] == 0]
| null |
impl Solution {
pub fn find_smallest_set_of_vertices(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
let mut arr = vec![true; n as usize];
edges.iter().for_each(|edge| {
arr[edge[1] as usize] = false;
});
arr.iter()
.enumerate()
.filter_map(|(i, &v)| if v { Some(i as i32) } else { None })
.collect()
}
}
| null | null | null |
function findSmallestSetOfVertices(n: number, edges: number[][]): number[] {
const cnt: number[] = new Array(n).fill(0);
for (const [_, t] of edges) {
cnt[t]++;
}
const ans: number[] = [];
for (let i = 0; i < n; ++i) {
if (cnt[i] === 0) {
ans.push(i);
}
}
return ans;
}
|
Users That Actively Request Confirmation Messages 🔒
|
Table:
Signups
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
+----------------+----------+
user_id is the column with unique values for this table.
Each row contains information about the signup time for the user with ID user_id.
Table:
Confirmations
+----------------+----------+
| Column Name | Type |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
| action | ENUM |
+----------------+----------+
(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.
user_id is a foreign key (reference column) to the Signups table.
action is an ENUM (category) of the type ('confirmed', 'timeout')
Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout').
Write a solution to find the IDs of the users that requested a confirmation message
twice
within a 24-hour window. Two messages exactly 24 hours apart are considered to be within the window. The
action
does not affect the answer, only the request time.
Return the result table in
any order
.
The result format is in the following example.
Example 1:
Input:
Signups table:
+---------+---------------------+
| user_id | time_stamp |
+---------+---------------------+
| 3 | 2020-03-21 10:16:13 |
| 7 | 2020-01-04 13:57:59 |
| 2 | 2020-07-29 23:09:44 |
| 6 | 2020-12-09 10:39:37 |
+---------+---------------------+
Confirmations table:
+---------+---------------------+-----------+
| user_id | time_stamp | action |
+---------+---------------------+-----------+
| 3 | 2021-01-06 03:30:46 | timeout |
| 3 | 2021-01-06 03:37:45 | timeout |
| 7 | 2021-06-12 11:57:29 | confirmed |
| 7 | 2021-06-13 11:57:30 | confirmed |
| 2 | 2021-01-22 00:00:00 | confirmed |
| 2 | 2021-01-23 00:00:00 | timeout |
| 6 | 2021-10-23 14:14:14 | confirmed |
| 6 | 2021-10-24 14:14:13 | timeout |
+---------+---------------------+-----------+
Output:
+---------+
| user_id |
+---------+
| 2 |
| 3 |
| 6 |
+---------+
Explanation:
User 2 requested two messages within exactly 24 hours of each other, so we include them.
User 3 requested two messages within 6 minutes and 59 seconds of each other, so we include them.
User 6 requested two messages within 23 hours, 59 minutes, and 59 seconds of each other, so we include them.
User 7 requested two messages within 24 hours and 1 second of each other, so we exclude them from the answer.
| null | null | null | null | null | null | null | null | null |
SELECT DISTINCT user_id
FROM
Confirmations AS c1
JOIN Confirmations AS c2 USING (user_id)
WHERE
c1.time_stamp < c2.time_stamp
AND TIMESTAMPDIFF(SECOND, c1.time_stamp, c2.time_stamp) <= 24 * 60 * 60;
| null | null | null | null | null | null | null | null | null | null |
Words Within Two Edits of Dictionary
|
You are given two string arrays,
queries
and
dictionary
. All words in each array comprise of lowercase English letters and have the same length.
In one
edit
you can take a word from
queries
, and change any letter in it to any other letter. Find all words from
queries
that, after a
maximum
of two edits, equal some word from
dictionary
.
Return
a list of all words from
queries
,
that match with some word from
dictionary
after a maximum of
two edits
. Return the words in the
same order
they appear in
queries
.
Example 1:
Input:
queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]
Output:
["word","note","wood"]
Explanation:
- Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood".
- Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke".
- It would take more than 2 edits for "ants" to equal a dictionary word.
- "wood" can remain unchanged (0 edits) and match the corresponding dictionary word.
Thus, we return ["word","note","wood"].
Example 2:
Input:
queries = ["yes"], dictionary = ["not"]
Output:
[]
Explanation:
Applying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.
Constraints:
1 <= queries.length, dictionary.length <= 100
n == queries[i].length == dictionary[j].length
1 <= n <= 100
All
queries[i]
and
dictionary[j]
are composed of lowercase English letters.
| null |
public class Solution {
public IList<string> TwoEditWords(string[] queries, string[] dictionary) {
var ans = new List<string>();
foreach (var s in queries) {
foreach (var t in dictionary) {
int cnt = 0;
for (int i = 0; i < s.Length; i++) {
if (s[i] != t[i]) {
cnt++;
}
}
if (cnt < 3) {
ans.Add(s);
break;
}
}
}
return ans;
}
}
|
class Solution {
public:
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
vector<string> ans;
for (auto& s : queries) {
for (auto& t : dictionary) {
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
cnt += s[i] != t[i];
}
if (cnt < 3) {
ans.emplace_back(s);
break;
}
}
}
return ans;
}
};
| null | null |
func twoEditWords(queries []string, dictionary []string) (ans []string) {
for _, s := range queries {
for _, t := range dictionary {
cnt := 0
for i := range s {
if s[i] != t[i] {
cnt++
}
}
if cnt < 3 {
ans = append(ans, s)
break
}
}
}
return
}
|
class Solution {
public List<String> twoEditWords(String[] queries, String[] dictionary) {
List<String> ans = new ArrayList<>();
int n = queries[0].length();
for (var s : queries) {
for (var t : dictionary) {
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (s.charAt(i) != t.charAt(i)) {
++cnt;
}
}
if (cnt < 3) {
ans.add(s);
break;
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:
ans = []
for s in queries:
for t in dictionary:
if sum(a != b for a, b in zip(s, t)) < 3:
ans.append(s)
break
return ans
| null |
impl Solution {
pub fn two_edit_words(queries: Vec<String>, dictionary: Vec<String>) -> Vec<String> {
queries
.into_iter()
.filter(|s| {
dictionary
.iter()
.any(|t| s.chars().zip(t.chars()).filter(|&(a, b)| a != b).count() < 3)
})
.collect()
}
}
| null | null | null |
function twoEditWords(queries: string[], dictionary: string[]): string[] {
const n = queries[0].length;
return queries.filter(s => {
for (const t of dictionary) {
let diff = 0;
for (let i = 0; i < n; ++i) {
if (s[i] !== t[i]) {
++diff;
}
}
if (diff < 3) {
return true;
}
}
return false;
});
}
|
Minimum Number of Primes to Sum to Target 🔒
|
You are given two integers
n
and
m
.
You have to select a multiset of
prime numbers
from the
first
m
prime numbers such that the sum of the selected primes is
exactly
n
. You may use each prime number
multiple
times.
Return the
minimum
number of prime numbers needed to sum up to
n
, or -1 if it is not possible.
Example 1:
Input:
n = 10, m = 2
Output:
4
Explanation:
The first 2 primes are [2, 3]. The sum 10 can be formed as 2 + 2 + 3 + 3, requiring 4 primes.
Example 2:
Input:
n = 15, m = 5
Output:
3
Explanation:
The first 5 primes are [2, 3, 5, 7, 11]. The sum 15 can be formed as 5 + 5 + 5, requiring 3 primes.
Example 3:
Input:
n = 7, m = 6
Output:
1
Explanation:
The first 6 primes are [2, 3, 5, 7, 11, 13]. The sum 7 can be formed directly by prime 7, requiring only 1 prime.
Constraints:
1 <= n <= 1000
1 <= m <= 1000
| null | null |
class Solution {
public:
int minNumberOfPrimes(int n, int m) {
static vector<int> primes;
if (primes.empty()) {
int x = 2;
int M = 1000;
while ((int) primes.size() < M) {
bool is_prime = true;
for (int p : primes) {
if (p * p > x) break;
if (x % p == 0) {
is_prime = false;
break;
}
}
if (is_prime) primes.push_back(x);
x++;
}
}
vector<int> f(n + 1, INT_MAX);
f[0] = 0;
for (int x : vector<int>(primes.begin(), primes.begin() + m)) {
for (int i = x; i <= n; ++i) {
if (f[i - x] != INT_MAX) {
f[i] = min(f[i], f[i - x] + 1);
}
}
}
return f[n] < INT_MAX ? f[n] : -1;
}
};
| null | null |
var primes []int
func init() {
x := 2
M := 1000
for len(primes) < M {
is_prime := true
for _, p := range primes {
if p*p > x {
break
}
if x%p == 0 {
is_prime = false
break
}
}
if is_prime {
primes = append(primes, x)
}
x++
}
}
func minNumberOfPrimes(n int, m int) int {
const inf = int(1e9)
f := make([]int, n+1)
for i := 1; i <= n; i++ {
f[i] = inf
}
f[0] = 0
for _, x := range primes[:m] {
for i := x; i <= n; i++ {
if f[i-x] < inf && f[i-x]+1 < f[i] {
f[i] = f[i-x] + 1
}
}
}
if f[n] < inf {
return f[n]
}
return -1
}
|
class Solution {
static List<Integer> primes = new ArrayList<>();
static {
int x = 2;
int M = 1000;
while (primes.size() < M) {
boolean is_prime = true;
for (int p : primes) {
if (p * p > x) {
break;
}
if (x % p == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primes.add(x);
}
x++;
}
}
public int minNumberOfPrimes(int n, int m) {
int[] f = new int[n + 1];
final int inf = 1 << 30;
Arrays.fill(f, inf);
f[0] = 0;
for (int x : primes.subList(0, m)) {
for (int i = x; i <= n; i++) {
f[i] = Math.min(f[i], f[i - x] + 1);
}
}
return f[n] < inf ? f[n] : -1;
}
}
| null | null | null | null | null | null |
primes = []
x = 2
M = 1000
while len(primes) < M:
is_prime = True
for p in primes:
if p * p > x:
break
if x % p == 0:
is_prime = False
break
if is_prime:
primes.append(x)
x += 1
class Solution:
def minNumberOfPrimes(self, n: int, m: int) -> int:
min = lambda x, y: x if x < y else y
f = [0] + [inf] * n
for x in primes[:m]:
for i in range(x, n + 1):
f[i] = min(f[i], f[i - x] + 1)
return f[n] if f[n] < inf else -1
| null | null | null | null | null |
const primes: number[] = [];
let x = 2;
const M = 1000;
while (primes.length < M) {
let is_prime = true;
for (const p of primes) {
if (p * p > x) break;
if (x % p === 0) {
is_prime = false;
break;
}
}
if (is_prime) primes.push(x);
x++;
}
function minNumberOfPrimes(n: number, m: number): number {
const inf = 1e9;
const f: number[] = Array(n + 1).fill(inf);
f[0] = 0;
for (const x of primes.slice(0, m)) {
for (let i = x; i <= n; i++) {
if (f[i - x] < inf) {
f[i] = Math.min(f[i], f[i - x] + 1);
}
}
}
return f[n] < inf ? f[n] : -1;
}
|
Number of Distinct Islands II 🔒
|
You are given an
m x n
binary matrix
grid
. An island is a group of
1
's (representing land) connected
4-directionally
(horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if they have the same shape, or have the same shape after
rotation
(90, 180, or 270 degrees only) or
reflection
(left/right direction or up/down direction).
Return
the number of
distinct
islands
.
Example 1:
Input:
grid = [[1,1,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,1,1]]
Output:
1
Explanation:
The two islands are considered the same because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.
Example 2:
Input:
grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output:
1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either
0
or
1
.
| null | null |
typedef pair<int, int> PII;
class Solution {
public:
int numDistinctIslands2(vector<vector<int>>& grid) {
set<vector<PII>> s;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j]) {
vector<PII> shape;
dfs(i, j, grid, shape);
s.insert(normalize(shape));
}
}
}
return s.size();
}
vector<PII> normalize(vector<PII>& shape) {
vector<vector<PII>> shapes(8);
for (auto& e : shape) {
int i = e.first, j = e.second;
shapes[0].push_back({i, j});
shapes[1].push_back({i, -j});
shapes[2].push_back({-i, j});
shapes[3].push_back({-i, -j});
shapes[4].push_back({j, i});
shapes[5].push_back({j, -i});
shapes[6].push_back({-j, -i});
shapes[7].push_back({-j, i});
}
for (auto& e : shapes) {
sort(e.begin(), e.end());
for (int k = e.size() - 1; k >= 0; --k) {
e[k].first -= e[0].first;
e[k].second -= e[0].second;
}
}
sort(shapes.begin(), shapes.end());
return shapes[0];
}
void dfs(int i, int j, vector<vector<int>>& grid, vector<PII>& shape) {
shape.push_back({i, j});
grid[i][j] = 0;
vector<int> dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == 1)
dfs(x, y, grid, shape);
}
}
};
| null | null | null |
class Solution {
private int m;
private int n;
private int[][] grid;
public int numDistinctIslands2(int[][] grid) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
Set<List<List<Integer>>> s = new HashSet<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
List<Integer> shape = new ArrayList<>();
dfs(i, j, shape);
s.add(normalize(shape));
}
}
}
return s.size();
}
private List<List<Integer>> normalize(List<Integer> shape) {
List<int[]>[] shapes = new List[8];
for (int i = 0; i < 8; ++i) {
shapes[i] = new ArrayList<>();
}
for (int e : shape) {
int i = e / n;
int j = e % n;
shapes[0].add(new int[] {i, j});
shapes[1].add(new int[] {i, -j});
shapes[2].add(new int[] {-i, j});
shapes[3].add(new int[] {-i, -j});
shapes[4].add(new int[] {j, i});
shapes[5].add(new int[] {j, -i});
shapes[6].add(new int[] {-j, i});
shapes[7].add(new int[] {-j, -i});
}
for (List<int[]> e : shapes) {
e.sort((a, b) -> {
int i1 = a[0];
int j1 = a[1];
int i2 = b[0];
int j2 = b[1];
if (i1 == i2) {
return j1 - j2;
}
return i1 - i2;
});
int a = e.get(0)[0];
int b = e.get(0)[1];
for (int k = e.size() - 1; k >= 0; --k) {
int i = e.get(k)[0];
int j = e.get(k)[1];
e.set(k, new int[] {i - a, j - b});
}
}
Arrays.sort(shapes, (a, b) -> {
for (int k = 0; k < a.size(); ++k) {
int i1 = a.get(k)[0];
int j1 = a.get(k)[1];
int i2 = b.get(k)[0];
int j2 = b.get(k)[1];
if (i1 != i2) {
return i1 - i2;
}
if (j1 != j2) {
return j1 - j2;
}
}
return 0;
});
List<List<Integer>> ans = new ArrayList<>();
for (int[] e : shapes[0]) {
ans.add(Arrays.asList(e[0], e[1]));
}
return ans;
}
private void dfs(int i, int j, List<Integer> shape) {
shape.add(i * n + j);
grid[i][j] = 0;
int[] dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k];
int y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
dfs(x, y, shape);
}
}
}
}
| null | null | null | null | null | null |
class Solution:
def numDistinctIslands2(self, grid: List[List[int]]) -> int:
def dfs(i, j, shape):
shape.append([i, j])
grid[i][j] = 0
for a, b in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
dfs(x, y, shape)
def normalize(shape):
shapes = [[] for _ in range(8)]
for i, j in shape:
shapes[0].append([i, j])
shapes[1].append([i, -j])
shapes[2].append([-i, j])
shapes[3].append([-i, -j])
shapes[4].append([j, i])
shapes[5].append([j, -i])
shapes[6].append([-j, i])
shapes[7].append([-j, -i])
for e in shapes:
e.sort()
for i in range(len(e) - 1, -1, -1):
e[i][0] -= e[0][0]
e[i][1] -= e[0][1]
shapes.sort()
return tuple(tuple(e) for e in shapes[0])
m, n = len(grid), len(grid[0])
s = set()
for i in range(m):
for j in range(n):
if grid[i][j]:
shape = []
dfs(i, j, shape)
s.add(normalize(shape))
return len(s)
| null | null | null | null | null | null |
Rabbits in Forest
|
There is a forest with an unknown number of rabbits. We asked n rabbits
"How many rabbits have the same color as you?"
and collected the answers in an integer array
answers
where
answers[i]
is the answer of the
i
th
rabbit.
Given the array
answers
, return
the minimum number of rabbits that could be in the forest
.
Example 1:
Input:
answers = [1,1,2]
Output:
5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
Input:
answers = [10,10,10]
Output:
11
Constraints:
1 <= answers.length <= 1000
0 <= answers[i] < 1000
| null | null |
class Solution {
public:
int numRabbits(vector<int>& answers) {
unordered_map<int, int> cnt;
for (int x : answers) {
++cnt[x];
}
int ans = 0;
for (auto& [x, v] : cnt) {
int group = x + 1;
ans += (v + group - 1) / group * group;
}
return ans;
}
};
| null | null |
func numRabbits(answers []int) (ans int) {
cnt := map[int]int{}
for _, x := range answers {
cnt[x]++
}
for x, v := range cnt {
group := x + 1
ans += (v + group - 1) / group * group
}
return
}
|
class Solution {
public int numRabbits(int[] answers) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : answers) {
cnt.merge(x, 1, Integer::sum);
}
int ans = 0;
for (var e : cnt.entrySet()) {
int group = e.getKey() + 1;
ans += (e.getValue() + group - 1) / group * group;
}
return ans;
}
}
|
function numRabbits(answers) {
const cnt = {};
let ans = 0;
for (const x of answers) {
if (cnt[x]) {
cnt[x]--;
} else {
cnt[x] = x;
ans += x + 1;
}
}
return ans;
}
| null | null | null | null | null |
class Solution:
def numRabbits(self, answers: List[int]) -> int:
cnt = Counter(answers)
ans = 0
for x, v in cnt.items():
group = x + 1
ans += (v + group - 1) // group * group
return ans
| null | null | null | null | null |
function numRabbits(answers: number[]): number {
const cnt: Record<number, number> = {};
let ans = 0;
for (const x of answers) {
if (cnt[x]) {
cnt[x]--;
} else {
cnt[x] = x;
ans += x + 1;
}
}
return ans;
}
|
List the Products Ordered in a Period
|
Table:
Products
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| product_id | int |
| product_name | varchar |
| product_category | varchar |
+------------------+---------+
product_id is the primary key (column with unique values) for this table.
This table contains data about the company's products.
Table:
Orders
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| order_date | date |
| unit | int |
+---------------+---------+
This table may have duplicate rows.
product_id is a foreign key (reference column) to the Products table.
unit is the number of products ordered in order_date.
Write a solution to get the names of products that have at least
100
units ordered in
February 2020
and their amount.
Return the result table in
any order
.
The result format is in the following example.
Example 1:
Input:
Products table:
+-------------+-----------------------+------------------+
| product_id | product_name | product_category |
+-------------+-----------------------+------------------+
| 1 | Leetcode Solutions | Book |
| 2 | Jewels of Stringology | Book |
| 3 | HP | Laptop |
| 4 | Lenovo | Laptop |
| 5 | Leetcode Kit | T-shirt |
+-------------+-----------------------+------------------+
Orders table:
+--------------+--------------+----------+
| product_id | order_date | unit |
+--------------+--------------+----------+
| 1 | 2020-02-05 | 60 |
| 1 | 2020-02-10 | 70 |
| 2 | 2020-01-18 | 30 |
| 2 | 2020-02-11 | 80 |
| 3 | 2020-02-17 | 2 |
| 3 | 2020-02-24 | 3 |
| 4 | 2020-03-01 | 20 |
| 4 | 2020-03-04 | 30 |
| 4 | 2020-03-04 | 60 |
| 5 | 2020-02-25 | 50 |
| 5 | 2020-02-27 | 50 |
| 5 | 2020-03-01 | 50 |
+--------------+--------------+----------+
Output:
+--------------------+---------+
| product_name | unit |
+--------------------+---------+
| Leetcode Solutions | 130 |
| Leetcode Kit | 100 |
+--------------------+---------+
Explanation:
Products with product_id = 1 is ordered in February a total of (60 + 70) = 130.
Products with product_id = 2 is ordered in February a total of 80.
Products with product_id = 3 is ordered in February a total of (2 + 3) = 5.
Products with product_id = 4 was not ordered in February 2020.
Products with product_id = 5 is ordered in February a total of (50 + 50) = 100.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
SELECT product_name, SUM(unit) AS unit
FROM
Orders AS o
JOIN Products AS p ON o.product_id = p.product_id
WHERE DATE_FORMAT(order_date, '%Y-%m') = '2020-02'
GROUP BY o.product_id
HAVING unit >= 100;
| null | null | null | null | null | null | null | null | null | null |
Guess Number Higher or Lower II
|
We are playing the Guessing Game. The game will work as follows:
I pick a number between
1
and
n
.
You guess a number.
If you guess the right number,
you win the game
.
If you guess the wrong number, then I will tell you whether the number I picked is
higher or lower
, and you will continue guessing.
Every time you guess a wrong number
x
, you will pay
x
dollars. If you run out of money,
you lose the game
.
Given a particular
n
, return
the minimum amount of money you need to
guarantee a win regardless of what number I pick
.
Example 1:
Input:
n = 10
Output:
16
Explanation:
The winning strategy is as follows:
- The range is [1,10]. Guess 7.
- If this is my number, your total is $0. Otherwise, you pay $7.
- If my number is higher, the range is [8,10]. Guess 9.
- If this is my number, your total is $7. Otherwise, you pay $9.
- If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
- If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
- If my number is lower, the range is [1,6]. Guess 3.
- If this is my number, your total is $7. Otherwise, you pay $3.
- If my number is higher, the range is [4,6]. Guess 5.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
- If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
- If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
- If my number is lower, the range is [1,2]. Guess 1.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
Example 2:
Input:
n = 1
Output:
0
Explanation:
There is only one possible number, so you can guess 1 and not have to pay anything.
Example 3:
Input:
n = 2
Output:
1
Explanation:
There are two possible numbers, 1 and 2.
- Guess 1.
- If this is my number, your total is $0. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $1.
The worst case is that you pay $1.
Constraints:
1 <= n <= 200
| null | null |
class Solution {
public:
int getMoneyAmount(int n) {
int f[n + 1][n + 1];
memset(f, 0, sizeof(f));
for (int i = n - 1; i; --i) {
for (int j = i + 1; j <= n; ++j) {
f[i][j] = j + f[i][j - 1];
for (int k = i; k < j; ++k) {
f[i][j] = min(f[i][j], max(f[i][k - 1], f[k + 1][j]) + k);
}
}
}
return f[1][n];
}
};
| null | null |
func getMoneyAmount(n int) int {
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, n+1)
}
for i := n - 1; i > 0; i-- {
for j := i + 1; j <= n; j++ {
f[i][j] = j + f[i][j-1]
for k := i; k < j; k++ {
f[i][j] = min(f[i][j], k+max(f[i][k-1], f[k+1][j]))
}
}
}
return f[1][n]
}
|
class Solution {
public int getMoneyAmount(int n) {
int[][] f = new int[n + 1][n + 1];
for (int i = n - 1; i > 0; --i) {
for (int j = i + 1; j <= n; ++j) {
f[i][j] = j + f[i][j - 1];
for (int k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], Math.max(f[i][k - 1], f[k + 1][j]) + k);
}
}
}
return f[1][n];
}
}
| null | null | null | null | null | null |
class Solution:
def getMoneyAmount(self, n: int) -> int:
f = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, 0, -1):
for j in range(i + 1, n + 1):
f[i][j] = j + f[i][j - 1]
for k in range(i, j):
f[i][j] = min(f[i][j], max(f[i][k - 1], f[k + 1][j]) + k)
return f[1][n]
| null | null | null | null | null |
function getMoneyAmount(n: number): number {
const f: number[][] = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
for (let i = n - 1; i; --i) {
for (let j = i + 1; j <= n; ++j) {
f[i][j] = j + f[i][j - 1];
for (let k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], k + Math.max(f[i][k - 1], f[k + 1][j]));
}
}
}
return f[1][n];
}
|
Eat Pizzas!
|
You are given an integer array
pizzas
of size
n
, where
pizzas[i]
represents the weight of the
i
th
pizza. Every day, you eat
exactly
4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights
W
,
X
,
Y
, and
Z
, where
W <= X <= Y <= Z
, you gain the weight of only 1 pizza!
On
odd-numbered
days
(1-indexed)
, you gain a weight of
Z
.
On
even-numbered
days, you gain a weight of
Y
.
Find the
maximum
total weight you can gain by eating
all
pizzas optimally.
Note
: It is guaranteed that
n
is a multiple of 4, and each pizza can be eaten only once.
Example 1:
Input:
pizzas = [1,2,3,4,5,6,7,8]
Output:
14
Explanation:
On day 1, you eat pizzas at indices
[1, 2, 4, 7] = [2, 3, 5, 8]
. You gain a weight of 8.
On day 2, you eat pizzas at indices
[0, 3, 5, 6] = [1, 4, 6, 7]
. You gain a weight of 6.
The total weight gained after eating all the pizzas is
8 + 6 = 14
.
Example 2:
Input:
pizzas = [2,1,1,1,1,1,1,1]
Output:
3
Explanation:
On day 1, you eat pizzas at indices
[4, 5, 6, 0] = [1, 1, 1, 2]
. You gain a weight of 2.
On day 2, you eat pizzas at indices
[1, 2, 3, 7] = [1, 1, 1, 1]
. You gain a weight of 1.
The total weight gained after eating all the pizzas is
2 + 1 = 3.
Constraints:
4 <= n == pizzas.length <= 2 * 10
5
1 <= pizzas[i] <= 10
5
n
is a multiple of 4.
| null | null |
class Solution {
public:
long long maxWeight(vector<int>& pizzas) {
int n = pizzas.size();
int days = pizzas.size() / 4;
ranges::sort(pizzas);
int odd = (days + 1) / 2;
int even = days - odd;
long long ans = accumulate(pizzas.begin() + n - odd, pizzas.end(), 0LL);
for (int i = n - odd - 2; even; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
};
| null | null |
func maxWeight(pizzas []int) (ans int64) {
n := len(pizzas)
days := n / 4
sort.Ints(pizzas)
odd := (days + 1) / 2
even := days - odd
for i := n - odd; i < n; i++ {
ans += int64(pizzas[i])
}
for i := n - odd - 2; even > 0; even-- {
ans += int64(pizzas[i])
i -= 2
}
return
}
|
class Solution {
public long maxWeight(int[] pizzas) {
int n = pizzas.length;
int days = n / 4;
Arrays.sort(pizzas);
int odd = (days + 1) / 2;
int even = days / 2;
long ans = 0;
for (int i = n - odd; i < n; ++i) {
ans += pizzas[i];
}
for (int i = n - odd - 2; even > 0; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maxWeight(self, pizzas: List[int]) -> int:
days = len(pizzas) // 4
pizzas.sort()
odd = (days + 1) // 2
even = days - odd
ans = sum(pizzas[-odd:])
i = len(pizzas) - odd - 2
for _ in range(even):
ans += pizzas[i]
i -= 2
return ans
| null | null | null | null | null |
function maxWeight(pizzas: number[]): number {
const n = pizzas.length;
const days = n >> 2;
pizzas.sort((a, b) => a - b);
const odd = (days + 1) >> 1;
let even = days - odd;
let ans = 0;
for (let i = n - odd; i < n; ++i) {
ans += pizzas[i];
}
for (let i = n - odd - 2; even; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
|
Minimum Sum of Squared Difference
|
You are given two positive
0-indexed
integer arrays
nums1
and
nums2
, both of length
n
.
The
sum of squared difference
of arrays
nums1
and
nums2
is defined as the
sum
of
(nums1[i] - nums2[i])
2
for each
0 <= i < n
.
You are also given two positive integers
k1
and
k2
. You can modify any of the elements of
nums1
by
+1
or
-1
at most
k1
times. Similarly, you can modify any of the elements of
nums2
by
+1
or
-1
at most
k2
times.
Return
the minimum
sum of squared difference
after modifying array
nums1
at most
k1
times and modifying array
nums2
at most
k2
times
.
Note
: You are allowed to modify the array elements to become
negative
integers.
Example 1:
Input:
nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0
Output:
579
Explanation:
The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0.
The sum of square difference will be: (1 - 2)
2
+ (2 - 10)
2
+ (3 - 20)
2
+ (4 - 19)
2
= 579.
Example 2:
Input:
nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1
Output:
43
Explanation:
One way to obtain the minimum sum of square difference is:
- Increase nums1[0] once.
- Increase nums2[2] once.
The minimum of the sum of square difference will be:
(2 - 5)
2
+ (4 - 8)
2
+ (10 - 7)
2
+ (12 - 9)
2
= 43.
Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 10
5
0 <= nums1[i], nums2[i] <= 10
5
0 <= k1, k2 <= 10
9
| null | null |
using ll = long long;
class Solution {
public:
long long minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
int n = nums1.size();
vector<int> d(n);
ll s = 0;
int mx = 0;
int k = k1 + k2;
for (int i = 0; i < n; ++i) {
d[i] = abs(nums1[i] - nums2[i]);
s += d[i];
mx = max(mx, d[i]);
}
if (s <= k) return 0;
int left = 0, right = mx;
while (left < right) {
int mid = (left + right) >> 1;
ll t = 0;
for (int v : d) t += max(v - mid, 0);
if (t <= k)
right = mid;
else
left = mid + 1;
}
for (int i = 0; i < n; ++i) {
k -= max(0, d[i] - left);
d[i] = min(d[i], left);
}
for (int i = 0; i < n && k; ++i) {
if (d[i] == left) {
--k;
--d[i];
}
}
ll ans = 0;
for (int v : d) ans += 1ll * v * v;
return ans;
}
};
| null | null |
func minSumSquareDiff(nums1 []int, nums2 []int, k1 int, k2 int) int64 {
k := k1 + k2
s, mx := 0, 0
n := len(nums1)
d := make([]int, n)
for i, v := range nums1 {
d[i] = abs(v - nums2[i])
s += d[i]
mx = max(mx, d[i])
}
if s <= k {
return 0
}
left, right := 0, mx
for left < right {
mid := (left + right) >> 1
t := 0
for _, v := range d {
t += max(v-mid, 0)
}
if t <= k {
right = mid
} else {
left = mid + 1
}
}
for i, v := range d {
k -= max(v-left, 0)
d[i] = min(v, left)
}
for i, v := range d {
if k <= 0 {
break
}
if v == left {
d[i]--
k--
}
}
ans := 0
for _, v := range d {
ans += v * v
}
return int64(ans)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {
int n = nums1.length;
int[] d = new int[n];
long s = 0;
int mx = 0;
int k = k1 + k2;
for (int i = 0; i < n; ++i) {
d[i] = Math.abs(nums1[i] - nums2[i]);
s += d[i];
mx = Math.max(mx, d[i]);
}
if (s <= k) {
return 0;
}
int left = 0, right = mx;
while (left < right) {
int mid = (left + right) >> 1;
long t = 0;
for (int v : d) {
t += Math.max(v - mid, 0);
}
if (t <= k) {
right = mid;
} else {
left = mid + 1;
}
}
for (int i = 0; i < n; ++i) {
k -= Math.max(0, d[i] - left);
d[i] = Math.min(d[i], left);
}
for (int i = 0; i < n && k > 0; ++i) {
if (d[i] == left) {
--k;
--d[i];
}
}
long ans = 0;
for (int v : d) {
ans += (long) v * v;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minSumSquareDiff(
self, nums1: List[int], nums2: List[int], k1: int, k2: int
) -> int:
d = [abs(a - b) for a, b in zip(nums1, nums2)]
k = k1 + k2
if sum(d) <= k:
return 0
left, right = 0, max(d)
while left < right:
mid = (left + right) >> 1
if sum(max(v - mid, 0) for v in d) <= k:
right = mid
else:
left = mid + 1
for i, v in enumerate(d):
d[i] = min(left, v)
k -= max(0, v - left)
for i, v in enumerate(d):
if k == 0:
break
if v == left:
k -= 1
d[i] -= 1
return sum(v * v for v in d)
| null | null | null | null | null | null |
Shopping Offers
|
In LeetCode Store, there are
n
items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array
price
where
price[i]
is the price of the
i
th
item, and an integer array
needs
where
needs[i]
is the number of pieces of the
i
th
item you want to buy.
You are also given an array
special
where
special[i]
is of size
n + 1
where
special[i][j]
is the number of pieces of the
j
th
item in the
i
th
offer and
special[i][n]
(i.e., the last integer in the array) is the price of the
i
th
offer.
Return
the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers
. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
Input:
price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output:
14
Explanation:
There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Example 2:
Input:
price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output:
11
Explanation:
The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
Constraints:
n == price.length == needs.length
1 <= n <= 6
0 <= price[i], needs[i] <= 10
1 <= special.length <= 100
special[i].length == n + 1
0 <= special[i][j] <= 50
The input is generated that at least one of
special[i][j]
is non-zero for
0 <= j <= n - 1
.
| null | null |
class Solution {
public:
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
const int bits = 4;
int n = needs.size();
unordered_map<int, int> f;
int mask = 0;
for (int i = 0; i < n; ++i) {
mask |= needs[i] << (i * bits);
}
function<int(int)> dfs = [&](int cur) {
if (f.contains(cur)) {
return f[cur];
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += price[i] * ((cur >> (i * bits)) & 0xf);
}
for (const auto& offer : special) {
int nxt = cur;
bool ok = true;
for (int j = 0; j < n; ++j) {
if (((cur >> (j * bits)) & 0xf) < offer[j]) {
ok = false;
break;
}
nxt -= offer[j] << (j * bits);
}
if (ok) {
ans = min(ans, offer[n] + dfs(nxt));
}
}
f[cur] = ans;
return ans;
};
return dfs(mask);
}
};
| null | null |
func shoppingOffers(price []int, special [][]int, needs []int) int {
const bits = 4
n := len(needs)
f := make(map[int]int)
mask := 0
for i, need := range needs {
mask |= need << (i * bits)
}
var dfs func(int) int
dfs = func(cur int) int {
if v, ok := f[cur]; ok {
return v
}
ans := 0
for i := 0; i < n; i++ {
ans += price[i] * ((cur >> (i * bits)) & 0xf)
}
for _, offer := range special {
nxt := cur
ok := true
for j := 0; j < n; j++ {
if ((cur >> (j * bits)) & 0xf) < offer[j] {
ok = false
break
}
nxt -= offer[j] << (j * bits)
}
if ok {
ans = min(ans, offer[n]+dfs(nxt))
}
}
f[cur] = ans
return ans
}
return dfs(mask)
}
|
class Solution {
private final int bits = 4;
private int n;
private List<Integer> price;
private List<List<Integer>> special;
private Map<Integer, Integer> f = new HashMap<>();
public int shoppingOffers(
List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
n = needs.size();
this.price = price;
this.special = special;
int mask = 0;
for (int i = 0; i < n; ++i) {
mask |= needs.get(i) << (i * bits);
}
return dfs(mask);
}
private int dfs(int cur) {
if (f.containsKey(cur)) {
return f.get(cur);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += price.get(i) * (cur >> (i * bits) & 0xf);
}
for (List<Integer> offer : special) {
int nxt = cur;
boolean ok = true;
for (int j = 0; j < n; ++j) {
if ((cur >> (j * bits) & 0xf) < offer.get(j)) {
ok = false;
break;
}
nxt -= offer.get(j) << (j * bits);
}
if (ok) {
ans = Math.min(ans, offer.get(n) + dfs(nxt));
}
}
f.put(cur, ans);
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def shoppingOffers(
self, price: List[int], special: List[List[int]], needs: List[int]
) -> int:
@cache
def dfs(cur: int) -> int:
ans = sum(p * (cur >> (i * bits) & 0xF) for i, p in enumerate(price))
for offer in special:
nxt = cur
for j in range(len(needs)):
if (cur >> (j * bits) & 0xF) < offer[j]:
break
nxt -= offer[j] << (j * bits)
else:
ans = min(ans, offer[-1] + dfs(nxt))
return ans
bits, mask = 4, 0
for i, need in enumerate(needs):
mask |= need << i * bits
return dfs(mask)
| null | null | null | null | null |
function shoppingOffers(price: number[], special: number[][], needs: number[]): number {
const bits = 4;
const n = needs.length;
const f: Map<number, number> = new Map();
let mask = 0;
for (let i = 0; i < n; i++) {
mask |= needs[i] << (i * bits);
}
const dfs = (cur: number): number => {
if (f.has(cur)) {
return f.get(cur)!;
}
let ans = 0;
for (let i = 0; i < n; i++) {
ans += price[i] * ((cur >> (i * bits)) & 0xf);
}
for (const offer of special) {
let nxt = cur;
let ok = true;
for (let j = 0; j < n; j++) {
if (((cur >> (j * bits)) & 0xf) < offer[j]) {
ok = false;
break;
}
nxt -= offer[j] << (j * bits);
}
if (ok) {
ans = Math.min(ans, offer[n] + dfs(nxt));
}
}
f.set(cur, ans);
return ans;
};
return dfs(mask);
}
|
Remove Duplicates from Sorted List
|
Given the
head
of a sorted linked list,
delete all duplicates such that each element appears only once
. Return
the linked list
sorted
as well
.
Example 1:
Input:
head = [1,1,2]
Output:
[1,2]
Example 2:
Input:
head = [1,1,2,3,3]
Output:
[1,2,3]
Constraints:
The number of nodes in the list is in the range
[0, 300]
.
-100 <= Node.val <= 100
The list is guaranteed to be
sorted
in ascending order.
| null |
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode DeleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* cur = head;
while (cur != nullptr && cur->next != nullptr) {
if (cur->val == cur->next->val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return head;
}
};
| null | null |
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
cur := head
for cur != nil && cur.Next != nil {
if cur.Val == cur.Next.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return head
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
|
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
let cur = head;
while (cur && cur.next) {
if (cur.next.val === cur.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
};
| null | null | null | null | null |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
| null |
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode::new(i32::MAX)));
let mut p = &mut dummy;
let mut current = head;
while let Some(mut node) = current {
current = node.next.take();
if p.as_mut().unwrap().val != node.val {
p.as_mut().unwrap().next = Some(node);
p = &mut p.as_mut().unwrap().next;
}
}
dummy.unwrap().next
}
}
| null | null | null | null |
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
|
Given a
m x n
binary matrix
mat
. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing
1
to
0
and
0
to
1
). A pair of cells are called neighbors if they share one edge.
Return the
minimum number of steps
required to convert
mat
to a zero matrix or
-1
if you cannot.
A
binary matrix
is a matrix with all cells equal to
0
or
1
only.
A
zero matrix
is a matrix with all cells equal to
0
.
Example 1:
Input:
mat = [[0,0],[0,1]]
Output:
3
Explanation:
One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
Input:
mat = [[0]]
Output:
0
Explanation:
Given matrix is a zero matrix. We do not need to change it.
Example 3:
Input:
mat = [[1,0,0],[1,0,0]]
Output:
-1
Explanation:
Given matrix cannot be a zero matrix.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 3
mat[i][j]
is either
0
or
1
.
| null | null |
class Solution {
public:
int minFlips(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
int state = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (mat[i][j])
state |= (1 << (i * n + j));
queue<int> q{{state}};
unordered_set<int> vis{{state}};
int ans = 0;
vector<int> dirs = {0, -1, 0, 1, 0, 0};
while (!q.empty()) {
for (int t = q.size(); t; --t) {
state = q.front();
if (state == 0) return ans;
q.pop();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int nxt = state;
for (int k = 0; k < 5; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n) continue;
if ((nxt & (1 << (x * n + y))) != 0)
nxt -= 1 << (x * n + y);
else
nxt |= 1 << (x * n + y);
}
if (!vis.count(nxt)) {
vis.insert(nxt);
q.push(nxt);
}
}
}
}
++ans;
}
return -1;
}
};
| null | null |
func minFlips(mat [][]int) int {
m, n := len(mat), len(mat[0])
state := 0
for i, row := range mat {
for j, v := range row {
if v == 1 {
state |= 1 << (i*n + j)
}
}
}
q := []int{state}
vis := map[int]bool{state: true}
ans := 0
dirs := []int{0, -1, 0, 1, 0, 0}
for len(q) > 0 {
for t := len(q); t > 0; t-- {
state = q[0]
if state == 0 {
return ans
}
q = q[1:]
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
nxt := state
for k := 0; k < 5; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x < 0 || x >= m || y < 0 || y >= n {
continue
}
if (nxt & (1 << (x*n + y))) != 0 {
nxt -= 1 << (x*n + y)
} else {
nxt |= 1 << (x*n + y)
}
}
if !vis[nxt] {
vis[nxt] = true
q = append(q, nxt)
}
}
}
}
ans++
}
return -1
}
|
class Solution {
public int minFlips(int[][] mat) {
int m = mat.length, n = mat[0].length;
int state = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 1) {
state |= 1 << (i * n + j);
}
}
}
Deque<Integer> q = new ArrayDeque<>();
q.offer(state);
Set<Integer> vis = new HashSet<>();
vis.add(state);
int ans = 0;
int[] dirs = {0, -1, 0, 1, 0, 0};
while (!q.isEmpty()) {
for (int t = q.size(); t > 0; --t) {
state = q.poll();
if (state == 0) {
return ans;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int nxt = state;
for (int k = 0; k < 5; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n) {
continue;
}
if ((nxt & (1 << (x * n + y))) != 0) {
nxt -= 1 << (x * n + y);
} else {
nxt |= 1 << (x * n + y);
}
}
if (!vis.contains(nxt)) {
vis.add(nxt);
q.offer(nxt);
}
}
}
}
++ans;
}
return -1;
}
}
| null | null | null | null | null | null |
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if mat[i][j])
q = deque([state])
vis = {state}
ans = 0
dirs = [0, -1, 0, 1, 0, 0]
while q:
for _ in range(len(q)):
state = q.popleft()
if state == 0:
return ans
for i in range(m):
for j in range(n):
nxt = state
for k in range(5):
x, y = i + dirs[k], j + dirs[k + 1]
if not 0 <= x < m or not 0 <= y < n:
continue
if nxt & (1 << (x * n + y)):
nxt -= 1 << (x * n + y)
else:
nxt |= 1 << (x * n + y)
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
return -1
| null | null | null | null | null | null |
Sort the Students by Their Kth Score
|
There is a class with
m
students and
n
exams. You are given a
0-indexed
m x n
integer matrix
score
, where each row represents one student and
score[i][j]
denotes the score the
i
th
student got in the
j
th
exam. The matrix
score
contains
distinct
integers only.
You are also given an integer
k
. Sort the students (i.e., the rows of the matrix) by their scores in the
k
th
(
0-indexed
) exam from the highest to the lowest.
Return
the matrix after sorting it.
Example 1:
Input:
score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2
Output:
[[7,5,11,2],[10,6,9,1],[4,8,3,15]]
Explanation:
In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.
- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.
- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.
Example 2:
Input:
score = [[3,4],[5,6]], k = 0
Output:
[[5,6],[3,4]]
Explanation:
In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.
- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.
Constraints:
m == score.length
n == score[i].length
1 <= m, n <= 250
1 <= score[i][j] <= 10
5
score
consists of
distinct
integers.
0 <= k < n
| null | null |
class Solution {
public:
vector<vector<int>> sortTheStudents(vector<vector<int>>& score, int k) {
ranges::sort(score, [k](const auto& a, const auto& b) { return a[k] > b[k]; });
return score;
}
};
| null | null |
func sortTheStudents(score [][]int, k int) [][]int {
sort.Slice(score, func(i, j int) bool { return score[i][k] > score[j][k] })
return score
}
|
class Solution {
public int[][] sortTheStudents(int[][] score, int k) {
Arrays.sort(score, (a, b) -> b[k] - a[k]);
return score;
}
}
| null | null | null | null | null | null |
class Solution:
def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:
return sorted(score, key=lambda x: -x[k])
| null |
impl Solution {
pub fn sort_the_students(mut score: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
let k = k as usize;
score.sort_by(|a, b| b[k].cmp(&a[k]));
score
}
}
| null | null | null |
function sortTheStudents(score: number[][], k: number): number[][] {
return score.sort((a, b) => b[k] - a[k]);
}
|
Game Play Analysis II 🔒
|
Table:
Activity
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key (combination of columns with unique values) of this table.
This table shows the activity of players of some games.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.
Write a solution to report the
device
that is first logged in for each player.
Return the result table in
any order
.
The result format is in the following example.
Example 1:
Input:
Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 2 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+
Output:
+-----------+-----------+
| player_id | device_id |
+-----------+-----------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
+-----------+-----------+
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY player_id
ORDER BY event_date
) AS rk
FROM Activity
)
SELECT player_id, device_id
FROM T
WHERE rk = 1;
| null | null | null | null | null | null | null | null | null | null |
Fair Candy Swap
|
Alice and Bob have a different total number of candies. You are given two integer arrays
aliceSizes
and
bobSizes
where
aliceSizes[i]
is the number of candies of the
i
th
box of candy that Alice has and
bobSizes[j]
is the number of candies of the
j
th
box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return a
n integer array
answer
where
answer[0]
is the number of candies in the box that Alice must exchange, and
answer[1]
is the number of candies in the box that Bob must exchange
. If there are multiple answers, you may
return any
one of them. It is guaranteed that at least one answer exists.
Example 1:
Input:
aliceSizes = [1,1], bobSizes = [2,2]
Output:
[1,2]
Example 2:
Input:
aliceSizes = [1,2], bobSizes = [2,3]
Output:
[1,2]
Example 3:
Input:
aliceSizes = [2], bobSizes = [1,3]
Output:
[2,3]
Constraints:
1 <= aliceSizes.length, bobSizes.length <= 10
4
1 <= aliceSizes[i], bobSizes[j] <= 10
5
Alice and Bob have a different total number of candies.
There will be at least one valid answer for the given input.
| null | null |
class Solution {
public:
vector<int> fairCandySwap(vector<int>& aliceSizes, vector<int>& bobSizes) {
int s1 = accumulate(aliceSizes.begin(), aliceSizes.end(), 0);
int s2 = accumulate(bobSizes.begin(), bobSizes.end(), 0);
int diff = (s1 - s2) >> 1;
unordered_set<int> s(bobSizes.begin(), bobSizes.end());
vector<int> ans;
for (int& a : aliceSizes) {
int b = a - diff;
if (s.count(b)) {
ans = vector<int>{a, b};
break;
}
}
return ans;
}
};
| null | null |
func fairCandySwap(aliceSizes []int, bobSizes []int) []int {
s1, s2 := 0, 0
s := map[int]bool{}
for _, a := range aliceSizes {
s1 += a
}
for _, b := range bobSizes {
s2 += b
s[b] = true
}
diff := (s1 - s2) / 2
for _, a := range aliceSizes {
if b := a - diff; s[b] {
return []int{a, b}
}
}
return nil
}
|
class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int s1 = 0, s2 = 0;
Set<Integer> s = new HashSet<>();
for (int a : aliceSizes) {
s1 += a;
}
for (int b : bobSizes) {
s.add(b);
s2 += b;
}
int diff = (s1 - s2) >> 1;
for (int a : aliceSizes) {
int b = a - diff;
if (s.contains(b)) {
return new int[] {a, b};
}
}
return null;
}
}
| null | null | null | null | null | null |
class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
diff = (sum(aliceSizes) - sum(bobSizes)) >> 1
s = set(bobSizes)
for a in aliceSizes:
if (b := (a - diff)) in s:
return [a, b]
| null | null | null | null | null |
function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
const s1 = aliceSizes.reduce((acc, cur) => acc + cur, 0);
const s2 = bobSizes.reduce((acc, cur) => acc + cur, 0);
const diff = (s1 - s2) >> 1;
const s = new Set(bobSizes);
for (const a of aliceSizes) {
const b = a - diff;
if (s.has(b)) {
return [a, b];
}
}
return [];
}
|
Tallest Billboard
|
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of
rods
that can be welded together. For example, if you have rods of lengths
1
,
2
, and
3
, you can weld them together to make a support of length
6
.
Return
the largest possible height of your billboard installation
. If you cannot support the billboard, return
0
.
Example 1:
Input:
rods = [1,2,3,6]
Output:
6
Explanation:
We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input:
rods = [1,2,3,4,5,6]
Output:
10
Explanation:
We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input:
rods = [1,2]
Output:
0
Explanation:
The billboard cannot be supported, so we return 0.
Constraints:
1 <= rods.length <= 20
1 <= rods[i] <= 1000
sum(rods[i]) <= 5000
| null | null |
class Solution {
public:
int tallestBillboard(vector<int>& rods) {
int n = rods.size();
int s = accumulate(rods.begin(), rods.end(), 0);
int f[n + 1][s + 1];
memset(f, -0x3f, sizeof(f));
f[0][0] = 0;
for (int i = 1, t = 0; i <= n; ++i) {
int x = rods[i - 1];
t += x;
for (int j = 0; j <= t; ++j) {
f[i][j] = f[i - 1][j];
if (j >= x) {
f[i][j] = max(f[i][j], f[i - 1][j - x]);
}
if (j + x <= t) {
f[i][j] = max(f[i][j], f[i - 1][j + x] + x);
}
if (j < x) {
f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j);
}
}
}
return f[n][0];
}
};
| null | null |
func tallestBillboard(rods []int) int {
n := len(rods)
s := 0
for _, x := range rods {
s += x
}
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, s+1)
for j := range f[i] {
f[i][j] = -(1 << 30)
}
}
f[0][0] = 0
for i, t := 1, 0; i <= n; i++ {
x := rods[i-1]
t += x
for j := 0; j <= t; j++ {
f[i][j] = f[i-1][j]
if j >= x {
f[i][j] = max(f[i][j], f[i-1][j-x])
}
if j+x <= t {
f[i][j] = max(f[i][j], f[i-1][j+x]+x)
}
if j < x {
f[i][j] = max(f[i][j], f[i-1][x-j]+x-j)
}
}
}
return f[n][0]
}
|
class Solution {
public int tallestBillboard(int[] rods) {
int n = rods.length;
int s = 0;
for (int x : rods) {
s += x;
}
int[][] f = new int[n + 1][s + 1];
for (var e : f) {
Arrays.fill(e, -(1 << 30));
}
f[0][0] = 0;
for (int i = 1, t = 0; i <= n; ++i) {
int x = rods[i - 1];
t += x;
for (int j = 0; j <= t; ++j) {
f[i][j] = f[i - 1][j];
if (j >= x) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - x]);
}
if (j + x <= t) {
f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x);
}
if (j < x) {
f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j);
}
}
}
return f[n][0];
}
}
| null | null | null | null | null | null |
class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
n = len(rods)
s = sum(rods)
f = [[-inf] * (s + 1) for _ in range(n + 1)]
f[0][0] = 0
t = 0
for i, x in enumerate(rods, 1):
t += x
for j in range(t + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = max(f[i][j], f[i - 1][j - x])
if j + x <= t:
f[i][j] = max(f[i][j], f[i - 1][j + x] + x)
if j < x:
f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j)
return f[n][0]
| null | null | null | null | null |
function tallestBillboard(rods: number[]): number {
const s = rods.reduce((a, b) => a + b, 0);
const n = rods.length;
const f = new Array(n).fill(0).map(() => new Array(s + 1).fill(-1));
const dfs = (i: number, j: number): number => {
if (i >= n) {
return j === 0 ? 0 : -(1 << 30);
}
if (f[i][j] !== -1) {
return f[i][j];
}
let ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i]));
ans = Math.max(ans, dfs(i + 1, Math.abs(j - rods[i])) + Math.min(j, rods[i]));
return (f[i][j] = ans);
};
return dfs(0, 0);
}
|
Count All Valid Pickup and Delivery Options
|
Given
n
orders, each order consists of a pickup and a delivery service.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input:
n = 1
Output:
1
Explanation:
Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
Example 2:
Input:
n = 2
Output:
6
Explanation:
All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
Example 3:
Input:
n = 3
Output:
90
Constraints:
1 <= n <= 500
| null | null |
class Solution {
public:
int countOrders(int n) {
const int mod = 1e9 + 7;
long long f = 1;
for (int i = 2; i <= n; ++i) {
f = f * i * (2 * i - 1) % mod;
}
return f;
}
};
| null | null |
func countOrders(n int) int {
const mod = 1e9 + 7
f := 1
for i := 2; i <= n; i++ {
f = f * i * (2*i - 1) % mod
}
return f
}
|
class Solution {
public int countOrders(int n) {
final int mod = (int) 1e9 + 7;
long f = 1;
for (int i = 2; i <= n; ++i) {
f = f * i * (2 * i - 1) % mod;
}
return (int) f;
}
}
| null | null | null | null | null | null |
class Solution:
def countOrders(self, n: int) -> int:
mod = 10**9 + 7
f = 1
for i in range(2, n + 1):
f = (f * i * (2 * i - 1)) % mod
return f
| null |
const MOD: i64 = (1e9 as i64) + 7;
impl Solution {
#[allow(dead_code)]
pub fn count_orders(n: i32) -> i32 {
let mut f = 1;
for i in 2..=n as i64 {
f = (i * (2 * i - 1) * f) % MOD;
}
f as i32
}
}
| null | null | null | null |
Build Array Where You Can Find The Maximum Exactly K Comparisons
|
You are given three integers
n
,
m
and
k
. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr
has exactly
n
integers.
1 <= arr[i] <= m
where
(0 <= i < n)
.
After applying the mentioned algorithm to
arr
, the value
search_cost
is equal to
k
.
Return
the number of ways
to build the array
arr
under the mentioned conditions. As the answer may grow large, the answer
must be
computed modulo
10
9
+ 7
.
Example 1:
Input:
n = 2, m = 3, k = 1
Output:
6
Explanation:
The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
Example 2:
Input:
n = 5, m = 2, k = 3
Output:
0
Explanation:
There are no possible arrays that satisfy the mentioned conditions.
Example 3:
Input:
n = 9, m = 1, k = 1
Output:
1
Explanation:
The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n
| null | null |
class Solution {
public:
int numOfArrays(int n, int m, int k) {
if (k == 0) return 0;
int mod = 1e9 + 7;
using ll = long long;
vector<vector<vector<ll>>> dp(n + 1, vector<vector<ll>>(k + 1, vector<ll>(m + 1)));
for (int i = 1; i <= m; ++i) dp[1][1][i] = 1;
for (int i = 2; i <= n; ++i) {
for (int c = 1; c <= min(i, k); ++c) {
for (int j = 1; j <= m; ++j) {
dp[i][c][j] = (dp[i - 1][c][j] * j) % mod;
for (int j0 = 1; j0 < j; ++j0) {
dp[i][c][j] = (dp[i][c][j] + dp[i - 1][c - 1][j0]) % mod;
}
}
}
}
ll ans = 0;
for (int i = 1; i <= m; ++i) ans = (ans + dp[n][k][i]) % mod;
return (int) ans;
}
};
| null | null |
func numOfArrays(n int, m int, k int) int {
if k == 0 {
return 0
}
mod := int(1e9) + 7
dp := make([][][]int, n+1)
for i := range dp {
dp[i] = make([][]int, k+1)
for j := range dp[i] {
dp[i][j] = make([]int, m+1)
}
}
for i := 1; i <= m; i++ {
dp[1][1][i] = 1
}
for i := 2; i <= n; i++ {
for c := 1; c <= k && c <= i; c++ {
for j := 1; j <= m; j++ {
dp[i][c][j] = (dp[i-1][c][j] * j) % mod
for j0 := 1; j0 < j; j0++ {
dp[i][c][j] = (dp[i][c][j] + dp[i-1][c-1][j0]) % mod
}
}
}
}
ans := 0
for i := 1; i <= m; i++ {
ans = (ans + dp[n][k][i]) % mod
}
return ans
}
|
class Solution {
private static final int MOD = (int) 1e9 + 7;
public int numOfArrays(int n, int m, int k) {
if (k == 0) {
return 0;
}
long[][][] dp = new long[n + 1][k + 1][m + 1];
for (int i = 1; i <= m; ++i) {
dp[1][1][i] = 1;
}
for (int i = 2; i <= n; ++i) {
for (int c = 1; c <= Math.min(i, k); ++c) {
for (int j = 1; j <= m; ++j) {
dp[i][c][j] = (dp[i - 1][c][j] * j) % MOD;
for (int j0 = 1; j0 < j; ++j0) {
dp[i][c][j] = (dp[i][c][j] + dp[i - 1][c - 1][j0]) % MOD;
}
}
}
}
long ans = 0;
for (int i = 1; i <= m; ++i) {
ans = (ans + dp[n][k][i]) % MOD;
}
return (int) ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
if k == 0:
return 0
dp = [[[0] * (m + 1) for _ in range(k + 1)] for _ in range(n + 1)]
mod = 10**9 + 7
for i in range(1, m + 1):
dp[1][1][i] = 1
for i in range(2, n + 1):
for c in range(1, min(k + 1, i + 1)):
for j in range(1, m + 1):
dp[i][c][j] = dp[i - 1][c][j] * j
for j0 in range(1, j):
dp[i][c][j] += dp[i - 1][c - 1][j0]
dp[i][c][j] %= mod
ans = 0
for i in range(1, m + 1):
ans += dp[n][k][i]
ans %= mod
return ans
| null | null | null | null | null | null |
Circle and Rectangle Overlapping
|
You are given a circle represented as
(radius, xCenter, yCenter)
and an axis-aligned rectangle represented as
(x1, y1, x2, y2)
, where
(x1, y1)
are the coordinates of the bottom-left corner, and
(x2, y2)
are the coordinates of the top-right corner of the rectangle.
Return
true
if the circle and rectangle are overlapped otherwise return
false
. In other words, check if there is
any
point
(x
i
, y
i
)
that belongs to the circle and the rectangle at the same time.
Example 1:
Input:
radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
Output:
true
Explanation:
Circle and rectangle share the point (1,0).
Example 2:
Input:
radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
Output:
false
Example 3:
Input:
radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
Output:
true
Constraints:
1 <= radius <= 2000
-10
4
<= xCenter, yCenter <= 10
4
-10
4
<= x1 < x2 <= 10
4
-10
4
<= y1 < y2 <= 10
4
| null | null |
class Solution {
public:
bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
auto f = [](int i, int j, int k) -> int {
if (i <= k && k <= j) {
return 0;
}
return k < i ? i - k : k - j;
};
int a = f(x1, x2, xCenter);
int b = f(y1, y2, yCenter);
return a * a + b * b <= radius * radius;
}
};
| null | null |
func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, y2 int) bool {
f := func(i, j, k int) int {
if i <= k && k <= j {
return 0
}
if k < i {
return i - k
}
return k - j
}
a := f(x1, x2, xCenter)
b := f(y1, y2, yCenter)
return a*a+b*b <= radius*radius
}
|
class Solution {
public boolean checkOverlap(
int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {
int a = f(x1, x2, xCenter);
int b = f(y1, y2, yCenter);
return a * a + b * b <= radius * radius;
}
private int f(int i, int j, int k) {
if (i <= k && k <= j) {
return 0;
}
return k < i ? i - k : k - j;
}
}
| null | null | null | null | null | null |
class Solution:
def checkOverlap(
self,
radius: int,
xCenter: int,
yCenter: int,
x1: int,
y1: int,
x2: int,
y2: int,
) -> bool:
def f(i: int, j: int, k: int) -> int:
if i <= k <= j:
return 0
return i - k if k < i else k - j
a = f(x1, x2, xCenter)
b = f(y1, y2, yCenter)
return a * a + b * b <= radius * radius
| null | null | null | null | null |
function checkOverlap(
radius: number,
xCenter: number,
yCenter: number,
x1: number,
y1: number,
x2: number,
y2: number,
): boolean {
const f = (i: number, j: number, k: number) => {
if (i <= k && k <= j) {
return 0;
}
return k < i ? i - k : k - j;
};
const a = f(x1, x2, xCenter);
const b = f(y1, y2, yCenter);
return a * a + b * b <= radius * radius;
}
|
Most Profitable Path in a Tree
|
There is an undirected tree with
n
nodes labeled from
0
to
n - 1
, rooted at node
0
. You are given a 2D integer array
edges
of length
n - 1
where
edges[i] = [a
i
, b
i
]
indicates that there is an edge between nodes
a
i
and
b
i
in the tree.
At every node
i
, there is a gate. You are also given an array of even integers
amount
, where
amount[i]
represents:
the price needed to open the gate at node
i
, if
amount[i]
is negative, or,
the cash reward obtained on opening the gate at node
i
, otherwise.
The game goes on as follows:
Initially, Alice is at node
0
and Bob is at node
bob
.
At every second, Alice and Bob
each
move to an adjacent node. Alice moves towards some
leaf node
, while Bob moves towards node
0
.
For
every
node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:
If the gate is
already open
, no price will be required, nor will there be any cash reward.
If Alice and Bob reach the node
simultaneously
, they share the price/reward for opening the gate there. In other words, if the price to open the gate is
c
, then both Alice and Bob pay
c / 2
each. Similarly, if the reward at the gate is
c
, both of them receive
c / 2
each.
If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node
0
, he stops moving. Note that these events are
independent
of each other.
Return
the
maximum
net income Alice can have if she travels towards the optimal leaf node.
Example 1:
Input:
edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Output:
6
Explanation:
The above diagram represents the given tree. The game goes as follows:
- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.
Alice's net income is now -2.
- Both Alice and Bob move to node 1.
Since they reach here simultaneously, they open the gate together and share the reward.
Alice's net income becomes -2 + (4 / 2) = 0.
- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.
Bob moves on to node 0, and stops moving.
- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.
Now, neither Alice nor Bob can make any further moves, and the game ends.
It is not possible for Alice to get a higher net income.
Example 2:
Input:
edges = [[0,1]], bob = 1, amount = [-7280,2350]
Output:
-7280
Explanation:
Alice follows the path 0->1 whereas Bob follows the path 1->0.
Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.
Constraints:
2 <= n <= 10
5
edges.length == n - 1
edges[i].length == 2
0 <= a
i
, b
i
< n
a
i
!= b
i
edges
represents a valid tree.
1 <= bob < n
amount.length == n
amount[i]
is an
even
integer in the range
[-10
4
, 10
4
]
.
| null | null |
class Solution {
public:
int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) {
int n = edges.size() + 1;
vector<vector<int>> g(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].emplace_back(b);
g[b].emplace_back(a);
}
vector<int> ts(n, n);
function<bool(int i, int fa, int t)> dfs1 = [&](int i, int fa, int t) -> bool {
if (i == 0) {
ts[i] = t;
return true;
}
for (int j : g[i]) {
if (j != fa && dfs1(j, i, t + 1)) {
ts[j] = min(ts[j], t + 1);
return true;
}
}
return false;
};
dfs1(bob, -1, 0);
ts[bob] = 0;
int ans = INT_MIN;
function<void(int i, int fa, int t, int v)> dfs2 = [&](int i, int fa, int t, int v) {
if (t == ts[i])
v += amount[i] >> 1;
else if (t < ts[i])
v += amount[i];
if (g[i].size() == 1 && g[i][0] == fa) {
ans = max(ans, v);
return;
}
for (int j : g[i])
if (j != fa) dfs2(j, i, t + 1, v);
};
dfs2(0, -1, 0, 0);
return ans;
}
};
| null | null |
func mostProfitablePath(edges [][]int, bob int, amount []int) int {
n := len(edges) + 1
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)
}
ts := make([]int, n)
for i := range ts {
ts[i] = n
}
var dfs1 func(int, int, int) bool
dfs1 = func(i, fa, t int) bool {
if i == 0 {
ts[i] = min(ts[i], t)
return true
}
for _, j := range g[i] {
if j != fa && dfs1(j, i, t+1) {
ts[j] = min(ts[j], t+1)
return true
}
}
return false
}
dfs1(bob, -1, 0)
ts[bob] = 0
ans := -0x3f3f3f3f
var dfs2 func(int, int, int, int)
dfs2 = func(i, fa, t, v int) {
if t == ts[i] {
v += amount[i] >> 1
} else if t < ts[i] {
v += amount[i]
}
if len(g[i]) == 1 && g[i][0] == fa {
ans = max(ans, v)
return
}
for _, j := range g[i] {
if j != fa {
dfs2(j, i, t+1, v)
}
}
}
dfs2(0, -1, 0, 0)
return ans
}
|
class Solution {
private List<Integer>[] g;
private int[] amount;
private int[] ts;
private int ans = Integer.MIN_VALUE;
public int mostProfitablePath(int[][] edges, int bob, int[] amount) {
int n = edges.length + 1;
g = new List[n];
ts = new int[n];
this.amount = amount;
Arrays.setAll(g, k -> new ArrayList<>());
Arrays.fill(ts, n);
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
dfs1(bob, -1, 0);
ts[bob] = 0;
dfs2(0, -1, 0, 0);
return ans;
}
private boolean dfs1(int i, int fa, int t) {
if (i == 0) {
ts[i] = Math.min(ts[i], t);
return true;
}
for (int j : g[i]) {
if (j != fa && dfs1(j, i, t + 1)) {
ts[j] = Math.min(ts[j], t + 1);
return true;
}
}
return false;
}
private void dfs2(int i, int fa, int t, int v) {
if (t == ts[i]) {
v += amount[i] >> 1;
} else if (t < ts[i]) {
v += amount[i];
}
if (g[i].size() == 1 && g[i].get(0) == fa) {
ans = Math.max(ans, v);
return;
}
for (int j : g[i]) {
if (j != fa) {
dfs2(j, i, t + 1, v);
}
}
}
}
| null | null | null | null | null | null |
class Solution:
def mostProfitablePath(
self, edges: List[List[int]], bob: int, amount: List[int]
) -> int:
def dfs1(i, fa, t):
if i == 0:
ts[i] = min(ts[i], t)
return True
for j in g[i]:
if j != fa and dfs1(j, i, t + 1):
ts[j] = min(ts[j], t + 1)
return True
return False
def dfs2(i, fa, t, v):
if t == ts[i]:
v += amount[i] // 2
elif t < ts[i]:
v += amount[i]
nonlocal ans
if len(g[i]) == 1 and g[i][0] == fa:
ans = max(ans, v)
return
for j in g[i]:
if j != fa:
dfs2(j, i, t + 1, v)
n = len(edges) + 1
g = defaultdict(list)
ts = [n] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
dfs1(bob, -1, 0)
ts[bob] = 0
ans = -inf
dfs2(0, -1, 0, 0)
return ans
| null | null | null | null | null | null |
Minimum Seconds to Equalize a Circular Array
|
You are given a
0-indexed
array
nums
containing
n
integers.
At each second, you perform the following operation on the array:
For every index
i
in the range
[0, n - 1]
, replace
nums[i]
with either
nums[i]
,
nums[(i - 1 + n) % n]
, or
nums[(i + 1) % n]
.
Note
that all the elements get replaced simultaneously.
Return
the
minimum
number of seconds needed to make all elements in the array
nums
equal
.
Example 1:
Input:
nums = [1,2,1,2]
Output:
1
Explanation:
We can equalize the array in 1 second in the following way:
- At 1
st
second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
Example 2:
Input:
nums = [2,1,3,3,2]
Output:
2
Explanation:
We can equalize the array in 2 seconds in the following way:
- At 1
st
second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2
nd
second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
Example 3:
Input:
nums = [5,5,5,5]
Output:
0
Explanation:
We don't need to perform any operations as all elements in the initial array are the same.
Constraints:
1 <= n == nums.length <= 10
5
1 <= nums[i] <= 10
9
| null | null |
class Solution {
public:
int minimumSeconds(vector<int>& nums) {
unordered_map<int, vector<int>> d;
int n = nums.size();
for (int i = 0; i < n; ++i) {
d[nums[i]].push_back(i);
}
int ans = 1 << 30;
for (auto& [_, idx] : d) {
int m = idx.size();
int t = idx[0] + n - idx[m - 1];
for (int i = 1; i < m; ++i) {
t = max(t, idx[i] - idx[i - 1]);
}
ans = min(ans, t / 2);
}
return ans;
}
};
| null | null |
func minimumSeconds(nums []int) int {
d := map[int][]int{}
for i, x := range nums {
d[x] = append(d[x], i)
}
ans := 1 << 30
n := len(nums)
for _, idx := range d {
m := len(idx)
t := idx[0] + n - idx[m-1]
for i := 1; i < m; i++ {
t = max(t, idx[i]-idx[i-1])
}
ans = min(ans, t/2)
}
return ans
}
|
class Solution {
public int minimumSeconds(List<Integer> nums) {
Map<Integer, List<Integer>> d = new HashMap<>();
int n = nums.size();
for (int i = 0; i < n; ++i) {
d.computeIfAbsent(nums.get(i), k -> new ArrayList<>()).add(i);
}
int ans = 1 << 30;
for (List<Integer> idx : d.values()) {
int m = idx.size();
int t = idx.get(0) + n - idx.get(m - 1);
for (int i = 1; i < m; ++i) {
t = Math.max(t, idx.get(i) - idx.get(i - 1));
}
ans = Math.min(ans, t / 2);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minimumSeconds(self, nums: List[int]) -> int:
d = defaultdict(list)
for i, x in enumerate(nums):
d[x].append(i)
ans = inf
n = len(nums)
for idx in d.values():
t = idx[0] + n - idx[-1]
for i, j in pairwise(idx):
t = max(t, j - i)
ans = min(ans, t // 2)
return ans
| null | null | null | null | null |
function minimumSeconds(nums: number[]): number {
const d: Map<number, number[]> = new Map();
const n = nums.length;
for (let i = 0; i < n; ++i) {
if (!d.has(nums[i])) {
d.set(nums[i], []);
}
d.get(nums[i])!.push(i);
}
let ans = 1 << 30;
for (const [_, idx] of d) {
const m = idx.length;
let t = idx[0] + n - idx[m - 1];
for (let i = 1; i < m; ++i) {
t = Math.max(t, idx[i] - idx[i - 1]);
}
ans = Math.min(ans, t >> 1);
}
return ans;
}
|
Minimum Number of Days to Disconnect Island
|
You are given an
m x n
binary grid
grid
where
1
represents land and
0
represents water. An
island
is a maximal
4-directionally
(horizontal or vertical) connected group of
1
's.
The grid is said to be
connected
if we have
exactly one island
, otherwise is said
disconnected
.
In one day, we are allowed to change
any
single land cell
(1)
into a water cell
(0)
.
Return
the minimum number of days to disconnect the grid
.
Example 1:
Input:
grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
Output:
2
Explanation:
We need at least 2 days to get a disconnected grid.
Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
Example 2:
Input:
grid = [[1,1]]
Output:
2
Explanation:
Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j]
is either
0
or
1
.
| null | null |
class Solution {
public:
const vector<int> dirs = {-1, 0, 1, 0, -1};
int m, n;
int minDays(vector<vector<int>>& grid) {
m = grid.size(), n = grid[0].size();
if (count(grid) != 1) {
return 0;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
grid[i][j] = 0;
if (count(grid) != 1) {
return 1;
}
grid[i][j] = 1;
}
}
}
return 2;
}
int count(vector<vector<int>>& grid) {
int cnt = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
dfs(i, j, grid);
++cnt;
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 2) {
grid[i][j] = 1;
}
}
}
return cnt;
}
void dfs(int i, int j, vector<vector<int>>& grid) {
grid[i][j] = 2;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
dfs(x, y, grid);
}
}
}
};
| null | null |
func minDays(grid [][]int) int {
m, n := len(grid), len(grid[0])
dirs := []int{-1, 0, 1, 0, -1}
var dfs func(i, j int)
dfs = func(i, j int) {
grid[i][j] = 2
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 {
dfs(x, y)
}
}
}
count := func() int {
cnt := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
dfs(i, j)
cnt++
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 2 {
grid[i][j] = 1
}
}
}
return cnt
}
if count() != 1 {
return 0
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
grid[i][j] = 0
if count() != 1 {
return 1
}
grid[i][j] = 1
}
}
}
return 2
}
|
class Solution {
private static final int[] DIRS = new int[] {-1, 0, 1, 0, -1};
private int[][] grid;
private int m;
private int n;
public int minDays(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
if (count() != 1) {
return 0;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
grid[i][j] = 0;
if (count() != 1) {
return 1;
}
grid[i][j] = 1;
}
}
}
return 2;
}
private int count() {
int cnt = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
dfs(i, j);
++cnt;
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 2) {
grid[i][j] = 1;
}
}
}
return cnt;
}
private void dfs(int i, int j) {
grid[i][j] = 2;
for (int k = 0; k < 4; ++k) {
int x = i + DIRS[k], y = j + DIRS[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
dfs(x, y);
}
}
}
}
|
/**
* @param {number[][]} grid
* @return {number}
*/
var minDays = function (grid) {
const dirs = [-1, 0, 1, 0, -1];
const [m, n] = [grid.length, grid[0].length];
const dfs = (i, j, visited) => {
if (i < 0 || m <= i || j < 0 || n <= j || grid[i][j] === 0 || visited[i][j]) {
return;
}
visited[i][j] = true;
for (let d = 0; d < 4; d++) {
const [y, x] = [i + dirs[d], j + dirs[d + 1]];
dfs(y, x, visited);
}
};
const count = () => {
const vis = Array.from({ length: m }, () => Array(n).fill(false));
let c = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1 && !vis[i][j]) {
c++;
dfs(i, j, vis);
}
}
}
return c;
};
if (count() !== 1) return 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
grid[i][j] = 0;
if (count() !== 1) return 1;
grid[i][j] = 1;
}
}
}
return 2;
};
| null | null | null | null | null |
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
if self.count(grid) != 1:
return 0
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = 0
if self.count(grid) != 1:
return 1
grid[i][j] = 1
return 2
def count(self, grid):
def dfs(i, j):
grid[i][j] = 2
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
dfs(x, y)
m, n = len(grid), len(grid[0])
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
dfs(i, j)
cnt += 1
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
grid[i][j] = 1
return cnt
| null | null | null | null | null |
function minDays(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
const dfs = (i: number, j: number) => {
if (i < 0 || m <= i || j < 0 || n <= j || [0, 2].includes(grid[i][j])) return;
grid[i][j] = 2;
const dir = [-1, 0, 1, 0, -1];
for (let k = 0; k < 4; k++) {
const [y, x] = [i + dir[k], j + dir[k + 1]];
dfs(y, x);
}
};
const count = () => {
let c = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
dfs(i, j);
c++;
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 2) {
grid[i][j] = 1;
}
}
}
return c;
};
if (count() !== 1) return 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
grid[i][j] = 0;
if (count() !== 1) return 1;
grid[i][j] = 1;
}
}
}
return 2;
}
|
Burst Balloons
|
You are given
n
balloons, indexed from
0
to
n - 1
. Each balloon is painted with a number on it represented by an array
nums
. You are asked to burst all the balloons.
If you burst the
i
th
balloon, you will get
nums[i - 1] * nums[i] * nums[i + 1]
coins. If
i - 1
or
i + 1
goes out of bounds of the array, then treat it as if there is a balloon with a
1
painted on it.
Return
the maximum coins you can collect by bursting the balloons wisely
.
Example 1:
Input:
nums = [3,1,5,8]
Output:
167
Explanation:
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
Example 2:
Input:
nums = [1,5]
Output:
10
Constraints:
n == nums.length
1 <= n <= 300
0 <= nums[i] <= 100
| null | null |
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
vector<int> arr(n + 2, 1);
for (int i = 0; i < n; ++i) {
arr[i + 1] = nums[i];
}
vector<vector<int>> f(n + 2, vector<int>(n + 2, 0));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 2; j <= n + 1; ++j) {
for (int k = i + 1; k < j; ++k) {
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
};
| null | null |
func maxCoins(nums []int) int {
n := len(nums)
arr := make([]int, n+2)
arr[0] = 1
arr[n+1] = 1
copy(arr[1:], nums)
f := make([][]int, n+2)
for i := range f {
f[i] = make([]int, n+2)
}
for i := n - 1; i >= 0; i-- {
for j := i + 2; j <= n+1; j++ {
for k := i + 1; k < j; k++ {
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i]*arr[k]*arr[j])
}
}
}
return f[0][n+1]
}
|
class Solution {
public int maxCoins(int[] nums) {
int n = nums.length;
int[] arr = new int[n + 2];
arr[0] = 1;
arr[n + 1] = 1;
System.arraycopy(nums, 0, arr, 1, n);
int[][] f = new int[n + 2][n + 2];
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 2; j <= n + 1; j++) {
for (int k = i + 1; k < j; k++) {
f[i][j] = Math.max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
}
| null | null | null | null | null | null |
class Solution:
def maxCoins(self, nums: List[int]) -> int:
n = len(nums)
arr = [1] + nums + [1]
f = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n - 1, -1, -1):
for j in range(i + 2, n + 2):
for k in range(i + 1, j):
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j])
return f[0][-1]
| null |
impl Solution {
pub fn max_coins(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut arr = vec![1; n + 2];
for i in 0..n {
arr[i + 1] = nums[i];
}
let mut f = vec![vec![0; n + 2]; n + 2];
for i in (0..n).rev() {
for j in i + 2..n + 2 {
for k in i + 1..j {
f[i][j] = f[i][j].max(f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
f[0][n + 1]
}
}
| null | null | null |
function maxCoins(nums: number[]): number {
const n = nums.length;
const arr = Array(n + 2).fill(1);
for (let i = 0; i < n; i++) {
arr[i + 1] = nums[i];
}
const f: number[][] = Array.from({ length: n + 2 }, () => Array(n + 2).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 2; j <= n + 1; j++) {
for (let k = i + 1; k < j; k++) {
f[i][j] = Math.max(f[i][j], f[i][k] + f[k][j] + arr[i] * arr[k] * arr[j]);
}
}
}
return f[0][n + 1];
}
|
Bomb Enemy 🔒
|
Given an
m x n
matrix
grid
where each cell is either a wall
'W'
, an enemy
'E'
or empty
'0'
, return
the maximum enemies you can kill using one bomb
. You can only place the bomb in an empty cell.
The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.
Example 1:
Input:
grid = [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output:
3
Example 2:
Input:
grid = [["W","W","W"],["0","0","0"],["E","E","E"]]
Output:
1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j]
is either
'W'
,
'E'
, or
'0'
.
| null | null |
class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> g(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
int t = 0;
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 'W')
t = 0;
else if (grid[i][j] == 'E')
++t;
g[i][j] += t;
}
t = 0;
for (int j = n - 1; j >= 0; --j) {
if (grid[i][j] == 'W')
t = 0;
else if (grid[i][j] == 'E')
++t;
g[i][j] += t;
}
}
for (int j = 0; j < n; ++j) {
int t = 0;
for (int i = 0; i < m; ++i) {
if (grid[i][j] == 'W')
t = 0;
else if (grid[i][j] == 'E')
++t;
g[i][j] += t;
}
t = 0;
for (int i = m - 1; i >= 0; --i) {
if (grid[i][j] == 'W')
t = 0;
else if (grid[i][j] == 'E')
++t;
g[i][j] += t;
}
}
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '0') ans = max(ans, g[i][j]);
}
}
return ans;
}
};
| null | null |
func maxKilledEnemies(grid [][]byte) int {
m, n := len(grid), len(grid[0])
g := make([][]int, m)
for i := range g {
g[i] = make([]int, n)
}
for i := 0; i < m; i++ {
t := 0
for j := 0; j < n; j++ {
if grid[i][j] == 'W' {
t = 0
} else if grid[i][j] == 'E' {
t++
}
g[i][j] += t
}
t = 0
for j := n - 1; j >= 0; j-- {
if grid[i][j] == 'W' {
t = 0
} else if grid[i][j] == 'E' {
t++
}
g[i][j] += t
}
}
for j := 0; j < n; j++ {
t := 0
for i := 0; i < m; i++ {
if grid[i][j] == 'W' {
t = 0
} else if grid[i][j] == 'E' {
t++
}
g[i][j] += t
}
t = 0
for i := m - 1; i >= 0; i-- {
if grid[i][j] == 'W' {
t = 0
} else if grid[i][j] == 'E' {
t++
}
g[i][j] += t
}
}
ans := 0
for i, row := range grid {
for j, v := range row {
if v == '0' && ans < g[i][j] {
ans = g[i][j]
}
}
}
return ans
}
|
class Solution {
public int maxKilledEnemies(char[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] g = new int[m][n];
for (int i = 0; i < m; ++i) {
int t = 0;
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 'W') {
t = 0;
} else if (grid[i][j] == 'E') {
++t;
}
g[i][j] += t;
}
t = 0;
for (int j = n - 1; j >= 0; --j) {
if (grid[i][j] == 'W') {
t = 0;
} else if (grid[i][j] == 'E') {
++t;
}
g[i][j] += t;
}
}
for (int j = 0; j < n; ++j) {
int t = 0;
for (int i = 0; i < m; ++i) {
if (grid[i][j] == 'W') {
t = 0;
} else if (grid[i][j] == 'E') {
++t;
}
g[i][j] += t;
}
t = 0;
for (int i = m - 1; i >= 0; --i) {
if (grid[i][j] == 'W') {
t = 0;
} else if (grid[i][j] == 'E') {
++t;
}
g[i][j] += t;
}
}
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '0') {
ans = Math.max(ans, g[i][j]);
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maxKilledEnemies(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
g = [[0] * n for _ in range(m)]
for i in range(m):
t = 0
for j in range(n):
if grid[i][j] == 'W':
t = 0
elif grid[i][j] == 'E':
t += 1
g[i][j] += t
t = 0
for j in range(n - 1, -1, -1):
if grid[i][j] == 'W':
t = 0
elif grid[i][j] == 'E':
t += 1
g[i][j] += t
for j in range(n):
t = 0
for i in range(m):
if grid[i][j] == 'W':
t = 0
elif grid[i][j] == 'E':
t += 1
g[i][j] += t
t = 0
for i in range(m - 1, -1, -1):
if grid[i][j] == 'W':
t = 0
elif grid[i][j] == 'E':
t += 1
g[i][j] += t
return max(
[g[i][j] for i in range(m) for j in range(n) if grid[i][j] == '0'],
default=0,
)
| null | null | null | null | null | null |
Stone Game III
|
Alice and Bob continue their games with piles of stones. There are several stones
arranged in a row
, and each stone has an associated value which is an integer given in the array
stoneValue
.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take
1
,
2
, or
3
stones from the
first
remaining stones in the row.
The score of each player is the sum of the values of the stones taken. The score of each player is
0
initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
Assume Alice and Bob
play optimally
.
Return
"Alice"
if Alice will win,
"Bob"
if Bob will win, or
"Tie"
if they will end the game with the same score
.
Example 1:
Input:
stoneValue = [1,2,3,7]
Output:
"Bob"
Explanation:
Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.
Example 2:
Input:
stoneValue = [1,2,3,-9]
Output:
"Alice"
Explanation:
Alice must choose all the three piles at the first move to win and leave Bob with negative score.
If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.
If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.
Remember that both play optimally so here Alice will choose the scenario that makes her win.
Example 3:
Input:
stoneValue = [1,2,3,6]
Output:
"Tie"
Explanation:
Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.
Constraints:
1 <= stoneValue.length <= 5 * 10
4
-1000 <= stoneValue[i] <= 1000
| null | null |
class Solution {
public:
string stoneGameIII(vector<int>& stoneValue) {
int n = stoneValue.size();
int f[n];
memset(f, 0x3f, sizeof(f));
function<int(int)> dfs = [&](int i) -> int {
if (i >= n) {
return 0;
}
if (f[i] != 0x3f3f3f3f) {
return f[i];
}
int ans = -(1 << 30), s = 0;
for (int j = 0; j < 3 && i + j < n; ++j) {
s += stoneValue[i + j];
ans = max(ans, s - dfs(i + j + 1));
}
return f[i] = ans;
};
int ans = dfs(0);
if (ans == 0) {
return "Tie";
}
return ans > 0 ? "Alice" : "Bob";
}
};
| null | null |
func stoneGameIII(stoneValue []int) string {
n := len(stoneValue)
f := make([]int, n)
const inf = 1 << 30
for i := range f {
f[i] = inf
}
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] != inf {
return f[i]
}
ans, s := -(1 << 30), 0
for j := 0; j < 3 && i+j < n; j++ {
s += stoneValue[i+j]
ans = max(ans, s-dfs(i+j+1))
}
f[i] = ans
return ans
}
ans := dfs(0)
if ans == 0 {
return "Tie"
}
if ans > 0 {
return "Alice"
}
return "Bob"
}
|
class Solution {
private int[] stoneValue;
private Integer[] f;
private int n;
public String stoneGameIII(int[] stoneValue) {
n = stoneValue.length;
f = new Integer[n];
this.stoneValue = stoneValue;
int ans = dfs(0);
if (ans == 0) {
return "Tie";
}
return ans > 0 ? "Alice" : "Bob";
}
private int dfs(int i) {
if (i >= n) {
return 0;
}
if (f[i] != null) {
return f[i];
}
int ans = -(1 << 30);
int s = 0;
for (int j = 0; j < 3 && i + j < n; ++j) {
s += stoneValue[i + j];
ans = Math.max(ans, s - dfs(i + j + 1));
}
return f[i] = ans;
}
}
| null | null | null | null | null | null |
class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
ans, s = -inf, 0
for j in range(3):
if i + j >= n:
break
s += stoneValue[i + j]
ans = max(ans, s - dfs(i + j + 1))
return ans
n = len(stoneValue)
ans = dfs(0)
if ans == 0:
return 'Tie'
return 'Alice' if ans > 0 else 'Bob'
| null | null | null | null | null |
function stoneGameIII(stoneValue: number[]): string {
const n = stoneValue.length;
const inf = 1 << 30;
const f: number[] = new Array(n).fill(inf);
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i] !== inf) {
return f[i];
}
let ans = -inf;
let s = 0;
for (let j = 0; j < 3 && i + j < n; ++j) {
s += stoneValue[i + j];
ans = Math.max(ans, s - dfs(i + j + 1));
}
return (f[i] = ans);
};
const ans = dfs(0);
if (ans === 0) {
return 'Tie';
}
return ans > 0 ? 'Alice' : 'Bob';
}
|
Sorting the Sentence
|
A
sentence
is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be
shuffled
by appending the
1-indexed word position
to each word then rearranging the words in the sentence.
For example, the sentence
"This is a sentence"
can be shuffled as
"sentence4 a3 is2 This1"
or
"is2 sentence4 This1 a3"
.
Given a
shuffled sentence
s
containing no more than
9
words, reconstruct and return
the original sentence
.
Example 1:
Input:
s = "is2 sentence4 This1 a3"
Output:
"This is a sentence"
Explanation:
Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Example 2:
Input:
s = "Myself2 Me1 I4 and3"
Output:
"Me Myself and I"
Explanation:
Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Constraints:
2 <= s.length <= 200
s
consists of lowercase and uppercase English letters, spaces, and digits from
1
to
9
.
The number of words in
s
is between
1
and
9
.
The words in
s
are separated by a single space.
s
contains no leading or trailing spaces.
| null | null |
class Solution {
public:
string sortSentence(string s) {
istringstream iss(s);
string w;
vector<string> ws;
while (iss >> w) {
ws.push_back(w);
}
vector<string> ss(ws.size());
for (auto& w : ws) {
ss[w.back() - '1'] = w.substr(0, w.size() - 1);
}
string ans;
for (auto& w : ss) {
ans += w + " ";
}
ans.pop_back();
return ans;
}
};
| null | null |
func sortSentence(s string) string {
ws := strings.Split(s, " ")
ans := make([]string, len(ws))
for _, w := range ws {
ans[w[len(w)-1]-'1'] = w[:len(w)-1]
}
return strings.Join(ans, " ")
}
|
class Solution {
public String sortSentence(String s) {
String[] ws = s.split(" ");
int n = ws.length;
String[] ans = new String[n];
for (int i = 0; i < n; ++i) {
String w = ws[i];
ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1);
}
return String.join(" ", ans);
}
}
|
/**
* @param {string} s
* @return {string}
*/
var sortSentence = function (s) {
const ws = s.split(' ');
const ans = Array(ws.length);
for (const w of ws) {
ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
};
| null | null | null | null | null |
class Solution:
def sortSentence(self, s: str) -> str:
ws = s.split()
ans = [None] * len(ws)
for w in ws:
ans[int(w[-1]) - 1] = w[:-1]
return " ".join(ans)
| null | null | null | null | null |
function sortSentence(s: string): string {
const ws = s.split(' ');
const ans = Array(ws.length);
for (const w of ws) {
ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
}
|
Merge Nodes in Between Zeros
|
You are given the
head
of a linked list, which contains a series of integers
separated
by
0
's. The
beginning
and
end
of the linked list will have
Node.val == 0
.
For
every
two consecutive
0
's,
merge
all the nodes lying in between them into a single node whose value is the
sum
of all the merged nodes. The modified list should not contain any
0
's.
Return
the
head
of the modified linked list
.
Example 1:
Input:
head = [0,3,1,0,4,5,2,0]
Output:
[4,11]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
Example 2:
Input:
head = [0,1,0,3,0,2,2,0]
Output:
[1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
Constraints:
The number of nodes in the list is in the range
[3, 2 * 10
5
]
.
0 <= Node.val <= 1000
There are
no
two consecutive nodes with
Node.val == 0
.
The
beginning
and
end
of the linked list have
Node.val == 0
.
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeNodes(struct ListNode* head) {
struct ListNode dummy;
struct ListNode* cur = &dummy;
int sum = 0;
while (head) {
if (head->val == 0 && sum != 0) {
cur->next = malloc(sizeof(struct ListNode));
cur->next->val = sum;
cur->next->next = NULL;
cur = cur->next;
sum = 0;
}
sum += head->val;
head = head->next;
}
return dummy.next;
}
| null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode* dummy = new ListNode();
ListNode* tail = dummy;
int s = 0;
for (ListNode* cur = head->next; cur; cur = cur->next) {
if (cur->val) {
s += cur->val;
} else {
tail->next = new ListNode(s);
tail = tail->next;
s = 0;
}
}
return dummy->next;
}
};
| null | null |
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeNodes(head *ListNode) *ListNode {
dummy := &ListNode{}
tail := dummy
s := 0
for cur := head.Next; cur != nil; cur = cur.Next {
if cur.Val != 0 {
s += cur.Val
} else {
tail.Next = &ListNode{Val: s}
tail = tail.Next
s = 0
}
}
return dummy.Next
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeNodes(ListNode head) {
ListNode dummy = new ListNode();
int s = 0;
ListNode tail = dummy;
for (ListNode cur = head.next; cur != null; cur = cur.next) {
if (cur.val != 0) {
s += cur.val;
} else {
tail.next = new ListNode(s);
tail = tail.next;
s = 0;
}
}
return dummy.next;
}
}
| null | null | null | null | null | null |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = tail = ListNode()
s = 0
cur = head.next
while cur:
if cur.val:
s += cur.val
else:
tail.next = ListNode(s)
tail = tail.next
s = 0
cur = cur.next
return dummy.next
| null |
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = Box::new(ListNode::new(0));
let mut tail = &mut dummy;
let mut s = 0;
let mut cur = head.unwrap().next;
while let Some(mut node) = cur {
if node.val != 0 {
s += node.val;
} else {
tail.next = Some(Box::new(ListNode::new(s)));
tail = tail.next.as_mut().unwrap();
s = 0;
}
cur = node.next.take();
}
dummy.next
}
}
| null | null | null |
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function mergeNodes(head: ListNode | null): ListNode | null {
const dummy = new ListNode();
let tail = dummy;
let s = 0;
for (let cur = head.next; cur; cur = cur.next) {
if (cur.val) {
s += cur.val;
} else {
tail.next = new ListNode(s);
tail = tail.next;
s = 0;
}
}
return dummy.next;
}
|
Number of Unique Categories 🔒
|
You are given an integer
n
and an object
categoryHandler
of class
CategoryHandler
.
There are
n
elements, numbered from
0
to
n - 1
. Each element has a category, and your task is to find the number of unique categories.
The class
CategoryHandler
contains the following function, which may help you:
boolean haveSameCategory(integer a, integer b)
: Returns
true
if
a
and
b
are in the same category and
false
otherwise. Also, if either
a
or
b
is not a valid number (i.e. it's greater than or equal to
n
or less than
0
), it returns
false
.
Return
the number of unique categories.
Example 1:
Input:
n = 6, categoryHandler = [1,1,2,2,3,3]
Output:
3
Explanation:
There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories.
Example 2:
Input:
n = 5, categoryHandler = [1,2,3,4,5]
Output:
5
Explanation:
There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories.
Example 3:
Input:
n = 3, categoryHandler = [1,1,1]
Output:
1
Explanation:
There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category.
Constraints:
1 <= n <= 100
| null | null |
/**
* Definition for a category handler.
* class CategoryHandler {
* public:
* CategoryHandler(vector<int> categories);
* bool haveSameCategory(int a, int b);
* };
*/
class Solution {
public:
int numberOfCategories(int n, CategoryHandler* categoryHandler) {
vector<int> p(n);
iota(p.begin(), p.end(), 0);
function<int(int)> find = [&](int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
for (int a = 0; a < n; ++a) {
for (int b = a + 1; b < n; ++b) {
if (categoryHandler->haveSameCategory(a, b)) {
p[find(a)] = find(b);
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += i == p[i];
}
return ans;
}
};
| null | null |
/**
* Definition for a category handler.
* type CategoryHandler interface {
* HaveSameCategory(int, int) bool
* }
*/
func numberOfCategories(n int, categoryHandler CategoryHandler) (ans int) {
p := make([]int, n)
for i := range p {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
for a := 0; a < n; a++ {
for b := a + 1; b < n; b++ {
if categoryHandler.HaveSameCategory(a, b) {
p[find(a)] = find(b)
}
}
}
for i, x := range p {
if i == x {
ans++
}
}
return
}
|
/**
* Definition for a category handler.
* class CategoryHandler {
* public CategoryHandler(int[] categories);
* public boolean haveSameCategory(int a, int b);
* };
*/
class Solution {
private int[] p;
public int numberOfCategories(int n, CategoryHandler categoryHandler) {
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
for (int a = 0; a < n; ++a) {
for (int b = a + 1; b < n; ++b) {
if (categoryHandler.haveSameCategory(a, b)) {
p[find(a)] = find(b);
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (i == p[i]) {
++ans;
}
}
return ans;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
| null | null | null | null | null | null |
# Definition for a category handler.
# class CategoryHandler:
# def haveSameCategory(self, a: int, b: int) -> bool:
# pass
class Solution:
def numberOfCategories(
self, n: int, categoryHandler: Optional['CategoryHandler']
) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
for a in range(n):
for b in range(a + 1, n):
if categoryHandler.haveSameCategory(a, b):
p[find(a)] = find(b)
return sum(i == x for i, x in enumerate(p))
| null | null | null | null | null |
/**
* Definition for a category handler.
* class CategoryHandler {
* constructor(categories: number[]);
* public haveSameCategory(a: number, b: number): boolean;
* }
*/
function numberOfCategories(n: number, categoryHandler: CategoryHandler): number {
const p: number[] = new Array(n).fill(0).map((_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
for (let a = 0; a < n; ++a) {
for (let b = a + 1; b < n; ++b) {
if (categoryHandler.haveSameCategory(a, b)) {
p[find(a)] = find(b);
}
}
}
let ans = 0;
for (let i = 0; i < n; ++i) {
if (i === p[i]) {
++ans;
}
}
return ans;
}
|
Loan Types 🔒
|
Table:
Loans
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| loan_id | int |
| user_id | int |
| loan_type | varchar |
+-------------+---------+
loan_id is column of unique values for this table.
This table contains loan_id, user_id, and loan_type.
Write a solution to find all
distinct
user_id
's that have
at least one
Refinance
loan type and at least one
Mortgage
loan type.
Return
the result table ordered by
user_id
in
ascending
order
.
The result format is in the following example.
Example 1:
Input:
Loans table:
+---------+---------+-----------+
| loan_id | user_id | loan_type |
+---------+---------+-----------+
| 683 | 101 | Mortgage |
| 218 | 101 | AutoLoan |
| 802 | 101 | Inschool |
| 593 | 102 | Mortgage |
| 138 | 102 | Refinance |
| 294 | 102 | Inschool |
| 308 | 103 | Refinance |
| 389 | 104 | Mortgage |
+---------+---------+-----------+
Output
+---------+
| user_id |
+---------+
| 102 |
+---------+
Explanation
- User_id 101 has three loan types, one of which is a Mortgage. However, this user does not have any loan type categorized as Refinance, so user_id 101 won't be considered.
- User_id 102 possesses three loan types: one for Mortgage and one for Refinance. Hence, user_id 102 will be included in the result.
- User_id 103 has a loan type of Refinance but lacks a Mortgage loan type, so user_id 103 won't be considered.
- User_id 104 has a Mortgage loan type but doesn't have a Refinance loan type, thus, user_id 104 won't be considered.
Output table is ordered by user_id in ascending order.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
SELECT user_id
FROM Loans
GROUP BY 1
HAVING SUM(loan_type = 'Refinance') > 0 AND SUM(loan_type = 'Mortgage') > 0
ORDER BY 1;
| null | null | null | null | null | null | null | null | null | null |
Block Placement Queries
|
There exists an infinite number line, with its origin at 0 and extending towards the
positive
x-axis.
You are given a 2D array
queries
, which contains two types of queries:
For a query of type 1,
queries[i] = [1, x]
. Build an obstacle at distance
x
from the origin. It is guaranteed that there is
no
obstacle at distance
x
when the query is asked.
For a query of type 2,
queries[i] = [2, x, sz]
. Check if it is possible to place a block of size
sz
anywhere
in the range
[0, x]
on the line, such that the block
entirely
lies in the range
[0, x]
. A block
cannot
be placed if it intersects with any obstacle, but it may touch it. Note that you do
not
actually place the block. Queries are separate.
Return a boolean array
results
, where
results[i]
is
true
if you can place the block specified in the
i
th
query of type 2, and
false
otherwise.
Example 1:
Input:
queries = [[1,2],[2,3,3],[2,3,1],[2,2,2]]
Output:
[false,true,true]
Explanation:
For query 0, place an obstacle at
x = 2
. A block of size at most 2 can be placed before
x = 3
.
Example 2:
Input:
queries =
[[1,7],[2,7,6],[1,2],[2,7,5],[2,7,6]]
Output:
[true,true,false]
Explanation:
Place an obstacle at
x = 7
for query 0. A block of size at most 7 can be placed before
x = 7
.
Place an obstacle at
x = 2
for query 2. Now, a block of size at most 5 can be placed before
x = 7
, and a block of size at most 2 before
x = 2
.
Constraints:
1 <= queries.length <= 15 * 10
4
2 <= queries[i].length <= 3
1 <= queries[i][0] <= 2
1 <= x, sz <= min(5 * 10
4
, 3 * queries.length)
The input is generated such that for queries of type 1, no obstacle exists at distance
x
when the query is asked.
The input is generated such that there is at least one query of type 2.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Alt and Tab Simulation 🔒
|
There are
n
windows open numbered from
1
to
n
, we want to simulate using alt + tab to navigate between the windows.
You are given an array
windows
which contains the initial order of the windows (the first element is at the top and the last one is at the bottom).
You are also given an array
queries
where for each query, the window
queries[i]
is brought to the top.
Return the final state of the array
windows
.
Example 1:
Input:
windows = [1,2,3], queries = [3,3,2]
Output:
[2,3,1]
Explanation:
Here is the window array after each query:
Initial order:
[1,2,3]
After the first query:
[
3
,1,2]
After the second query:
[
3
,1,2]
After the last query:
[
2
,3,1]
Example 2:
Input:
windows = [1,4,2,3], queries = [4,1,3]
Output:
[3,1,4,2]
Explanation:
Here is the window array after each query:
Initial order:
[1,4,2,3]
After the first query:
[
4
,1,2,3]
After the second query:
[
1
,4,2,3]
After the last query:
[
3
,1,4,2]
Constraints:
1 <= n == windows.length <= 10
5
windows
is a permutation of
[1, n]
.
1 <= queries.length <= 10
5
1 <= queries[i] <= n
| null | null |
class Solution {
public:
vector<int> simulationResult(vector<int>& windows, vector<int>& queries) {
int n = windows.size();
vector<bool> s(n + 1);
vector<int> ans;
for (int i = queries.size() - 1; ~i; --i) {
int q = queries[i];
if (!s[q]) {
s[q] = true;
ans.push_back(q);
}
}
for (int w : windows) {
if (!s[w]) {
ans.push_back(w);
}
}
return ans;
}
};
| null | null |
func simulationResult(windows []int, queries []int) (ans []int) {
n := len(windows)
s := make([]bool, n+1)
for i := len(queries) - 1; i >= 0; i-- {
q := queries[i]
if !s[q] {
s[q] = true
ans = append(ans, q)
}
}
for _, w := range windows {
if !s[w] {
ans = append(ans, w)
}
}
return
}
|
class Solution {
public int[] simulationResult(int[] windows, int[] queries) {
int n = windows.length;
boolean[] s = new boolean[n + 1];
int[] ans = new int[n];
int k = 0;
for (int i = queries.length - 1; i >= 0; --i) {
int q = queries[i];
if (!s[q]) {
ans[k++] = q;
s[q] = true;
}
}
for (int w : windows) {
if (!s[w]) {
ans[k++] = w;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def simulationResult(self, windows: List[int], queries: List[int]) -> List[int]:
s = set()
ans = []
for q in queries[::-1]:
if q not in s:
ans.append(q)
s.add(q)
for w in windows:
if w not in s:
ans.append(w)
return ans
| null | null | null | null | null |
function simulationResult(windows: number[], queries: number[]): number[] {
const n = windows.length;
const s: boolean[] = Array(n + 1).fill(false);
const ans: number[] = [];
for (let i = queries.length - 1; i >= 0; i--) {
const q = queries[i];
if (!s[q]) {
s[q] = true;
ans.push(q);
}
}
for (const w of windows) {
if (!s[w]) {
ans.push(w);
}
}
return ans;
}
|
Maximum Matching of Players With Trainers
|
You are given a
0-indexed
integer array
players
, where
players[i]
represents the
ability
of the
i
th
player. You are also given a
0-indexed
integer array
trainers
, where
trainers[j]
represents the
training capacity
of the
j
th
trainer.
The
i
th
player can
match
with the
j
th
trainer if the player's ability is
less than or equal to
the trainer's training capacity. Additionally, the
i
th
player can be matched with at most one trainer, and the
j
th
trainer can be matched with at most one player.
Return
the
maximum
number of matchings between
players
and
trainers
that satisfy these conditions.
Example 1:
Input:
players = [4,7,9], trainers = [8,2,5,8]
Output:
2
Explanation:
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 <= 8.
- players[1] can be matched with trainers[3] since 7 <= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
Example 2:
Input:
players = [1,1,1], trainers = [10]
Output:
1
Explanation:
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
Constraints:
1 <= players.length, trainers.length <= 10
5
1 <= players[i], trainers[j] <= 10
9
Note:
This question is the same as
445: Assign Cookies.
| null | null |
class Solution {
public:
int matchPlayersAndTrainers(vector<int>& players, vector<int>& trainers) {
ranges::sort(players);
ranges::sort(trainers);
int m = players.size(), n = trainers.size();
for (int i = 0, j = 0; i < m; ++i, ++j) {
while (j < n && trainers[j] < players[i]) {
++j;
}
if (j == n) {
return i;
}
}
return m;
}
};
| null | null |
func matchPlayersAndTrainers(players []int, trainers []int) int {
sort.Ints(players)
sort.Ints(trainers)
m, n := len(players), len(trainers)
for i, j := 0, 0; i < m; i, j = i+1, j+1 {
for j < n && trainers[j] < players[i] {
j++
}
if j == n {
return i
}
}
return m
}
|
class Solution {
public int matchPlayersAndTrainers(int[] players, int[] trainers) {
Arrays.sort(players);
Arrays.sort(trainers);
int m = players.length, n = trainers.length;
for (int i = 0, j = 0; i < m; ++i, ++j) {
while (j < n && trainers[j] < players[i]) {
++j;
}
if (j == n) {
return i;
}
}
return m;
}
}
| null | null | null | null | null | null |
class Solution:
def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
players.sort()
trainers.sort()
j, n = 0, len(trainers)
for i, p in enumerate(players):
while j < n and trainers[j] < p:
j += 1
if j == n:
return i
j += 1
return len(players)
| null |
impl Solution {
pub fn match_players_and_trainers(mut players: Vec<i32>, mut trainers: Vec<i32>) -> i32 {
players.sort();
trainers.sort();
let mut j = 0;
let n = trainers.len();
for (i, &p) in players.iter().enumerate() {
while j < n && trainers[j] < p {
j += 1;
}
if j == n {
return i as i32;
}
j += 1;
}
players.len() as i32
}
}
| null | null | null |
function matchPlayersAndTrainers(players: number[], trainers: number[]): number {
players.sort((a, b) => a - b);
trainers.sort((a, b) => a - b);
const [m, n] = [players.length, trainers.length];
for (let i = 0, j = 0; i < m; ++i, ++j) {
while (j < n && trainers[j] < players[i]) {
++j;
}
if (j === n) {
return i;
}
}
return m;
}
|
Zero Array Transformation III
|
You are given an integer array
nums
of length
n
and a 2D array
queries
where
queries[i] = [l
i
, r
i
]
.
Each
queries[i]
represents the following action on
nums
:
Decrement the value at each index in the range
[l
i
, r
i
]
in
nums
by
at most
1.
The amount by which the value is decremented can be chosen
independently
for each index.
A
Zero Array
is an array with all its elements equal to 0.
Return the
maximum
number of elements that can be removed from
queries
, such that
nums
can still be converted to a
zero array
using the
remaining
queries. If it is not possible to convert
nums
to a
zero array
, return -1.
Example 1:
Input:
nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]
Output:
1
Explanation:
After removing
queries[2]
,
nums
can still be converted to a zero array.
Using
queries[0]
, decrement
nums[0]
and
nums[2]
by 1 and
nums[1]
by 0.
Using
queries[1]
, decrement
nums[0]
and
nums[2]
by 1 and
nums[1]
by 0.
Example 2:
Input:
nums = [1,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]
Output:
2
Explanation:
We can remove
queries[2]
and
queries[3]
.
Example 3:
Input:
nums = [1,2,3,4], queries = [[0,3]]
Output:
-1
Explanation:
nums
cannot be converted to a zero array even after using all the queries.
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] <= 10
5
1 <= queries.length <= 10
5
queries[i].length == 2
0 <= l
i
<= r
i
< nums.length
| null | null |
class Solution {
public:
int maxRemoval(vector<int>& nums, vector<vector<int>>& queries) {
sort(queries.begin(), queries.end());
priority_queue<int> pq;
int n = nums.size();
vector<int> d(n + 1, 0);
int s = 0, j = 0;
for (int i = 0; i < n; ++i) {
s += d[i];
while (j < queries.size() && queries[j][0] <= i) {
pq.push(queries[j][1]);
++j;
}
while (s < nums[i] && !pq.empty() && pq.top() >= i) {
++s;
int end = pq.top();
pq.pop();
--d[end + 1];
}
if (s < nums[i]) {
return -1;
}
}
return pq.size();
}
};
| null | null |
func maxRemoval(nums []int, queries [][]int) int {
sort.Slice(queries, func(i, j int) bool {
return queries[i][0] < queries[j][0]
})
var h hp
heap.Init(&h)
n := len(nums)
d := make([]int, n+1)
s, j := 0, 0
for i := 0; i < n; i++ {
s += d[i]
for j < len(queries) && queries[j][0] <= i {
heap.Push(&h, queries[j][1])
j++
}
for s < nums[i] && h.Len() > 0 && h.IntSlice[0] >= i {
s++
end := heap.Pop(&h).(int)
if end+1 < len(d) {
d[end+1]--
}
}
if s < nums[i] {
return -1
}
}
return h.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
}
|
class Solution {
public int maxRemoval(int[] nums, int[][] queries) {
Arrays.sort(queries, (a, b) -> Integer.compare(a[0], b[0]));
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
int n = nums.length;
int[] d = new int[n + 1];
int s = 0, j = 0;
for (int i = 0; i < n; i++) {
s += d[i];
while (j < queries.length && queries[j][0] <= i) {
pq.offer(queries[j][1]);
j++;
}
while (s < nums[i] && !pq.isEmpty() && pq.peek() >= i) {
s++;
d[pq.poll() + 1]--;
}
if (s < nums[i]) {
return -1;
}
}
return pq.size();
}
}
| null | null | null | null | null | null |
class Solution:
def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int:
queries.sort()
pq = []
d = [0] * (len(nums) + 1)
s = j = 0
for i, x in enumerate(nums):
s += d[i]
while j < len(queries) and queries[j][0] <= i:
heappush(pq, -queries[j][1])
j += 1
while s < x and pq and -pq[0] >= i:
s += 1
d[-heappop(pq) + 1] -= 1
if s < x:
return -1
return len(pq)
| null | null | null | null | null |
function maxRemoval(nums: number[], queries: number[][]): number {
queries.sort((a, b) => a[0] - b[0]);
const pq = new MaxPriorityQueue<number>();
const n = nums.length;
const d: number[] = Array(n + 1).fill(0);
let [s, j] = [0, 0];
for (let i = 0; i < n; i++) {
s += d[i];
while (j < queries.length && queries[j][0] <= i) {
pq.enqueue(queries[j][1]);
j++;
}
while (s < nums[i] && !pq.isEmpty() && pq.front() >= i) {
s++;
d[pq.dequeue() + 1]--;
}
if (s < nums[i]) {
return -1;
}
}
return pq.size();
}
|
Find Pivot Index
|
Given an array of integers
nums
, calculate the
pivot index
of this array.
The
pivot index
is the index where the sum of all the numbers
strictly
to the left of the index is equal to the sum of all the numbers
strictly
to the index's right.
If the index is on the left edge of the array, then the left sum is
0
because there are no elements to the left. This also applies to the right edge of the array.
Return
the
leftmost pivot index
. If no such index exists, return
-1
.
Example 1:
Input:
nums = [1,7,3,6,5,6]
Output:
3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input:
nums = [1,2,3]
Output:
-1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
Input:
nums = [2,1,-1]
Output:
0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
Constraints:
1 <= nums.length <= 10
4
-1000 <= nums[i] <= 1000
Note:
This question is the same as 1991:
https://leetcode.com/problems/find-the-middle-index-in-array/
| null | null |
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int left = 0, right = accumulate(nums.begin(), nums.end(), 0);
for (int i = 0; i < nums.size(); ++i) {
right -= nums[i];
if (left == right) {
return i;
}
left += nums[i];
}
return -1;
}
};
| null | null |
func pivotIndex(nums []int) int {
var left, right int
for _, x := range nums {
right += x
}
for i, x := range nums {
right -= x
if left == right {
return i
}
left += x
}
return -1
}
|
class Solution {
public int pivotIndex(int[] nums) {
int left = 0, right = Arrays.stream(nums).sum();
for (int i = 0; i < nums.length; ++i) {
right -= nums[i];
if (left == right) {
return i;
}
left += nums[i];
}
return -1;
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var pivotIndex = function (nums) {
let left = 0,
right = nums.reduce((a, b) => a + b);
for (let i = 0; i < nums.length; ++i) {
right -= nums[i];
if (left == right) {
return i;
}
left += nums[i];
}
return -1;
};
| null | null | null | null | null |
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left, right = 0, sum(nums)
for i, x in enumerate(nums):
right -= x
if left == right:
return i
left += x
return -1
| null |
impl Solution {
pub fn pivot_index(nums: Vec<i32>) -> i32 {
let (mut left, mut right): (i32, i32) = (0, nums.iter().sum());
for i in 0..nums.len() {
right -= nums[i];
if left == right {
return i as i32;
}
left += nums[i];
}
-1
}
}
| null | null | null |
function pivotIndex(nums: number[]): number {
let left = 0,
right = nums.reduce((a, b) => a + b);
for (let i = 0; i < nums.length; ++i) {
right -= nums[i];
if (left == right) {
return i;
}
left += nums[i];
}
return -1;
}
|
Smallest String With Swaps
|
You are given a string
s
, and an array of pairs of indices in the string
pairs
where
pairs[i] = [a, b]
indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given
pairs
any number of times
.
Return the lexicographically smallest string that
s
can be changed to after using the swaps.
Example 1:
Input:
s = "dcab", pairs = [[0,3],[1,2]]
Output:
"bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input:
s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output:
"abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input:
s = "cba", pairs = [[0,1],[1,2]]
Output:
"abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s
only contains lower case English letters.
| null | null |
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
int n = s.size();
int p[n];
iota(p, p + n, 0);
vector<char> d[n];
function<int(int)> find = [&](int x) -> int {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
for (auto e : pairs) {
int a = e[0], b = e[1];
p[find(a)] = find(b);
}
for (int i = 0; i < n; ++i) {
d[find(i)].push_back(s[i]);
}
for (auto& e : d) {
sort(e.rbegin(), e.rend());
}
for (int i = 0; i < n; ++i) {
auto& e = d[find(i)];
s[i] = e.back();
e.pop_back();
}
return s;
}
};
| null | null |
func smallestStringWithSwaps(s string, pairs [][]int) string {
n := len(s)
p := make([]int, n)
d := make([][]byte, n)
for i := range p {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
for _, pair := range pairs {
a, b := pair[0], pair[1]
p[find(a)] = find(b)
}
cs := []byte(s)
for i, c := range cs {
j := find(i)
d[j] = append(d[j], c)
}
for i := range d {
sort.Slice(d[i], func(a, b int) bool { return d[i][a] > d[i][b] })
}
for i := range cs {
j := find(i)
cs[i] = d[j][len(d[j])-1]
d[j] = d[j][:len(d[j])-1]
}
return string(cs)
}
|
class Solution {
private int[] p;
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
int n = s.length();
p = new int[n];
List<Character>[] d = new List[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
d[i] = new ArrayList<>();
}
for (var pair : pairs) {
int a = pair.get(0), b = pair.get(1);
p[find(a)] = find(b);
}
char[] cs = s.toCharArray();
for (int i = 0; i < n; ++i) {
d[find(i)].add(cs[i]);
}
for (var e : d) {
e.sort((a, b) -> b - a);
}
for (int i = 0; i < n; ++i) {
var e = d[find(i)];
cs[i] = e.remove(e.size() - 1);
}
return String.valueOf(cs);
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
| null | null | null | null | null | null |
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
n = len(s)
p = list(range(n))
for a, b in pairs:
p[find(a)] = find(b)
d = defaultdict(list)
for i, c in enumerate(s):
d[find(i)].append(c)
for i in d.keys():
d[i].sort(reverse=True)
return "".join(d[find(i)].pop() for i in range(n))
| null |
impl Solution {
#[allow(dead_code)]
pub fn smallest_string_with_swaps(s: String, pairs: Vec<Vec<i32>>) -> String {
let n = s.as_bytes().len();
let s = s.as_bytes();
let mut disjoint_set: Vec<usize> = vec![0; n];
let mut str_vec: Vec<Vec<u8>> = vec![Vec::new(); n];
let mut ret_str = String::new();
// Initialize the disjoint set
for i in 0..n {
disjoint_set[i] = i;
}
// Union the pairs
for pair in pairs {
Self::union(pair[0] as usize, pair[1] as usize, &mut disjoint_set);
}
// Initialize the return vector
for (i, c) in s.iter().enumerate() {
let p_c = Self::find(i, &mut disjoint_set);
str_vec[p_c].push(*c);
}
// Sort the return vector in reverse order
for cur_vec in &mut str_vec {
cur_vec.sort();
cur_vec.reverse();
}
// Construct the return string
for i in 0..n {
let index = Self::find(i, &mut disjoint_set);
ret_str.push(str_vec[index].last().unwrap().clone() as char);
str_vec[index].pop();
}
ret_str
}
#[allow(dead_code)]
fn find(x: usize, d_set: &mut Vec<usize>) -> usize {
if d_set[x] != x {
d_set[x] = Self::find(d_set[x], d_set);
}
d_set[x]
}
#[allow(dead_code)]
fn union(x: usize, y: usize, d_set: &mut Vec<usize>) {
let p_x = Self::find(x, d_set);
let p_y = Self::find(y, d_set);
d_set[p_x] = p_y;
}
}
| null | null | null |
function smallestStringWithSwaps(s: string, pairs: number[][]): string {
const n = s.length;
const p = new Array(n).fill(0).map((_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
const d: string[][] = new Array(n).fill(0).map(() => []);
for (const [a, b] of pairs) {
p[find(a)] = find(b);
}
for (let i = 0; i < n; ++i) {
d[find(i)].push(s[i]);
}
for (const e of d) {
e.sort((a, b) => b.charCodeAt(0) - a.charCodeAt(0));
}
const ans: string[] = [];
for (let i = 0; i < n; ++i) {
ans.push(d[find(i)].pop()!);
}
return ans.join('');
}
|
Minimize XOR
|
Given two positive integers
num1
and
num2
, find the positive integer
x
such that:
x
has the same number of set bits as
num2
, and
The value
x XOR num1
is
minimal
.
Note that
XOR
is the bitwise XOR operation.
Return
the integer
x
. The test cases are generated such that
x
is
uniquely determined
.
The number of
set bits
of an integer is the number of
1
's in its binary representation.
Example 1:
Input:
num1 = 3, num2 = 5
Output:
3
Explanation:
The binary representations of num1 and num2 are 0011 and 0101, respectively.
The integer
3
has the same number of set bits as num2, and the value
3 XOR 3 = 0
is minimal.
Example 2:
Input:
num1 = 1, num2 = 12
Output:
3
Explanation:
The binary representations of num1 and num2 are 0001 and 1100, respectively.
The integer
3
has the same number of set bits as num2, and the value
3 XOR 1 = 2
is minimal.
Constraints:
1 <= num1, num2 <= 10
9
| null | null |
class Solution {
public:
int minimizeXor(int num1, int num2) {
int cnt1 = __builtin_popcount(num1);
int cnt2 = __builtin_popcount(num2);
for (; cnt1 > cnt2; --cnt1) {
num1 &= (num1 - 1);
}
for (; cnt1 < cnt2; ++cnt1) {
num1 |= (num1 + 1);
}
return num1;
}
};
| null | null |
func minimizeXor(num1 int, num2 int) int {
cnt1 := bits.OnesCount(uint(num1))
cnt2 := bits.OnesCount(uint(num2))
for ; cnt1 > cnt2; cnt1-- {
num1 &= (num1 - 1)
}
for ; cnt1 < cnt2; cnt1++ {
num1 |= (num1 + 1)
}
return num1
}
|
class Solution {
public int minimizeXor(int num1, int num2) {
int cnt1 = Integer.bitCount(num1);
int cnt2 = Integer.bitCount(num2);
for (; cnt1 > cnt2; --cnt1) {
num1 &= (num1 - 1);
}
for (; cnt1 < cnt2; ++cnt1) {
num1 |= (num1 + 1);
}
return num1;
}
}
| null | null | null | null | null | null |
class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
cnt1 = num1.bit_count()
cnt2 = num2.bit_count()
while cnt1 > cnt2:
num1 &= num1 - 1
cnt1 -= 1
while cnt1 < cnt2:
num1 |= num1 + 1
cnt1 += 1
return num1
| null | null | null | null | null |
function minimizeXor(num1: number, num2: number): number {
let cnt1 = bitCount(num1);
let cnt2 = bitCount(num2);
for (; cnt1 > cnt2; --cnt1) {
num1 &= num1 - 1;
}
for (; cnt1 < cnt2; ++cnt1) {
num1 |= num1 + 1;
}
return num1;
}
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;
}
|
Longest Consecutive Sequence
|
Given an unsorted array of integers
nums
, return
the length of the longest consecutive elements sequence.
You must write an algorithm that runs in
O(n)
time.
Example 1:
Input:
nums = [100,4,200,1,3,2]
Output:
4
Explanation:
The longest consecutive elements sequence is
[1, 2, 3, 4]
. Therefore its length is 4.
Example 2:
Input:
nums = [0,3,7,2,5,8,4,6,0,1]
Output:
9
Example 3:
Input:
nums = [1,0,1,2]
Output:
3
Constraints:
0 <= nums.length <= 10
5
-10
9
<= nums[i] <= 10
9
| null | null |
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int ans = 0;
for (int x : s) {
if (!s.contains(x - 1)) {
int y = x + 1;
while (s.contains(y)) {
y++;
}
ans = max(ans, y - x);
}
}
return ans;
}
};
| null | null |
func longestConsecutive(nums []int) (ans int) {
s := map[int]bool{}
for _, x := range nums {
s[x] = true
}
for x, _ := range s {
if !s[x-1] {
y := x + 1
for s[y] {
y++
}
ans = max(ans, y-x)
}
}
return
}
|
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
int ans = 0;
for (int x : s) {
if (!s.contains(x - 1)) {
int y = x + 1;
while (s.contains(y)) {
++y;
}
ans = Math.max(ans, y - x);
}
}
return ans;
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
const s = new Set(nums);
let ans = 0;
for (const x of nums) {
if (!s.has(x - 1)) {
let y = x + 1;
while (s.has(y)) {
y++;
}
ans = Math.max(ans, y - x);
}
}
return ans;
};
| null | null | null | null | null |
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
ans = 0
for x in s:
if x - 1 not in s:
y = x + 1
while y in s:
y += 1
ans = max(ans, y - x)
return ans
| null |
use std::collections::HashSet;
impl Solution {
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let s: HashSet<i32> = nums.iter().cloned().collect();
let mut ans = 0;
for &x in &s {
if !s.contains(&(x - 1)) {
let mut y = x + 1;
while s.contains(&y) {
y += 1;
}
ans = ans.max(y - x);
}
}
ans
}
}
| null | null | null |
function longestConsecutive(nums: number[]): number {
const s = new Set<number>(nums);
let ans = 0;
for (const x of s) {
if (!s.has(x - 1)) {
let y = x + 1;
while (s.has(y)) {
y++;
}
ans = Math.max(ans, y - x);
}
}
return ans;
}
|
Mini Parser
|
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return
the deserialized
NestedInteger
.
Each element is either an integer or a list whose elements may also be integers or other lists.
Example 1:
Input:
s = "324"
Output:
324
Explanation:
You should return a NestedInteger object which contains a single integer 324.
Example 2:
Input:
s = "[123,[456,[789]]]"
Output:
[123,[456,[789]]]
Explanation:
Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
i. An integer containing value 456.
ii. A nested list with one element:
a. An integer containing value 789
Constraints:
1 <= s.length <= 5 * 10
4
s
consists of digits, square brackets
"[]"
, negative sign
'-'
, and commas
','
.
s
is the serialization of valid
NestedInteger
.
All the values in the input are in the range
[-10
6
, 10
6
]
.
| null | null |
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
NestedInteger deserialize(string s) {
if (s[0] != '[') {
return NestedInteger(stoi(s));
}
stack<NestedInteger> stk;
int x = 0;
bool neg = false;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '-') {
neg = true;
} else if (isdigit(s[i])) {
x = x * 10 + s[i] - '0';
} else if (s[i] == '[') {
stk.push(NestedInteger());
} else if (s[i] == ',' || s[i] == ']') {
if (isdigit(s[i - 1])) {
if (neg) {
x = -x;
}
stk.top().add(NestedInteger(x));
}
x = 0;
neg = false;
if (s[i] == ']' && stk.size() > 1) {
auto t = stk.top();
stk.pop();
stk.top().add(t);
}
}
}
return stk.top();
}
};
| null | null |
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* type NestedInteger struct {
* }
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* func (n NestedInteger) IsInteger() bool {}
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* // So before calling this method, you should have a check
* func (n NestedInteger) GetInteger() int {}
*
* // Set this NestedInteger to hold a single integer.
* func (n *NestedInteger) SetInteger(value int) {}
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* func (n *NestedInteger) Add(elem NestedInteger) {}
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The list length is zero if this NestedInteger holds a single integer
* // You can access NestedInteger's List element directly if you want to modify it
* func (n NestedInteger) GetList() []*NestedInteger {}
*/
func deserialize(s string) *NestedInteger {
if s[0] != '[' {
v, _ := strconv.Atoi(s)
ans := NestedInteger{}
ans.SetInteger(v)
return &ans
}
stk := []*NestedInteger{}
x := 0
neg := false
for i, c := range s {
if c == '-' {
neg = true
} else if c >= '0' && c <= '9' {
x = x*10 + int(c-'0')
} else if c == '[' {
stk = append(stk, &NestedInteger{})
} else if c == ',' || c == ']' {
if s[i-1] >= '0' && s[i-1] <= '9' {
if neg {
x = -x
}
t := NestedInteger{}
t.SetInteger(x)
stk[len(stk)-1].Add(t)
}
x = 0
neg = false
if c == ']' && len(stk) > 1 {
t := stk[len(stk)-1]
stk = stk[:len(stk)-1]
stk[len(stk)-1].Add(*t)
}
}
}
return stk[0]
}
|
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* // Constructor initializes an empty nested list.
* public NestedInteger();
*
* // Constructor initializes a single integer.
* public NestedInteger(int value);
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // Set this NestedInteger to hold a single integer.
* public void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public void add(NestedInteger ni);
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return empty list if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
public NestedInteger deserialize(String s) {
if (s.charAt(0) != '[') {
return new NestedInteger(Integer.parseInt(s));
}
Deque<NestedInteger> stk = new ArrayDeque<>();
int x = 0;
boolean neg = false;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '-') {
neg = true;
} else if (Character.isDigit(c)) {
x = x * 10 + c - '0';
} else if (c == '[') {
stk.push(new NestedInteger());
} else if (c == ',' || c == ']') {
if (Character.isDigit(s.charAt(i - 1))) {
if (neg) {
x = -x;
}
stk.peek().add(new NestedInteger(x));
}
x = 0;
neg = false;
if (c == ']' && stk.size() > 1) {
NestedInteger t = stk.pop();
stk.peek().add(t);
}
}
}
return stk.peek();
}
}
| null | null | null | null | null | null |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution:
def deserialize(self, s: str) -> NestedInteger:
if s[0] != '[':
return NestedInteger(int(s))
stk, x, neg = [], 0, False
for i, c in enumerate(s):
if c == '-':
neg = True
elif c.isdigit():
x = x * 10 + int(c)
elif c == '[':
stk.append(NestedInteger())
elif c in ',]':
if s[i - 1].isdigit():
if neg:
x = -x
stk[-1].add(NestedInteger(x))
x, neg = 0, False
if c == ']' and len(stk) > 1:
t = stk.pop()
stk[-1].add(t)
return stk.pop()
| null | null | null | null | null |
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* If value is provided, then it holds a single integer
* Otherwise it holds an empty nested list
* constructor(value?: number) {
* ...
* };
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* isInteger(): boolean {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* getInteger(): number | null {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* setInteger(value: number) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
* add(elem: NestedInteger) {
* ...
* };
*
* Return the nested list that this NestedInteger holds,
* or an empty list if this NestedInteger holds a single integer
* getList(): NestedInteger[] {
* ...
* };
* };
*/
function deserialize(s: string): NestedInteger {
if (s[0] !== '[') {
return new NestedInteger(+s);
}
const stk: NestedInteger[] = [];
let x = 0;
let neg = false;
for (let i = 0; i < s.length; ++i) {
if (s[i] === '-') {
neg = true;
} else if (s[i] === '[') {
stk.push(new NestedInteger());
} else if (s[i] >= '0' && s[i] <= '9') {
x = x * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0);
} else if (s[i] === ',' || s[i] === ']') {
if (s[i - 1] >= '0' && s[i - 1] <= '9') {
stk[stk.length - 1].add(new NestedInteger(neg ? -x : x));
}
x = 0;
neg = false;
if (s[i] === ']' && stk.length > 1) {
const t = stk.pop()!;
stk[stk.length - 1].add(t);
}
}
}
return stk[0];
}
|
Closest Dessert Cost
|
You would like to make dessert and are preparing to buy the ingredients. You have
n
ice cream base flavors and
m
types of toppings to choose from. You must follow these rules when making your dessert:
There must be
exactly one
ice cream base.
You can add
one or more
types of topping or have no toppings at all.
There are
at most two
of
each type
of topping.
You are given three inputs:
baseCosts
, an integer array of length
n
, where each
baseCosts[i]
represents the price of the
i
th
ice cream base flavor.
toppingCosts
, an integer array of length
m
, where each
toppingCosts[i]
is the price of
one
of the
i
th
topping.
target
, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to
target
as possible.
Return
the closest possible cost of the dessert to
target
. If there are multiple, return
the
lower
one.
Example 1:
Input:
baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output:
10
Explanation:
Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
Example 2:
Input:
baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
Output:
17
Explanation:
Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
Example 3:
Input:
baseCosts = [3,10], toppingCosts = [2,5], target = 9
Output:
8
Explanation:
It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
Constraints:
n == baseCosts.length
m == toppingCosts.length
1 <= n, m <= 10
1 <= baseCosts[i], toppingCosts[i] <= 10
4
1 <= target <= 10
4
| null | null |
class Solution {
public:
const int inf = INT_MAX;
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
vector<int> arr;
function<void(int, int)> dfs = [&](int i, int t) {
if (i >= toppingCosts.size()) {
arr.push_back(t);
return;
}
dfs(i + 1, t);
dfs(i + 1, t + toppingCosts[i]);
};
dfs(0, 0);
sort(arr.begin(), arr.end());
int d = inf, ans = inf;
// 选择一种冰激淋基料
for (int x : baseCosts) {
// 枚举子集和
for (int y : arr) {
// 二分查找
int i = lower_bound(arr.begin(), arr.end(), target - x - y) - arr.begin();
for (int j = i - 1; j < i + 1; ++j) {
if (j >= 0 && j < arr.size()) {
int t = abs(x + y + arr[j] - target);
if (d > t || (d == t && ans > x + y + arr[j])) {
d = t;
ans = x + y + arr[j];
}
}
}
}
}
return ans;
}
};
| null | null |
func closestCost(baseCosts []int, toppingCosts []int, target int) int {
arr := []int{}
var dfs func(int, int)
dfs = func(i, t int) {
if i >= len(toppingCosts) {
arr = append(arr, t)
return
}
dfs(i+1, t)
dfs(i+1, t+toppingCosts[i])
}
dfs(0, 0)
sort.Ints(arr)
const inf = 1 << 30
ans, d := inf, inf
// 选择一种冰激淋基料
for _, x := range baseCosts {
// 枚举子集和
for _, y := range arr {
// 二分查找
i := sort.SearchInts(arr, target-x-y)
for j := i - 1; j < i+1; j++ {
if j >= 0 && j < len(arr) {
t := abs(x + y + arr[j] - target)
if d > t || (d == t && ans > x+y+arr[j]) {
d = t
ans = x + y + arr[j]
}
}
}
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
private List<Integer> arr = new ArrayList<>();
private int[] ts;
private int inf = 1 << 30;
public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
ts = toppingCosts;
dfs(0, 0);
Collections.sort(arr);
int d = inf, ans = inf;
// 选择一种冰激淋基料
for (int x : baseCosts) {
// 枚举子集和
for (int y : arr) {
// 二分查找
int i = search(target - x - y);
for (int j : new int[] {i, i - 1}) {
if (j >= 0 && j < arr.size()) {
int t = Math.abs(x + y + arr.get(j) - target);
if (d > t || (d == t && ans > x + y + arr.get(j))) {
d = t;
ans = x + y + arr.get(j);
}
}
}
}
}
return ans;
}
private int search(int x) {
int left = 0, right = arr.size();
while (left < right) {
int mid = (left + right) >> 1;
if (arr.get(mid) >= x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private void dfs(int i, int t) {
if (i >= ts.length) {
arr.add(t);
return;
}
dfs(i + 1, t);
dfs(i + 1, t + ts[i]);
}
}
|
const closestCost = function (baseCosts, toppingCosts, target) {
let closestDessertCost = -Infinity;
function dfs(dessertCost, j) {
const tarCurrDiff = Math.abs(target - dessertCost);
const tarCloseDiff = Math.abs(target - closestDessertCost);
if (tarCurrDiff < tarCloseDiff) {
closestDessertCost = dessertCost;
} else if (tarCurrDiff === tarCloseDiff && dessertCost < closestDessertCost) {
closestDessertCost = dessertCost;
}
if (dessertCost > target) return;
if (j === toppingCosts.length) return;
for (let count = 0; count <= 2; count++) {
dfs(dessertCost + count * toppingCosts[j], j + 1);
}
}
for (let i = 0; i < baseCosts.length; i++) {
dfs(baseCosts[i], 0);
}
return closestDessertCost;
};
| null | null | null | null | null |
class Solution:
def closestCost(
self, baseCosts: List[int], toppingCosts: List[int], target: int
) -> int:
def dfs(i, t):
if i >= len(toppingCosts):
arr.append(t)
return
dfs(i + 1, t)
dfs(i + 1, t + toppingCosts[i])
arr = []
dfs(0, 0)
arr.sort()
d = ans = inf
# 选择一种冰激淋基料
for x in baseCosts:
# 枚举子集和
for y in arr:
# 二分查找
i = bisect_left(arr, target - x - y)
for j in (i, i - 1):
if 0 <= j < len(arr):
t = abs(x + y + arr[j] - target)
if d > t or (d == t and ans > x + y + arr[j]):
d = t
ans = x + y + arr[j]
return ans
| null | null | null | null | null | null |
Minimum Window Substring
|
Given two strings
s
and
t
of lengths
m
and
n
respectively, return
the
minimum window
substring
of
s
such that every character in
t
(
including duplicates
) is included in the window
. If there is no such substring, return
the empty string
""
.
The testcases will be generated such that the answer is
unique
.
Example 1:
Input:
s = "ADOBECODEBANC", t = "ABC"
Output:
"BANC"
Explanation:
The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input:
s = "a", t = "a"
Output:
"a"
Explanation:
The entire string s is the minimum window.
Example 3:
Input:
s = "a", t = "aa"
Output:
""
Explanation:
Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.length
n == t.length
1 <= m, n <= 10
5
s
and
t
consist of uppercase and lowercase English letters.
Follow up:
Could you find an algorithm that runs in
O(m + n)
time?
| null |
public class Solution {
public string MinWindow(string s, string t) {
int[] need = new int[128];
int[] window = new int[128];
foreach (var c in t) {
need[c]++;
}
int m = s.Length, n = t.Length;
int k = -1, mi = m + 1, cnt = 0;
int l = 0;
for (int r = 0; r < m; r++) {
char c = s[r];
window[c]++;
if (window[c] <= need[c]) {
cnt++;
}
while (cnt == n) {
if (r - l + 1 < mi) {
mi = r - l + 1;
k = l;
}
c = s[l];
if (window[c] <= need[c]) {
cnt--;
}
window[c]--;
l++;
}
}
return k < 0 ? "" : s.Substring(k, mi);
}
}
|
class Solution {
public:
string minWindow(string s, string t) {
vector<int> need(128, 0);
vector<int> window(128, 0);
for (char c : t) {
++need[c];
}
int m = s.length(), n = t.length();
int k = -1, mi = m + 1, cnt = 0;
for (int l = 0, r = 0; r < m; ++r) {
char c = s[r];
if (++window[c] <= need[c]) {
++cnt;
}
while (cnt == n) {
if (r - l + 1 < mi) {
mi = r - l + 1;
k = l;
}
c = s[l];
if (window[c] <= need[c]) {
--cnt;
}
--window[c];
++l;
}
}
return k < 0 ? "" : s.substr(k, mi);
}
};
| null | null |
func minWindow(s string, t string) string {
need := make([]int, 128)
window := make([]int, 128)
for i := 0; i < len(t); i++ {
need[t[i]]++
}
m, n := len(s), len(t)
k, mi, cnt := -1, m+1, 0
for l, r := 0, 0; r < m; r++ {
c := s[r]
if window[c]++; window[c] <= need[c] {
cnt++
}
for cnt == n {
if r-l+1 < mi {
mi = r - l + 1
k = l
}
c = s[l]
if window[c] <= need[c] {
cnt--
}
window[c]--
l++
}
}
if k < 0 {
return ""
}
return s[k : k+mi]
}
|
class Solution {
public String minWindow(String s, String t) {
int[] need = new int[128];
int[] window = new int[128];
for (char c : t.toCharArray()) {
++need[c];
}
int m = s.length(), n = t.length();
int k = -1, mi = m + 1, cnt = 0;
for (int l = 0, r = 0; r < m; ++r) {
char c = s.charAt(r);
if (++window[c] <= need[c]) {
++cnt;
}
while (cnt == n) {
if (r - l + 1 < mi) {
mi = r - l + 1;
k = l;
}
c = s.charAt(l);
if (window[c] <= need[c]) {
--cnt;
}
--window[c];
++l;
}
}
return k < 0 ? "" : s.substring(k, k + mi);
}
}
| null | null | null | null | null | null |
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = Counter(t)
window = Counter()
cnt = l = 0
k, mi = -1, inf
for r, c in enumerate(s):
window[c] += 1
if need[c] >= window[c]:
cnt += 1
while cnt == len(t):
if r - l + 1 < mi:
mi = r - l + 1
k = l
if need[s[l]] >= window[s[l]]:
cnt -= 1
window[s[l]] -= 1
l += 1
return "" if k < 0 else s[k : k + mi]
| null |
use std::collections::HashMap;
impl Solution {
pub fn min_window(s: String, t: String) -> String {
let mut need: HashMap<char, usize> = HashMap::new();
let mut window: HashMap<char, usize> = HashMap::new();
for c in t.chars() {
*need.entry(c).or_insert(0) += 1;
}
let m = s.len();
let n = t.len();
let mut k = -1;
let mut mi = m + 1;
let mut cnt = 0;
let s_bytes = s.as_bytes();
let mut l = 0;
for r in 0..m {
let c = s_bytes[r] as char;
*window.entry(c).or_insert(0) += 1;
if window[&c] <= *need.get(&c).unwrap_or(&0) {
cnt += 1;
}
while cnt == n {
if r - l + 1 < mi {
mi = r - l + 1;
k = l as i32;
}
let c = s_bytes[l] as char;
if window[&c] <= *need.get(&c).unwrap_or(&0) {
cnt -= 1;
}
*window.entry(c).or_insert(0) -= 1;
l += 1;
}
}
if k < 0 {
return String::new();
}
s[k as usize..(k as usize + mi)].to_string()
}
}
| null | null | null |
function minWindow(s: string, t: string): string {
const need: number[] = Array(128).fill(0);
const window: number[] = Array(128).fill(0);
for (let i = 0; i < t.length; i++) {
need[t.charCodeAt(i)]++;
}
const [m, n] = [s.length, t.length];
let [k, mi, cnt] = [-1, m + 1, 0];
for (let l = 0, r = 0; r < m; r++) {
let c = s.charCodeAt(r);
if (++window[c] <= need[c]) {
cnt++;
}
while (cnt === n) {
if (r - l + 1 < mi) {
mi = r - l + 1;
k = l;
}
c = s.charCodeAt(l);
if (window[c] <= need[c]) {
cnt--;
}
window[c]--;
l++;
}
}
return k < 0 ? '' : s.substring(k, k + mi);
}
|
Maximize Score After Pair Deletions 🔒
|
You are given an array of integers
nums
. You
must
repeatedly perform one of the following operations while the array has more than two elements:
Remove the first two elements.
Remove the last two elements.
Remove the first and last element.
For each operation, add the sum of the removed elements to your total score.
Return the
maximum
possible score you can achieve.
Example 1:
Input:
nums = [2,4,1]
Output:
6
Explanation:
The possible operations are:
Remove the first two elements
(2 + 4) = 6
. The remaining array is
[1]
.
Remove the last two elements
(4 + 1) = 5
. The remaining array is
[2]
.
Remove the first and last elements
(2 + 1) = 3
. The remaining array is
[4]
.
The maximum score is obtained by removing the first two elements, resulting in a final score of 6.
Example 2:
Input:
nums = [5,-1,4,2]
Output:
7
Explanation:
The possible operations are:
Remove the first and last elements
(5 + 2) = 7
. The remaining array is
[-1, 4]
.
Remove the first two elements
(5 + -1) = 4
. The remaining array is
[4, 2]
.
Remove the last two elements
(4 + 2) = 6
. The remaining array is
[5, -1]
.
The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.
Constraints:
1 <= nums.length <= 10
5
-10
4
<= nums[i] <= 10
4
| null | null |
class Solution {
public:
int maxScore(vector<int>& nums) {
const int inf = 1 << 30;
int n = nums.size();
int s = 0, mi = inf;
int t = inf;
for (int i = 0; i < n; ++i) {
s += nums[i];
mi = min(mi, nums[i]);
if (i + 1 < n) {
t = min(t, nums[i] + nums[i + 1]);
}
}
if (n % 2 == 1) {
return s - mi;
}
return s - t;
}
};
| null | null |
func maxScore(nums []int) int {
const inf = 1 << 30
n := len(nums)
s, mi, t := 0, inf, inf
for i, x := range nums {
s += x
mi = min(mi, x)
if i+1 < n {
t = min(t, x+nums[i+1])
}
}
if n%2 == 1 {
return s - mi
}
return s - t
}
|
class Solution {
public int maxScore(int[] nums) {
final int inf = 1 << 30;
int n = nums.length;
int s = 0, mi = inf;
int t = inf;
for (int i = 0; i < n; ++i) {
s += nums[i];
mi = Math.min(mi, nums[i]);
if (i + 1 < n) {
t = Math.min(t, nums[i] + nums[i + 1]);
}
}
if (n % 2 == 1) {
return s - mi;
}
return s - t;
}
}
| null | null | null | null | null | null |
class Solution:
def maxScore(self, nums: List[int]) -> int:
s = sum(nums)
if len(nums) & 1:
return s - min(nums)
return s - min(a + b for a, b in pairwise(nums))
| null | null | null | null | null |
function maxScore(nums: number[]): number {
const inf = Infinity;
const n = nums.length;
let [s, mi, t] = [0, inf, inf];
for (let i = 0; i < n; ++i) {
s += nums[i];
mi = Math.min(mi, nums[i]);
if (i + 1 < n) {
t = Math.min(t, nums[i] + nums[i + 1]);
}
}
return n % 2 ? s - mi : s - t;
}
|
Course Schedule
|
There are a total of
numCourses
courses you have to take, labeled from
0
to
numCourses - 1
. You are given an array
prerequisites
where
prerequisites[i] = [a
i
, b
i
]
indicates that you
must
take course
b
i
first if you want to take course
a
i
.
For example, the pair
[0, 1]
, indicates that to take course
0
you have to first take course
1
.
Return
true
if you can finish all courses. Otherwise, return
false
.
Example 1:
Input:
numCourses = 2, prerequisites = [[1,0]]
Output:
true
Explanation:
There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input:
numCourses = 2, prerequisites = [[1,0],[0,1]]
Output:
false
Explanation:
There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= a
i
, b
i
< numCourses
All the pairs prerequisites[i] are
unique
.
| null |
public class Solution {
public bool CanFinish(int numCourses, int[][] prerequisites) {
var g = new List<int>[numCourses];
for (int i = 0; i < numCourses; ++i) {
g[i] = new List<int>();
}
var indeg = new int[numCourses];
foreach (var p in prerequisites) {
int a = p[0], b = p[1];
g[b].Add(a);
++indeg[a];
}
var q = new Queue<int>();
for (int i = 0; i < numCourses; ++i) {
if (indeg[i] == 0) {
q.Enqueue(i);
}
}
while (q.Count > 0) {
int i = q.Dequeue();
--numCourses;
foreach (int j in g[i]) {
if (--indeg[j] == 0) {
q.Enqueue(j);
}
}
}
return numCourses == 0;
}
}
|
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> g(numCourses);
vector<int> indeg(numCourses);
for (auto& p : prerequisites) {
int a = p[0], b = p[1];
g[b].push_back(a);
++indeg[a];
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (indeg[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int i = q.front();
q.pop();
--numCourses;
for (int j : g[i]) {
if (--indeg[j] == 0) {
q.push(j);
}
}
}
return numCourses == 0;
}
};
| null | null |
func canFinish(numCourses int, prerequisites [][]int) bool {
g := make([][]int, numCourses)
indeg := make([]int, numCourses)
for _, p := range prerequisites {
a, b := p[0], p[1]
g[b] = append(g[b], a)
indeg[a]++
}
q := []int{}
for i, x := range indeg {
if x == 0 {
q = append(q, i)
}
}
for len(q) > 0 {
i := q[0]
q = q[1:]
numCourses--
for _, j := range g[i] {
indeg[j]--
if indeg[j] == 0 {
q = append(q, j)
}
}
}
return numCourses == 0
}
|
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] g = new List[numCourses];
Arrays.setAll(g, k -> new ArrayList<>());
int[] indeg = new int[numCourses];
for (var p : prerequisites) {
int a = p[0], b = p[1];
g[b].add(a);
++indeg[a];
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < numCourses; ++i) {
if (indeg[i] == 0) {
q.offer(i);
}
}
while (!q.isEmpty()) {
int i = q.poll();
--numCourses;
for (int j : g[i]) {
if (--indeg[j] == 0) {
q.offer(j);
}
}
}
return numCourses == 0;
}
}
| null | null | null | null | null | null |
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
g = [[] for _ in range(numCourses)]
indeg = [0] * numCourses
for a, b in prerequisites:
g[b].append(a)
indeg[a] += 1
q = [i for i, x in enumerate(indeg) if x == 0]
for i in q:
numCourses -= 1
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return numCourses == 0
| null |
use std::collections::VecDeque;
impl Solution {
pub fn can_finish(mut num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
let mut g: Vec<Vec<i32>> = vec![vec![]; num_courses as usize];
let mut indeg: Vec<i32> = vec![0; num_courses as usize];
for p in prerequisites {
let a = p[0] as usize;
let b = p[1] as usize;
g[b].push(a as i32);
indeg[a] += 1;
}
let mut q: VecDeque<usize> = VecDeque::new();
for i in 0..num_courses {
if indeg[i as usize] == 0 {
q.push_back(i as usize);
}
}
while let Some(i) = q.pop_front() {
num_courses -= 1;
for &j in &g[i] {
let j = j as usize;
indeg[j] -= 1;
if indeg[j] == 0 {
q.push_back(j);
}
}
}
num_courses == 0
}
}
| null | null | null |
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
const g: number[][] = Array.from({ length: numCourses }, () => []);
const indeg: number[] = Array(numCourses).fill(0);
for (const [a, b] of prerequisites) {
g[b].push(a);
indeg[a]++;
}
const q: number[] = [];
for (let i = 0; i < numCourses; ++i) {
if (indeg[i] === 0) {
q.push(i);
}
}
for (const i of q) {
--numCourses;
for (const j of g[i]) {
if (--indeg[j] === 0) {
q.push(j);
}
}
}
return numCourses === 0;
}
|
Check if Move is Legal
|
You are given a
0-indexed
8 x 8
grid
board
, where
board[r][c]
represents the cell
(r, c)
on a game board. On the board, free cells are represented by
'.'
, white cells are represented by
'W'
, and black cells are represented by
'B'
.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only
legal
if, after changing it, the cell becomes the
endpoint of a good line
(horizontal, vertical, or diagonal).
A
good line
is a line of
three or more cells (including the endpoints)
where the endpoints of the line are
one color
, and the remaining cells in the middle are the
opposite color
(no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers
rMove
and
cMove
and a character
color
representing the color you are playing as (white or black), return
true
if changing cell
(rMove, cMove)
to color
color
is a
legal
move, or
false
if it is not legal
.
Example 1:
Input:
board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"
Output:
true
Explanation:
'.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
Example 2:
Input:
board = [[".",".",".",".",".",".",".","."],[".","B",".",".","W",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W","B",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".","B","W",".","."],[".",".",".",".",".",".","W","."],[".",".",".",".",".",".",".","B"]], rMove = 4, cMove = 4, color = "W"
Output:
false
Explanation:
While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
Constraints:
board.length == board[r].length == 8
0 <= rMove, cMove < 8
board[rMove][cMove] == '.'
color
is either
'B'
or
'W'
.
| null | null |
class Solution {
public:
bool checkMove(vector<vector<char>>& board, int rMove, int cMove, char color) {
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a == 0 && b == 0) {
continue;
}
int i = rMove, j = cMove;
int cnt = 0;
while (0 <= i + a && i + a < 8 && 0 <= j + b && j + b < 8) {
i += a;
j += b;
if (++cnt > 1 && board[i][j] == color) {
return true;
}
if (board[i][j] == color || board[i][j] == '.') {
break;
}
}
}
}
return false;
}
};
| null | null |
func checkMove(board [][]byte, rMove int, cMove int, color byte) bool {
for a := -1; a <= 1; a++ {
for b := -1; b <= 1; b++ {
if a == 0 && b == 0 {
continue
}
i, j := rMove, cMove
cnt := 0
for 0 <= i+a && i+a < 8 && 0 <= j+b && j+b < 8 {
i += a
j += b
cnt++
if cnt > 1 && board[i][j] == color {
return true
}
if board[i][j] == color || board[i][j] == '.' {
break
}
}
}
}
return false
}
|
class Solution {
public boolean checkMove(char[][] board, int rMove, int cMove, char color) {
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a == 0 && b == 0) {
continue;
}
int i = rMove, j = cMove;
int cnt = 0;
while (0 <= i + a && i + a < 8 && 0 <= j + b && j + b < 8) {
i += a;
j += b;
if (++cnt > 1 && board[i][j] == color) {
return true;
}
if (board[i][j] == color || board[i][j] == '.') {
break;
}
}
}
}
return false;
}
}
| null | null | null | null | null | null |
class Solution:
def checkMove(
self, board: List[List[str]], rMove: int, cMove: int, color: str
) -> bool:
for a in range(-1, 2):
for b in range(-1, 2):
if a == 0 and b == 0:
continue
i, j = rMove, cMove
cnt = 0
while 0 <= i + a < 8 and 0 <= j + b < 8:
cnt += 1
i, j = i + a, j + b
if cnt > 1 and board[i][j] == color:
return True
if board[i][j] in (color, "."):
break
return False
| null | null | null | null | null |
function checkMove(board: string[][], rMove: number, cMove: number, color: string): boolean {
for (let a = -1; a <= 1; ++a) {
for (let b = -1; b <= 1; ++b) {
if (a === 0 && b === 0) {
continue;
}
let [i, j] = [rMove, cMove];
let cnt = 0;
while (0 <= i + a && i + a < 8 && 0 <= j + b && j + b < 8) {
i += a;
j += b;
if (++cnt > 1 && board[i][j] === color) {
return true;
}
if (board[i][j] === color || board[i][j] === '.') {
break;
}
}
}
}
return false;
}
|
Unique Word Abbreviation 🔒
|
The
abbreviation
of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an
abbreviation
of itself.
For example:
dog --> d1g
because there is one letter between the first letter
'd'
and the last letter
'g'
.
internationalization --> i18n
because there are 18 letters between the first letter
'i'
and the last letter
'n'
.
it --> it
because any word with only two characters is an
abbreviation
of itself.
Implement the
ValidWordAbbr
class:
ValidWordAbbr(String[] dictionary)
Initializes the object with a
dictionary
of words.
boolean isUnique(string word)
Returns
true
if
either
of the following conditions are met (otherwise returns
false
):
There is no word in
dictionary
whose
abbreviation
is equal to
word
's
abbreviation
.
For any word in
dictionary
whose
abbreviation
is equal to
word
's
abbreviation
, that word and
word
are
the same
.
Example 1:
Input
["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique", "isUnique"]
[[["deer", "door", "cake", "card"]], ["dear"], ["cart"], ["cane"], ["make"], ["cake"]]
Output
[null, false, true, false, true, true]
Explanation
ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]);
validWordAbbr.isUnique("dear"); // return false, dictionary word "deer" and word "dear" have the same abbreviation "d2r" but are not the same.
validWordAbbr.isUnique("cart"); // return true, no words in the dictionary have the abbreviation "c2t".
validWordAbbr.isUnique("cane"); // return false, dictionary word "cake" and word "cane" have the same abbreviation "c2e" but are not the same.
validWordAbbr.isUnique("make"); // return true, no words in the dictionary have the abbreviation "m2e".
validWordAbbr.isUnique("cake"); // return true, because "cake" is already in the dictionary and no other word in the dictionary has "c2e" abbreviation.
Constraints:
1 <= dictionary.length <= 3 * 10
4
1 <= dictionary[i].length <= 20
dictionary[i]
consists of lowercase English letters.
1 <= word.length <= 20
word
consists of lowercase English letters.
At most
5000
calls will be made to
isUnique
.
| null | null |
class ValidWordAbbr {
public:
ValidWordAbbr(vector<string>& dictionary) {
for (auto& s : dictionary) {
d[abbr(s)].insert(s);
}
}
bool isUnique(string word) {
string s = abbr(word);
return !d.count(s) || (d[s].size() == 1 && d[s].count(word));
}
private:
unordered_map<string, unordered_set<string>> d;
string abbr(string& s) {
int n = s.size();
return n < 3 ? s : s.substr(0, 1) + to_string(n - 2) + s.substr(n - 1, 1);
}
};
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr* obj = new ValidWordAbbr(dictionary);
* bool param_1 = obj->isUnique(word);
*/
| null | null |
type ValidWordAbbr struct {
d map[string]map[string]bool
}
func Constructor(dictionary []string) ValidWordAbbr {
d := make(map[string]map[string]bool)
for _, s := range dictionary {
abbr := abbr(s)
if _, ok := d[abbr]; !ok {
d[abbr] = make(map[string]bool)
}
d[abbr][s] = true
}
return ValidWordAbbr{d}
}
func (this *ValidWordAbbr) IsUnique(word string) bool {
ws := this.d[abbr(word)]
return ws == nil || (len(ws) == 1 && ws[word])
}
func abbr(s string) string {
n := len(s)
if n < 3 {
return s
}
return fmt.Sprintf("%c%d%c", s[0], n-2, s[n-1])
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* obj := Constructor(dictionary);
* param_1 := obj.IsUnique(word);
*/
|
class ValidWordAbbr {
private Map<String, Set<String>> d = new HashMap<>();
public ValidWordAbbr(String[] dictionary) {
for (var s : dictionary) {
d.computeIfAbsent(abbr(s), k -> new HashSet<>()).add(s);
}
}
public boolean isUnique(String word) {
var ws = d.get(abbr(word));
return ws == null || (ws.size() == 1 && ws.contains(word));
}
private String abbr(String s) {
int n = s.length();
return n < 3 ? s : s.substring(0, 1) + (n - 2) + s.substring(n - 1);
}
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* boolean param_1 = obj.isUnique(word);
*/
| null | null | null | null | null | null |
class ValidWordAbbr:
def __init__(self, dictionary: List[str]):
self.d = defaultdict(set)
for s in dictionary:
self.d[self.abbr(s)].add(s)
def isUnique(self, word: str) -> bool:
s = self.abbr(word)
return s not in self.d or all(word == t for t in self.d[s])
def abbr(self, s: str) -> str:
return s if len(s) < 3 else s[0] + str(len(s) - 2) + s[-1]
# Your ValidWordAbbr object will be instantiated and called as such:
# obj = ValidWordAbbr(dictionary)
# param_1 = obj.isUnique(word)
| null | null | null | null | null |
class ValidWordAbbr {
private d: Map<string, Set<string>> = new Map();
constructor(dictionary: string[]) {
for (const s of dictionary) {
const abbr = this.abbr(s);
if (!this.d.has(abbr)) {
this.d.set(abbr, new Set());
}
this.d.get(abbr)!.add(s);
}
}
isUnique(word: string): boolean {
const ws = this.d.get(this.abbr(word));
return ws === undefined || (ws.size === 1 && ws.has(word));
}
abbr(s: string): string {
const n = s.length;
return n < 3 ? s : s[0] + (n - 2) + s[n - 1];
}
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* var obj = new ValidWordAbbr(dictionary)
* var param_1 = obj.isUnique(word)
*/
|
Find Minimum in Rotated Sorted Array
|
Suppose an array of length
n
sorted in ascending order is
rotated
between
1
and
n
times. For example, the array
nums = [0,1,2,4,5,6,7]
might become:
[4,5,6,7,0,1,2]
if it was rotated
4
times.
[0,1,2,4,5,6,7]
if it was rotated
7
times.
Notice that
rotating
an array
[a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array
[a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array
nums
of
unique
elements, return
the minimum element of this array
.
You must write an algorithm that runs in
O(log n) time
.
Example 1:
Input:
nums = [3,4,5,1,2]
Output:
1
Explanation:
The original array was [1,2,3,4,5] rotated 3 times.
Example 2:
Input:
nums = [4,5,6,7,0,1,2]
Output:
0
Explanation:
The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Example 3:
Input:
nums = [11,13,15,17]
Output:
11
Explanation:
The original array was [11,13,15,17] and it was rotated 4 times.
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
All the integers of
nums
are
unique
.
nums
is sorted and rotated between
1
and
n
times.
| null | null |
class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
if (nums[0] <= nums[n - 1]) return nums[0];
int left = 0, right = n - 1;
while (left < right) {
int mid = (left + right) >> 1;
if (nums[0] <= nums[mid])
left = mid + 1;
else
right = mid;
}
return nums[left];
}
};
| null | null |
func findMin(nums []int) int {
n := len(nums)
if nums[0] <= nums[n-1] {
return nums[0]
}
left, right := 0, n-1
for left < right {
mid := (left + right) >> 1
if nums[0] <= nums[mid] {
left = mid + 1
} else {
right = mid
}
}
return nums[left]
}
|
class Solution {
public int findMin(int[] nums) {
int n = nums.length;
if (nums[0] <= nums[n - 1]) {
return nums[0];
}
int left = 0, right = n - 1;
while (left < right) {
int mid = (left + right) >> 1;
if (nums[0] <= nums[mid]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var findMin = function (nums) {
let l = 0,
r = nums.length - 1;
if (nums[l] < nums[r]) return nums[0];
while (l < r) {
const m = (l + r) >> 1;
if (nums[m] > nums[r]) l = m + 1;
else r = m;
}
return nums[l];
};
| null | null | null | null | null |
class Solution:
def findMin(self, nums: List[int]) -> int:
if nums[0] <= nums[-1]:
return nums[0]
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[0] <= nums[mid]:
left = mid + 1
else:
right = mid
return nums[left]
| null |
impl Solution {
pub fn find_min(nums: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = nums.len() - 1;
while left < right {
let mid = left + (right - left) / 2;
if nums[mid] > nums[right] {
left = mid + 1;
} else {
right = mid;
}
}
nums[left]
}
}
| null | null | null |
function findMin(nums: number[]): number {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const mid = (left + right) >>> 1;
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
}
|
Number of Longest Increasing Subsequence
|
Given an integer array
nums
, return
the number of longest increasing subsequences.
Notice
that the sequence has to be
strictly
increasing.
Example 1:
Input:
nums = [1,3,5,4,7]
Output:
2
Explanation:
The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input:
nums = [2,2,2,2,2]
Output:
5
Explanation:
The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
Constraints:
1 <= nums.length <= 2000
-10
6
<= nums[i] <= 10
6
The answer is guaranteed to fit inside a 32-bit integer.
| null | null |
class BinaryIndexedTree {
private:
int n;
vector<int> c;
vector<int> d;
public:
BinaryIndexedTree(int n)
: n(n)
, c(n + 1, 0)
, d(n + 1, 0) {}
void update(int x, int v, int cnt) {
while (x <= n) {
if (c[x] < v) {
c[x] = v;
d[x] = cnt;
} else if (c[x] == v) {
d[x] += cnt;
}
x += x & -x;
}
}
pair<int, int> query(int x) {
int v = 0, cnt = 0;
while (x > 0) {
if (c[x] > v) {
v = c[x];
cnt = d[x];
} else if (c[x] == v) {
cnt += d[x];
}
x -= x & -x;
}
return {v, cnt};
}
};
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
vector<int> arr = nums;
sort(arr.begin(), arr.end());
arr.erase(unique(arr.begin(), arr.end()), arr.end());
int m = arr.size();
BinaryIndexedTree tree(m);
for (int x : nums) {
auto it = lower_bound(arr.begin(), arr.end(), x);
int i = distance(arr.begin(), it) + 1;
auto [v, cnt] = tree.query(i - 1);
tree.update(i, v + 1, max(cnt, 1));
}
return tree.query(m).second;
}
};
| null | null |
type BinaryIndexedTree struct {
n int
c []int
d []int
}
func newBinaryIndexedTree(n int) BinaryIndexedTree {
return BinaryIndexedTree{
n: n,
c: make([]int, n+1),
d: make([]int, n+1),
}
}
func (bit *BinaryIndexedTree) update(x, v, cnt int) {
for x <= bit.n {
if bit.c[x] < v {
bit.c[x] = v
bit.d[x] = cnt
} else if bit.c[x] == v {
bit.d[x] += cnt
}
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) (int, int) {
v, cnt := 0, 0
for x > 0 {
if bit.c[x] > v {
v = bit.c[x]
cnt = bit.d[x]
} else if bit.c[x] == v {
cnt += bit.d[x]
}
x -= x & -x
}
return v, cnt
}
func findNumberOfLIS(nums []int) int {
arr := make([]int, len(nums))
copy(arr, nums)
sort.Ints(arr)
m := len(arr)
tree := newBinaryIndexedTree(m)
for _, x := range nums {
i := sort.SearchInts(arr, x) + 1
v, cnt := tree.query(i - 1)
tree.update(i, v+1, max(cnt, 1))
}
_, ans := tree.query(m)
return ans
}
|
class BinaryIndexedTree {
private int n;
private int[] c;
private int[] d;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
d = new int[n + 1];
}
public void update(int x, int v, int cnt) {
while (x <= n) {
if (c[x] < v) {
c[x] = v;
d[x] = cnt;
} else if (c[x] == v) {
d[x] += cnt;
}
x += x & -x;
}
}
public int[] query(int x) {
int v = 0, cnt = 0;
while (x > 0) {
if (c[x] > v) {
v = c[x];
cnt = d[x];
} else if (c[x] == v) {
cnt += d[x];
}
x -= x & -x;
}
return new int[] {v, cnt};
}
}
public class Solution {
public int findNumberOfLIS(int[] nums) {
// int[] arr = Arrays.stream(nums).distinct().sorted().toArray();
int[] arr = nums.clone();
Arrays.sort(arr);
int m = arr.length;
BinaryIndexedTree tree = new BinaryIndexedTree(m);
for (int x : nums) {
int i = Arrays.binarySearch(arr, x) + 1;
int[] t = tree.query(i - 1);
int v = t[0];
int cnt = t[1];
tree.update(i, v + 1, Math.max(cnt, 1));
}
return tree.query(m)[1];
}
}
| null | null | null | null | null | null |
class BinaryIndexedTree:
__slots__ = ["n", "c", "d"]
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
self.d = [0] * (n + 1)
def update(self, x, v, cnt):
while x <= self.n:
if self.c[x] < v:
self.c[x] = v
self.d[x] = cnt
elif self.c[x] == v:
self.d[x] += cnt
x += x & -x
def query(self, x):
v = cnt = 0
while x:
if self.c[x] > v:
v = self.c[x]
cnt = self.d[x]
elif self.c[x] == v:
cnt += self.d[x]
x -= x & -x
return v, cnt
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
arr = sorted(set(nums))
m = len(arr)
tree = BinaryIndexedTree(m)
for x in nums:
i = bisect_left(arr, x) + 1
v, cnt = tree.query(i - 1)
tree.update(i, v + 1, max(cnt, 1))
return tree.query(m)[1]
| null |
struct BinaryIndexedTree {
n: usize,
c: Vec<i32>,
d: Vec<i32>,
}
impl BinaryIndexedTree {
fn new(n: usize) -> BinaryIndexedTree {
BinaryIndexedTree {
n,
c: vec![0; n + 1],
d: vec![0; n + 1],
}
}
fn update(&mut self, x: usize, v: i32, cnt: i32) {
let mut x = x as usize;
while x <= self.n {
if self.c[x] < v {
self.c[x] = v;
self.d[x] = cnt;
} else if self.c[x] == v {
self.d[x] += cnt;
}
x += x & x.wrapping_neg();
}
}
fn query(&self, mut x: usize) -> (i32, i32) {
let (mut v, mut cnt) = (0, 0);
while x > 0 {
if self.c[x] > v {
v = self.c[x];
cnt = self.d[x];
} else if self.c[x] == v {
cnt += self.d[x];
}
x -= x & x.wrapping_neg();
}
(v, cnt)
}
}
impl Solution {
pub fn find_number_of_lis(nums: Vec<i32>) -> i32 {
let mut arr: Vec<i32> = nums.iter().cloned().collect();
arr.sort();
let m = arr.len();
let mut tree = BinaryIndexedTree::new(m);
for x in nums.iter() {
if let Ok(i) = arr.binary_search(x) {
let (v, cnt) = tree.query(i);
tree.update(i + 1, v + 1, cnt.max(1));
}
}
let (_, ans) = tree.query(m);
ans
}
}
| null | null | null |
class BinaryIndexedTree {
private n: number;
private c: number[];
private d: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
this.d = Array(n + 1).fill(0);
}
update(x: number, v: number, cnt: number): void {
while (x <= this.n) {
if (this.c[x] < v) {
this.c[x] = v;
this.d[x] = cnt;
} else if (this.c[x] === v) {
this.d[x] += cnt;
}
x += x & -x;
}
}
query(x: number): [number, number] {
let v = 0;
let cnt = 0;
while (x > 0) {
if (this.c[x] > v) {
v = this.c[x];
cnt = this.d[x];
} else if (this.c[x] === v) {
cnt += this.d[x];
}
x -= x & -x;
}
return [v, cnt];
}
}
function findNumberOfLIS(nums: number[]): number {
const arr: number[] = [...new Set(nums)].sort((a, b) => a - b);
const m: number = arr.length;
const tree: BinaryIndexedTree = new BinaryIndexedTree(m);
const search = (x: number): number => {
let l = 0,
r = arr.length;
while (l < r) {
const mid = (l + r) >> 1;
if (arr[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l + 1;
};
for (const x of nums) {
const i: number = search(x);
const [v, cnt]: [number, number] = tree.query(i - 1);
tree.update(i, v + 1, Math.max(cnt, 1));
}
return tree.query(m)[1];
}
|
The Maze III 🔒
|
There is a ball in a
maze
with empty spaces (represented as
0
) and walls (represented as
1
). The ball can go through the empty spaces by rolling
up, down, left or right
, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.
Given the
m x n
maze
, the ball's position
ball
and the hole's position
hole
, where
ball = [ball
row
, ball
col
]
and
hole = [hole
row
, hole
col
]
, return
a string
instructions
of all the instructions that the ball should follow to drop in the hole with the
shortest distance
possible
. If there are multiple valid instructions, return the
lexicographically minimum
one. If the ball can't drop in the hole, return
"impossible"
.
If there is a way for the ball to drop in the hole, the answer
instructions
should contain the characters
'u'
(i.e., up),
'd'
(i.e., down),
'l'
(i.e., left), and
'r'
(i.e., right).
The
distance
is the number of
empty spaces
traveled by the ball from the start position (excluded) to the destination (included).
You may assume that
the borders of the maze are all walls
(see examples).
Example 1:
Input:
maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1]
Output:
"lul"
Explanation:
There are two shortest ways for the ball to drop into the hole.
The first way is left -> up -> left, represented by "lul".
The second way is up -> left, represented by 'ul'.
Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul".
Example 2:
Input:
maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0]
Output:
"impossible"
Explanation:
The ball cannot reach the hole.
Example 3:
Input:
maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5]
Output:
"dldr"
Constraints:
m == maze.length
n == maze[i].length
1 <= m, n <= 100
maze[i][j]
is
0
or
1
.
ball.length == 2
hole.length == 2
0 <= ball
row
, hole
row
<= m
0 <= ball
col
, hole
col
<= n
Both the ball and the hole exist in an empty space, and they will not be in the same position initially.
The maze contains
at least 2 empty spaces
.
| null | null |
class Solution {
public:
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
int m = maze.size();
int n = maze[0].size();
int r = ball[0], c = ball[1];
int rh = hole[0], ch = hole[1];
queue<pair<int, int>> q;
q.push({r, c});
vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
dist[r][c] = 0;
vector<vector<string>> path(m, vector<string>(n, ""));
vector<vector<int>> dirs = {{-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'}};
while (!q.empty()) {
auto p = q.front();
q.pop();
int i = p.first, j = p.second;
for (auto& dir : dirs) {
int a = dir[0], b = dir[1];
char d = (char) dir[2];
int x = i, y = j;
int step = dist[i][j];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0 && (x != rh || y != ch)) {
x += a;
y += b;
++step;
}
if (dist[x][y] > step || (dist[x][y] == step && (path[i][j] + d < path[x][y]))) {
dist[x][y] = step;
path[x][y] = path[i][j] + d;
if (x != rh || y != ch) q.push({x, y});
}
}
}
return path[rh][ch] == "" ? "impossible" : path[rh][ch];
}
};
| null | null |
import "math"
func findShortestWay(maze [][]int, ball []int, hole []int) string {
m, n := len(maze), len(maze[0])
r, c := ball[0], ball[1]
rh, ch := hole[0], hole[1]
q := [][]int{[]int{r, c}}
dist := make([][]int, m)
path := make([][]string, m)
for i := range dist {
dist[i] = make([]int, n)
path[i] = make([]string, n)
for j := range dist[i] {
dist[i][j] = math.MaxInt32
path[i][j] = ""
}
}
dist[r][c] = 0
dirs := map[string][]int{"u": {-1, 0}, "d": {1, 0}, "l": {0, -1}, "r": {0, 1}}
for len(q) > 0 {
p := q[0]
q = q[1:]
i, j := p[0], p[1]
for d, dir := range dirs {
a, b := dir[0], dir[1]
x, y := i, j
step := dist[i][j]
for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 && (x != rh || y != ch) {
x += a
y += b
step++
}
if dist[x][y] > step || (dist[x][y] == step && (path[i][j]+d) < path[x][y]) {
dist[x][y] = step
path[x][y] = path[i][j] + d
if x != rh || y != ch {
q = append(q, []int{x, y})
}
}
}
}
if path[rh][ch] == "" {
return "impossible"
}
return path[rh][ch]
}
|
class Solution {
public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
int m = maze.length;
int n = maze[0].length;
int r = ball[0], c = ball[1];
int rh = hole[0], ch = hole[1];
Deque<int[]> q = new LinkedList<>();
q.offer(new int[] {r, c});
int[][] dist = new int[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
}
dist[r][c] = 0;
String[][] path = new String[m][n];
path[r][c] = "";
int[][] dirs = {{-1, 0, 'u'}, {1, 0, 'd'}, {0, -1, 'l'}, {0, 1, 'r'}};
while (!q.isEmpty()) {
int[] p = q.poll();
int i = p[0], j = p[1];
for (int[] dir : dirs) {
int a = dir[0], b = dir[1];
String d = String.valueOf((char) (dir[2]));
int x = i, y = j;
int step = dist[i][j];
while (x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0
&& (x != rh || y != ch)) {
x += a;
y += b;
++step;
}
if (dist[x][y] > step
|| (dist[x][y] == step && (path[i][j] + d).compareTo(path[x][y]) < 0)) {
dist[x][y] = step;
path[x][y] = path[i][j] + d;
if (x != rh || y != ch) {
q.offer(new int[] {x, y});
}
}
}
}
return path[rh][ch] == null ? "impossible" : path[rh][ch];
}
}
| null | null | null | null | null | null |
class Solution:
def findShortestWay(
self, maze: List[List[int]], ball: List[int], hole: List[int]
) -> str:
m, n = len(maze), len(maze[0])
r, c = ball
rh, ch = hole
q = deque([(r, c)])
dist = [[inf] * n for _ in range(m)]
dist[r][c] = 0
path = [[None] * n for _ in range(m)]
path[r][c] = ''
while q:
i, j = q.popleft()
for a, b, d in [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')]:
x, y, step = i, j, dist[i][j]
while (
0 <= x + a < m
and 0 <= y + b < n
and maze[x + a][y + b] == 0
and (x != rh or y != ch)
):
x, y = x + a, y + b
step += 1
if dist[x][y] > step or (
dist[x][y] == step and path[i][j] + d < path[x][y]
):
dist[x][y] = step
path[x][y] = path[i][j] + d
if x != rh or y != ch:
q.append((x, y))
return path[rh][ch] or 'impossible'
| null | null | null | null | null | null |
Compact Object
|
Given an object or array
obj
, return a
compact object
.
A
compact object
is the same as the original object, except with keys containing
falsy
values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered
falsy
when
Boolean(value)
returns
false
.
You may assume the
obj
is the output of
JSON.parse
. In other words, it is valid JSON.
Example 1:
Input:
obj = [null, 0, false, 1]
Output:
[1]
Explanation:
All falsy values have been removed from the array.
Example 2:
Input:
obj = {"a": null, "b": [false, 1]}
Output:
{"b": [1]}
Explanation:
obj["a"] and obj["b"][0] had falsy values and were removed.
Example 3:
Input:
obj = [null, 0, 5, [0], [false, 16]]
Output:
[5, [], [16]]
Explanation:
obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints:
obj
is a valid JSON object
2 <= JSON.stringify(obj).length <= 10
6
| null | null | null | null | null | null | null |
/**
* @param {Object|Array} obj
* @return {Object|Array}
*/
var compactObject = function (obj) {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.filter(Boolean).map(compactObject);
}
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value) {
acc[key] = compactObject(value);
}
return acc;
}, {});
};
| null | null | null | null | null | null | null | null | null | null | null |
type Obj = Record<any, any>;
function compactObject(obj: Obj): Obj {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.filter(Boolean).map(compactObject);
}
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value) {
acc[key] = compactObject(value);
}
return acc;
}, {} as Obj);
}
|
Largest Unique Number 🔒
|
Given an integer array
nums
, return
the largest integer that only occurs once
. If no integer occurs once, return
-1
.
Example 1:
Input:
nums = [5,7,3,9,4,9,8,3,1]
Output:
8
Explanation:
The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it is the answer.
Example 2:
Input:
nums = [9,9,8,8]
Output:
-1
Explanation:
There is no number that occurs only once.
Constraints:
1 <= nums.length <= 2000
0 <= nums[i] <= 1000
| null | null |
class Solution {
public:
int largestUniqueNumber(vector<int>& nums) {
int cnt[1001]{};
for (int& x : nums) {
++cnt[x];
}
for (int x = 1000; ~x; --x) {
if (cnt[x] == 1) {
return x;
}
}
return -1;
}
};
| null | null |
func largestUniqueNumber(nums []int) int {
cnt := [1001]int{}
for _, x := range nums {
cnt[x]++
}
for x := 1000; x >= 0; x-- {
if cnt[x] == 1 {
return x
}
}
return -1
}
|
class Solution {
public int largestUniqueNumber(int[] nums) {
int[] cnt = new int[1001];
for (int x : nums) {
++cnt[x];
}
for (int x = 1000; x >= 0; --x) {
if (cnt[x] == 1) {
return x;
}
}
return -1;
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var largestUniqueNumber = function (nums) {
const cnt = Array(1001).fill(0);
for (const x of nums) {
++cnt[x];
}
for (let x = 1000; x >= 0; --x) {
if (cnt[x] === 1) {
return x;
}
}
return -1;
};
| null | null | null | null | null |
class Solution:
def largestUniqueNumber(self, nums: List[int]) -> int:
cnt = Counter(nums)
return max((x for x, v in cnt.items() if v == 1), default=-1)
| null | null | null | null | null |
function largestUniqueNumber(nums: number[]): number {
const cnt = Array(1001).fill(0);
for (const x of nums) {
++cnt[x];
}
for (let x = 1000; x >= 0; --x) {
if (cnt[x] === 1) {
return x;
}
}
return -1;
}
|
Additive Number
|
An
additive number
is a string whose digits can form an
additive sequence
.
A valid
additive sequence
should contain
at least
three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given a string containing only digits, return
true
if it is an
additive number
or
false
otherwise.
Note:
Numbers in the additive sequence
cannot
have leading zeros, so sequence
1, 2, 03
or
1, 02, 3
is invalid.
Example 1:
Input:
"112358"
Output:
true
Explanation:
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
Example 2:
Input:
"199100199"
Output:
true
Explanation:
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Constraints:
1 <= num.length <= 35
num
consists only of digits.
Follow up:
How would you handle overflow for very large input integers?
| null | null |
class Solution {
public:
bool isAdditiveNumber(string num) {
int n = num.size();
for (int i = 1; i < min(n - 1, 19); ++i) {
for (int j = i + 1; j < min(n, i + 19); ++j) {
if (i > 1 && num[0] == '0') break;
if (j - i > 1 && num[i] == '0') continue;
auto a = stoll(num.substr(0, i));
auto b = stoll(num.substr(i, j - i));
if (dfs(a, b, num.substr(j, n - j))) return true;
}
}
return false;
}
bool dfs(long long a, long long b, string num) {
if (num == "") return true;
if (a + b > 0 && num[0] == '0') return false;
for (int i = 1; i < min((int) num.size() + 1, 19); ++i)
if (a + b == stoll(num.substr(0, i)))
if (dfs(b, a + b, num.substr(i, num.size() - i)))
return true;
return false;
}
};
| null | null |
func isAdditiveNumber(num string) bool {
n := len(num)
var dfs func(a, b int64, num string) bool
dfs = func(a, b int64, num string) bool {
if num == "" {
return true
}
if a+b > 0 && num[0] == '0' {
return false
}
for i := 1; i < min(len(num)+1, 19); i++ {
c, _ := strconv.ParseInt(num[:i], 10, 64)
if a+b == c {
if dfs(b, c, num[i:]) {
return true
}
}
}
return false
}
for i := 1; i < min(n-1, 19); i++ {
for j := i + 1; j < min(n, i+19); j++ {
if i > 1 && num[0] == '0' {
break
}
if j-i > 1 && num[i] == '0' {
continue
}
a, _ := strconv.ParseInt(num[:i], 10, 64)
b, _ := strconv.ParseInt(num[i:j], 10, 64)
if dfs(a, b, num[j:]) {
return true
}
}
}
return false
}
|
class Solution {
public boolean isAdditiveNumber(String num) {
int n = num.length();
for (int i = 1; i < Math.min(n - 1, 19); ++i) {
for (int j = i + 1; j < Math.min(n, i + 19); ++j) {
if (i > 1 && num.charAt(0) == '0') {
break;
}
if (j - i > 1 && num.charAt(i) == '0') {
continue;
}
long a = Long.parseLong(num.substring(0, i));
long b = Long.parseLong(num.substring(i, j));
if (dfs(a, b, num.substring(j))) {
return true;
}
}
}
return false;
}
private boolean dfs(long a, long b, String num) {
if ("".equals(num)) {
return true;
}
if (a + b > 0 && num.charAt(0) == '0') {
return false;
}
for (int i = 1; i < Math.min(num.length() + 1, 19); ++i) {
if (a + b == Long.parseLong(num.substring(0, i))) {
if (dfs(b, a + b, num.substring(i))) {
return true;
}
}
}
return false;
}
}
| null | null | null | null | null | null |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
def dfs(a, b, num):
if not num:
return True
if a + b > 0 and num[0] == '0':
return False
for i in range(1, len(num) + 1):
if a + b == int(num[:i]):
if dfs(b, a + b, num[i:]):
return True
return False
n = len(num)
for i in range(1, n - 1):
for j in range(i + 1, n):
if i > 1 and num[0] == '0':
break
if j - i > 1 and num[i] == '0':
continue
if dfs(int(num[:i]), int(num[i:j]), num[j:]):
return True
return False
| null | null | null | null | null | null |
Longest Uncommon Subsequence I
|
Given two strings
a
and
b
, return
the length of the
longest uncommon subsequence
between
a
and
b
.
If no such uncommon subsequence exists, return
-1
.
An
uncommon subsequence
between two strings is a string that is a
subsequence
of exactly one of them
.
Example 1:
Input:
a = "aba", b = "cdc"
Output:
3
Explanation:
One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.
Example 2:
Input:
a = "aaa", b = "bbb"
Output:
3
Explanation:
The longest uncommon subsequences are "aaa" and "bbb".
Example 3:
Input:
a = "aaa", b = "aaa"
Output:
-1
Explanation:
Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be
-1
.
Constraints:
1 <= a.length, b.length <= 100
a
and
b
consist of lower-case English letters.
| null | null |
class Solution {
public:
int findLUSlength(string a, string b) {
return a == b ? -1 : max(a.size(), b.size());
}
};
| null | null |
func findLUSlength(a string, b string) int {
if a == b {
return -1
}
if len(a) > len(b) {
return len(a)
}
return len(b)
}
|
class Solution {
public int findLUSlength(String a, String b) {
return a.equals(b) ? -1 : Math.max(a.length(), b.length());
}
}
| null | null | null | null | null | null |
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
return -1 if a == b else max(len(a), len(b))
| null |
impl Solution {
pub fn find_lu_slength(a: String, b: String) -> i32 {
if a == b {
return -1;
}
a.len().max(b.len()) as i32
}
}
| null | null | null |
function findLUSlength(a: string, b: string): number {
return a === b ? -1 : Math.max(a.length, b.length);
}
|
Number of Ways to Divide a Long Corridor
|
Along a long library corridor, there is a line of seats and decorative plants. You are given a
0-indexed
string
corridor
of length
n
consisting of letters
'S'
and
'P'
where each
'S'
represents a seat and each
'P'
represents a plant.
One room divider has
already
been installed to the left of index
0
, and
another
to the right of index
n - 1
. Additional room dividers can be installed. For each position between indices
i - 1
and
i
(
1 <= i <= n - 1
), at most one divider can be installed.
Divide the corridor into non-overlapping sections, where each section has
exactly two seats
with any number of plants. There may be multiple ways to perform the division. Two ways are
different
if there is a position with a room divider installed in the first way but not in the second way.
Return
the number of ways to divide the corridor
. Since the answer may be very large, return it
modulo
10
9
+ 7
. If there is no way, return
0
.
Example 1:
Input:
corridor = "SSPPSPS"
Output:
3
Explanation:
There are 3 different ways to divide the corridor.
The black bars in the above image indicate the two room dividers already installed.
Note that in each of the ways,
each
section has exactly
two
seats.
Example 2:
Input:
corridor = "PPSPSP"
Output:
1
Explanation:
There is only 1 way to divide the corridor, by not installing any additional dividers.
Installing any would create some section that does not have exactly two seats.
Example 3:
Input:
corridor = "S"
Output:
0
Explanation:
There is no way to divide the corridor because there will always be a section that does not have exactly two seats.
Constraints:
n == corridor.length
1 <= n <= 10
5
corridor[i]
is either
'S'
or
'P'
.
| null | null |
class Solution {
public:
int numberOfWays(string corridor) {
const int mod = 1e9 + 7;
long long ans = 1;
int cnt = 0, last = 0;
for (int i = 0; i < corridor.length(); ++i) {
if (corridor[i] == 'S') {
if (++cnt > 2 && cnt % 2) {
ans = ans * (i - last) % mod;
}
last = i;
}
}
return cnt > 0 && cnt % 2 == 0 ? ans : 0;
}
};
| null | null |
func numberOfWays(corridor string) int {
const mod int = 1e9 + 7
ans, cnt, last := 1, 0, 0
for i, c := range corridor {
if c == 'S' {
cnt++
if cnt > 2 && cnt%2 == 1 {
ans = ans * (i - last) % mod
}
last = i
}
}
if cnt > 0 && cnt%2 == 0 {
return ans
}
return 0
}
|
class Solution {
public int numberOfWays(String corridor) {
final int mod = (int) 1e9 + 7;
long ans = 1, cnt = 0, last = 0;
for (int i = 0; i < corridor.length(); ++i) {
if (corridor.charAt(i) == 'S') {
if (++cnt > 2 && cnt % 2 == 1) {
ans = ans * (i - last) % mod;
}
last = i;
}
}
return cnt > 0 && cnt % 2 == 0 ? (int) ans : 0;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfWays(self, corridor: str) -> int:
mod = 10**9 + 7
ans, cnt, last = 1, 0, 0
for i, c in enumerate(corridor):
if c == "S":
cnt += 1
if cnt > 2 and cnt % 2:
ans = ans * (i - last) % mod
last = i
return ans if cnt and cnt % 2 == 0 else 0
| null | null | null | null | null |
function numberOfWays(corridor: string): number {
const mod = 10 ** 9 + 7;
const n = corridor.length;
let [ans, cnt, last] = [1, 0, 0];
for (let i = 0; i < n; ++i) {
if (corridor[i] === 'S') {
if (++cnt > 2 && cnt % 2) {
ans = (ans * (i - last)) % mod;
}
last = i;
}
}
return cnt > 0 && cnt % 2 === 0 ? ans : 0;
}
|
Construct Product Matrix
|
Given a
0-indexed
2D integer matrix
grid
of size
n * m
, we define a
0-indexed
2D matrix
p
of size
n * m
as the
product
matrix of
grid
if the following condition is met:
Each element
p[i][j]
is calculated as the product of all elements in
grid
except for the element
grid[i][j]
. This product is then taken modulo
12345
.
Return
the product matrix of
grid
.
Example 1:
Input:
grid = [[1,2],[3,4]]
Output:
[[24,12],[8,6]]
Explanation:
p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].
Example 2:
Input:
grid = [[12345],[2],[1]]
Output:
[[2],[0],[0]]
Explanation:
p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].
Constraints:
1 <= n == grid.length <= 10
5
1 <= m == grid[i].length <= 10
5
2 <= n * m <= 10
5
1 <= grid[i][j] <= 10
9
| null | null |
class Solution {
public:
vector<vector<int>> constructProductMatrix(vector<vector<int>>& grid) {
const int mod = 12345;
int n = grid.size(), m = grid[0].size();
vector<vector<int>> p(n, vector<int>(m));
long long suf = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
p[i][j] = suf;
suf = suf * grid[i][j] % mod;
}
}
long long pre = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
p[i][j] = p[i][j] * pre % mod;
pre = pre * grid[i][j] % mod;
}
}
return p;
}
};
| null | null |
func constructProductMatrix(grid [][]int) [][]int {
const mod int = 12345
n, m := len(grid), len(grid[0])
p := make([][]int, n)
for i := range p {
p[i] = make([]int, m)
}
suf := 1
for i := n - 1; i >= 0; i-- {
for j := m - 1; j >= 0; j-- {
p[i][j] = suf
suf = suf * grid[i][j] % mod
}
}
pre := 1
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
p[i][j] = p[i][j] * pre % mod
pre = pre * grid[i][j] % mod
}
}
return p
}
|
class Solution {
public int[][] constructProductMatrix(int[][] grid) {
final int mod = 12345;
int n = grid.length, m = grid[0].length;
int[][] p = new int[n][m];
long suf = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
p[i][j] = (int) suf;
suf = suf * grid[i][j] % mod;
}
}
long pre = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
p[i][j] = (int) (p[i][j] * pre % mod);
pre = pre * grid[i][j] % mod;
}
}
return p;
}
}
| null | null | null | null | null | null |
class Solution:
def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n, m = len(grid), len(grid[0])
p = [[0] * m for _ in range(n)]
mod = 12345
suf = 1
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
p[i][j] = suf
suf = suf * grid[i][j] % mod
pre = 1
for i in range(n):
for j in range(m):
p[i][j] = p[i][j] * pre % mod
pre = pre * grid[i][j] % mod
return p
| null |
impl Solution {
pub fn construct_product_matrix(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let modulo: i32 = 12345;
let n = grid.len();
let m = grid[0].len();
let mut p: Vec<Vec<i32>> = vec![vec![0; m]; n];
let mut suf = 1;
for i in (0..n).rev() {
for j in (0..m).rev() {
p[i][j] = suf;
suf = (((suf as i64) * (grid[i][j] as i64)) % (modulo as i64)) as i32;
}
}
let mut pre = 1;
for i in 0..n {
for j in 0..m {
p[i][j] = (((p[i][j] as i64) * (pre as i64)) % (modulo as i64)) as i32;
pre = (((pre as i64) * (grid[i][j] as i64)) % (modulo as i64)) as i32;
}
}
p
}
}
| null | null | null |
function constructProductMatrix(grid: number[][]): number[][] {
const mod = 12345;
const [n, m] = [grid.length, grid[0].length];
const p: number[][] = Array.from({ length: n }, () => Array.from({ length: m }, () => 0));
let suf = 1;
for (let i = n - 1; ~i; --i) {
for (let j = m - 1; ~j; --j) {
p[i][j] = suf;
suf = (suf * grid[i][j]) % mod;
}
}
let pre = 1;
for (let i = 0; i < n; ++i) {
for (let j = 0; j < m; ++j) {
p[i][j] = (p[i][j] * pre) % mod;
pre = (pre * grid[i][j]) % mod;
}
}
return p;
}
|
Poor Pigs
|
There are
buckets
buckets of liquid, where
exactly one
of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have
minutesToTest
minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
Choose some live pigs to feed.
For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
Wait for
minutesToDie
minutes. You may
not
feed any other pigs during this time.
After
minutesToDie
minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
Repeat this process until you run out of time.
Given
buckets
,
minutesToDie
, and
minutesToTest
, return
the
minimum
number of pigs needed to figure out which bucket is poisonous within the allotted time
.
Example 1:
Input:
buckets = 4, minutesToDie = 15, minutesToTest = 15
Output:
2
Explanation:
We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
Example 2:
Input:
buckets = 4, minutesToDie = 15, minutesToTest = 30
Output:
2
Explanation:
We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
Constraints:
1 <= buckets <= 1000
1 <= minutesToDie <= minutesToTest <= 100
| null | null |
class Solution {
public:
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int base = minutesToTest / minutesToDie + 1;
int res = 0;
for (int p = 1; p < buckets; p *= base) ++res;
return res;
}
};
| null | null |
func poorPigs(buckets int, minutesToDie int, minutesToTest int) int {
base := minutesToTest/minutesToDie + 1
res := 0
for p := 1; p < buckets; p *= base {
res++
}
return res
}
|
class Solution {
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int base = minutesToTest / minutesToDie + 1;
int res = 0;
for (int p = 1; p < buckets; p *= base) {
++res;
}
return res;
}
}
| null | null | null | null | null | null |
class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
base = minutesToTest // minutesToDie + 1
res, p = 0, 1
while p < buckets:
p *= base
res += 1
return res
| null | null | null | null | null | null |
Word Frequency
|
Write a bash script to calculate the
frequency
of each word in a text file
words.txt
.
For simplicity sake, you may assume:
words.txt
contains only lowercase characters and space
' '
characters.
Each word must consist of lowercase characters only.
Words are separated by one or more whitespace characters.
Example:
Assume that
words.txt
has the following content:
the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:
the 4
is 3
sunny 2
day 1
Note:
Don't worry about handling ties, it is guaranteed that each word's frequency count is unique.
Could you write it in one-line using
Unix pipes
?
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Read from the file words.txt and output the word frequency list to stdout.
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'
| null | null |
Maximize the Distance Between Points on a Square
|
You are given an integer
side
, representing the edge length of a square with corners at
(0, 0)
,
(0, side)
,
(side, 0)
, and
(side, side)
on a Cartesian plane.
You are also given a
positive
integer
k
and a 2D integer array
points
, where
points[i] = [x
i
, y
i
]
represents the coordinate of a point lying on the
boundary
of the square.
You need to select
k
elements among
points
such that the
minimum
Manhattan distance between any two points is
maximized
.
Return the
maximum
possible
minimum
Manhattan distance between the selected
k
points.
The Manhattan Distance between two cells
(x
i
, y
i
)
and
(x
j
, y
j
)
is
|x
i
- x
j
| + |y
i
- y
j
|
.
Example 1:
Input:
side = 2, points = [[0,2],[2,0],[2,2],[0,0]], k = 4
Output:
2
Explanation:
Select all four points.
Example 2:
Input:
side = 2, points = [[0,0],[1,2],[2,0],[2,2],[2,1]], k = 4
Output:
1
Explanation:
Select the points
(0, 0)
,
(2, 0)
,
(2, 2)
, and
(2, 1)
.
Example 3:
Input:
side = 2, points = [[0,0],[0,1],[0,2],[1,2],[2,0],[2,2],[2,1]], k = 5
Output:
1
Explanation:
Select the points
(0, 0)
,
(0, 1)
,
(0, 2)
,
(1, 2)
, and
(2, 2)
.
Constraints:
1 <= side <= 10
9
4 <= points.length <= min(4 * side, 15 * 10
3
)
points[i] == [xi, yi]
The input is generated such that:
points[i]
lies on the boundary of the square.
All
points[i]
are
unique
.
4 <= k <= min(25, points.length)
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Remove Boxes
|
You are given several
boxes
with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of
k
boxes,
k >= 1
), remove them and get
k * k
points.
Return
the maximum points you can get
.
Example 1:
Input:
boxes = [1,3,2,2,2,3,4,3,1]
Output:
23
Explanation:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
----> [1, 3, 3, 3, 1] (1*1=1 points)
----> [1, 1] (3*3=9 points)
----> [] (2*2=4 points)
Example 2:
Input:
boxes = [1,1,1]
Output:
9
Example 3:
Input:
boxes = [1]
Output:
1
Constraints:
1 <= boxes.length <= 100
1 <= boxes[i] <= 100
| null | null |
class Solution {
public:
int removeBoxes(vector<int>& boxes) {
int n = boxes.size();
vector<vector<vector<int>>> f(n, vector<vector<int>>(n, vector<int>(n)));
function<int(int, int, int)> dfs;
dfs = [&](int i, int j, int k) {
if (i > j) return 0;
while (i < j && boxes[j] == boxes[j - 1]) {
--j;
++k;
}
if (f[i][j][k]) return f[i][j][k];
int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1);
for (int h = i; h < j; ++h) {
if (boxes[h] == boxes[j]) {
ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1));
}
}
f[i][j][k] = ans;
return ans;
};
return dfs(0, n - 1, 0);
}
};
| null | null |
func removeBoxes(boxes []int) int {
n := len(boxes)
f := make([][][]int, n)
for i := range f {
f[i] = make([][]int, n)
for j := range f[i] {
f[i][j] = make([]int, n)
}
}
var dfs func(i, j, k int) int
dfs = func(i, j, k int) int {
if i > j {
return 0
}
for i < j && boxes[j] == boxes[j-1] {
j, k = j-1, k+1
}
if f[i][j][k] > 0 {
return f[i][j][k]
}
ans := dfs(i, j-1, 0) + (k+1)*(k+1)
for h := i; h < j; h++ {
if boxes[h] == boxes[j] {
ans = max(ans, dfs(h+1, j-1, 0)+dfs(i, h, k+1))
}
}
f[i][j][k] = ans
return ans
}
return dfs(0, n-1, 0)
}
|
class Solution {
private int[][][] f;
private int[] b;
public int removeBoxes(int[] boxes) {
b = boxes;
int n = b.length;
f = new int[n][n][n];
return dfs(0, n - 1, 0);
}
private int dfs(int i, int j, int k) {
if (i > j) {
return 0;
}
while (i < j && b[j] == b[j - 1]) {
--j;
++k;
}
if (f[i][j][k] > 0) {
return f[i][j][k];
}
int ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1);
for (int h = i; h < j; ++h) {
if (b[h] == b[j]) {
ans = Math.max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1));
}
}
f[i][j][k] = ans;
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def removeBoxes(self, boxes: List[int]) -> int:
@cache
def dfs(i, j, k):
if i > j:
return 0
while i < j and boxes[j] == boxes[j - 1]:
j, k = j - 1, k + 1
ans = dfs(i, j - 1, 0) + (k + 1) * (k + 1)
for h in range(i, j):
if boxes[h] == boxes[j]:
ans = max(ans, dfs(h + 1, j - 1, 0) + dfs(i, h, k + 1))
return ans
n = len(boxes)
ans = dfs(0, n - 1, 0)
dfs.cache_clear()
return ans
| null | null | null | null | null | null |
Find the Distinct Difference Array
|
You are given a
0-indexed
array
nums
of length
n
.
The
distinct difference
array of
nums
is an array
diff
of length
n
such that
diff[i]
is equal to the number of distinct elements in the suffix
nums[i + 1, ..., n - 1]
subtracted from
the number of distinct elements in the prefix
nums[0, ..., i]
.
Return
the
distinct difference
array of
nums
.
Note that
nums[i, ..., j]
denotes the subarray of
nums
starting at index
i
and ending at index
j
inclusive. Particularly, if
i > j
then
nums[i, ..., j]
denotes an empty subarray.
Example 1:
Input:
nums = [1,2,3,4,5]
Output:
[-3,-1,1,3,5]
Explanation:
For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3.
For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1.
For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1.
For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3.
For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5.
Example 2:
Input:
nums = [3,2,3,4,2]
Output:
[-2,-1,0,2,3]
Explanation:
For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2.
For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1.
For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0.
For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2.
For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3.
Constraints:
1 <= n == nums.length <= 50
1 <= nums[i] <= 50
| null | null |
class Solution {
public:
vector<int> distinctDifferenceArray(vector<int>& nums) {
int n = nums.size();
vector<int> suf(n + 1);
unordered_set<int> s;
for (int i = n - 1; i >= 0; --i) {
s.insert(nums[i]);
suf[i] = s.size();
}
s.clear();
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
s.insert(nums[i]);
ans[i] = s.size() - suf[i + 1];
}
return ans;
}
};
| null | null |
func distinctDifferenceArray(nums []int) []int {
n := len(nums)
suf := make([]int, n+1)
s := map[int]bool{}
for i := n - 1; i >= 0; i-- {
s[nums[i]] = true
suf[i] = len(s)
}
ans := make([]int, n)
s = map[int]bool{}
for i, x := range nums {
s[x] = true
ans[i] = len(s) - suf[i+1]
}
return ans
}
|
class Solution {
public int[] distinctDifferenceArray(int[] nums) {
int n = nums.length;
int[] suf = new int[n + 1];
Set<Integer> s = new HashSet<>();
for (int i = n - 1; i >= 0; --i) {
s.add(nums[i]);
suf[i] = s.size();
}
s.clear();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
s.add(nums[i]);
ans[i] = s.size() - suf[i + 1];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
n = len(nums)
suf = [0] * (n + 1)
s = set()
for i in range(n - 1, -1, -1):
s.add(nums[i])
suf[i] = len(s)
s.clear()
ans = [0] * n
for i, x in enumerate(nums):
s.add(x)
ans[i] = len(s) - suf[i + 1]
return ans
| null |
use std::collections::HashSet;
impl Solution {
pub fn distinct_difference_array(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut suf = vec![0; n + 1];
let mut s = HashSet::new();
for i in (0..n).rev() {
s.insert(nums[i]);
suf[i] = s.len();
}
let mut ans = Vec::new();
s.clear();
for i in 0..n {
s.insert(nums[i]);
ans.push((s.len() - suf[i + 1]) as i32);
}
ans
}
}
| null | null | null |
function distinctDifferenceArray(nums: number[]): number[] {
const n = nums.length;
const suf: number[] = Array(n + 1).fill(0);
const s: Set<number> = new Set();
for (let i = n - 1; i >= 0; --i) {
s.add(nums[i]);
suf[i] = s.size;
}
s.clear();
const ans: number[] = Array(n).fill(0);
for (let i = 0; i < n; ++i) {
s.add(nums[i]);
ans[i] = s.size - suf[i + 1];
}
return ans;
}
|
Minimum Time to Complete All Tasks
|
There is a computer that can run an unlimited number of tasks
at the same time
. You are given a 2D integer array
tasks
where
tasks[i] = [start
i
, end
i
, duration
i
]
indicates that the
i
th
task should run for a total of
duration
i
seconds (not necessarily continuous) within the
inclusive
time range
[start
i
, end
i
]
.
You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.
Return
the minimum time during which the computer should be turned on to complete all tasks
.
Example 1:
Input:
tasks = [[2,3,1],[4,5,1],[1,5,2]]
Output:
2
Explanation:
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
Example 2:
Input:
tasks = [[1,3,2],[2,5,3],[5,6,2]]
Output:
4
Explanation:
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
Constraints:
1 <= tasks.length <= 2000
tasks[i].length == 3
1 <= start
i
, end
i
<= 2000
1 <= duration
i
<= end
i
- start
i
+ 1
| null | null |
class Solution {
public:
int findMinimumTime(vector<vector<int>>& tasks) {
sort(tasks.begin(), tasks.end(), [&](auto& a, auto& b) { return a[1] < b[1]; });
bitset<2010> vis;
int ans = 0;
for (auto& task : tasks) {
int start = task[0], end = task[1], duration = task[2];
for (int i = start; i <= end; ++i) {
duration -= vis[i];
}
for (int i = end; i >= start && duration > 0; --i) {
if (!vis[i]) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
};
| null | null |
func findMinimumTime(tasks [][]int) (ans int) {
sort.Slice(tasks, func(i, j int) bool { return tasks[i][1] < tasks[j][1] })
vis := [2010]int{}
for _, task := range tasks {
start, end, duration := task[0], task[1], task[2]
for _, x := range vis[start : end+1] {
duration -= x
}
for i := end; i >= start && duration > 0; i-- {
if vis[i] == 0 {
vis[i] = 1
duration--
ans++
}
}
}
return
}
|
class Solution {
public int findMinimumTime(int[][] tasks) {
Arrays.sort(tasks, (a, b) -> a[1] - b[1]);
int[] vis = new int[2010];
int ans = 0;
for (var task : tasks) {
int start = task[0], end = task[1], duration = task[2];
for (int i = start; i <= end; ++i) {
duration -= vis[i];
}
for (int i = end; i >= start && duration > 0; --i) {
if (vis[i] == 0) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def findMinimumTime(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1])
vis = [0] * 2010
ans = 0
for start, end, duration in tasks:
duration -= sum(vis[start : end + 1])
i = end
while i >= start and duration > 0:
if not vis[i]:
duration -= 1
vis[i] = 1
ans += 1
i -= 1
return ans
| null |
impl Solution {
pub fn find_minimum_time(tasks: Vec<Vec<i32>>) -> i32 {
let mut tasks = tasks;
tasks.sort_by(|a, b| a[1].cmp(&b[1]));
let mut vis = vec![0; 2010];
let mut ans = 0;
for task in tasks {
let start = task[0] as usize;
let end = task[1] as usize;
let mut duration = task[2] - vis[start..=end].iter().sum::<i32>();
let mut i = end;
while i >= start && duration > 0 {
if vis[i] == 0 {
duration -= 1;
vis[i] = 1;
ans += 1;
}
i -= 1;
}
}
ans
}
}
| null | null | null |
function findMinimumTime(tasks: number[][]): number {
tasks.sort((a, b) => a[1] - b[1]);
const vis: number[] = Array(2010).fill(0);
let ans = 0;
for (let [start, end, duration] of tasks) {
for (let i = start; i <= end; ++i) {
duration -= vis[i];
}
for (let i = end; i >= start && duration > 0; --i) {
if (vis[i] === 0) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
|
Read N Characters Given Read4 🔒
|
Given a
file
and assume that you can only read the file using a given method
read4
, implement a method to read
n
characters.
Method read4:
The API
read4
reads
four consecutive characters
from
file
, then writes those characters into the buffer array
buf4
.
The return value is the number of actual characters read.
Note that
read4()
has its own file pointer, much like
FILE *fp
in C.
Definition of read4:
Parameter: char[] buf4
Returns: int
buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
Below is a high-level example of how
read4
works:
File file("abcde
"); // File is "
abcde
", initially file pointer (fp) points to 'a'
char[] buf4 = new char[4]; // Create buffer with enough space to store characters
read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file
Method read:
By using the
read4
method, implement the method read that reads
n
characters from
file
and store it in the buffer array
buf
. Consider that you cannot manipulate
file
directly.
The return value is the number of actual characters read.
Definition of read:
Parameters: char[] buf, int n
Returns: int
buf[] is a destination, not a source. You will need to write the results to buf[].
Note:
Consider that you cannot manipulate the file directly. The file is only accessible for
read4
but not for
read
.
The
read
function will only be called once for each test case.
You may assume the destination buffer array,
buf
, is guaranteed to have enough space for storing
n
characters.
Example 1:
Input:
file = "abc", n = 4
Output:
3
Explanation:
After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.
Example 2:
Input:
file = "abcde", n = 5
Output:
5
Explanation:
After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.
Example 3:
Input:
file = "abcdABCD1234", n = 12
Output:
12
Explanation:
After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.
Constraints:
1 <= file.length <= 500
file
consist of English letters and digits.
1 <= n <= 1000
| null | null |
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char* buf, int n) {
char buf4[4];
int i = 0, v = 5;
while (v >= 4) {
v = read4(buf4);
for (int j = 0; j < v; ++j) {
buf[i++] = buf4[j];
if (i >= n) {
return n;
}
}
}
return i;
}
};
| null | null |
/**
* The read4 API is already defined for you.
*
* read4 := func(buf4 []byte) int
*
* // Below is an example of how the read4 API can be called.
* file := File("abcdefghijk") // File is "abcdefghijk", initially file pointer (fp) points to 'a'
* buf4 := make([]byte, 4) // Create buffer with enough space to store characters
* read4(buf4) // read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
* read4(buf4) // read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
* read4(buf4) // read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
*/
var solution = func(read4 func([]byte) int) func([]byte, int) int {
// implement read below.
return func(buf []byte, n int) int {
buf4 := make([]byte, 4)
i, v := 0, 5
for v >= 4 {
v = read4(buf4)
for j := 0; j < v; j++ {
buf[i] = buf4[j]
i++
if i >= n {
return n
}
}
}
return i
}
}
|
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf4);
*/
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
char[] buf4 = new char[4];
int i = 0, v = 5;
while (v >= 4) {
v = read4(buf4);
for (int j = 0; j < v; ++j) {
buf[i++] = buf4[j];
if (i >= n) {
return n;
}
}
}
return i;
}
}
| null | null | null | null | null | null |
"""
The read4 API is already defined for you.
@param buf4, a list of characters
@return an integer
def read4(buf4):
# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf4 = [' '] * 4 # Create buffer with enough space to store characters
read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""
class Solution:
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
i = 0
buf4 = [0] * 4
v = 5
while v >= 4:
v = read4(buf4)
for j in range(v):
buf[i] = buf4[j]
i += 1
if i >= n:
return n
return i
| null | null | null | null | null | null |
Popularity Percentage 🔒
|
Table:
Friends
+-------------+------+
| Column Name | Type |
+-------------+------+
| user1 | int |
| user2 | int |
+-------------+------+
(user1, user2) is the primary key (combination of unique values) of this table.
Each row contains information about friendship where user1 and user2 are friends.
Write a solution to find the popularity percentage for each user on Meta/Facebook. The popularity percentage is defined as the total number of friends the user has divided by the total number of users on the platform, then converted into a percentage by multiplying by 100,
rounded to 2 decimal places
.
Return
the result table ordered by
user1
in
ascending
order.
The result format is in the following example.
Example 1:
Input:
Friends table:
+-------+-------+
| user1 | user2 |
+-------+-------+
| 2 | 1 |
| 1 | 3 |
| 4 | 1 |
| 1 | 5 |
| 1 | 6 |
| 2 | 6 |
| 7 | 2 |
| 8 | 3 |
| 3 | 9 |
+-------+-------+
Output:
+-------+-----------------------+
| user1 | percentage_popularity |
+-------+-----------------------+
| 1 | 55.56 |
| 2 | 33.33 |
| 3 | 33.33 |
| 4 | 11.11 |
| 5 | 11.11 |
| 6 | 22.22 |
| 7 | 11.11 |
| 8 | 11.11 |
| 9 | 11.11 |
+-------+-----------------------+
Explanation:
There are total 9 users on the platform.
- User "1" has friendships with 2, 3, 4, 5 and 6. Therefore, the percentage popularity for user 1 would be calculated as (5/9) * 100 = 55.56.
- User "2" has friendships with 1, 6 and 7. Therefore, the percentage popularity for user 2 would be calculated as (3/9) * 100 = 33.33.
- User "3" has friendships with 1, 8 and 9. Therefore, the percentage popularity for user 3 would be calculated as (3/9) * 100 = 33.33.
- User "4" has friendships with 1. Therefore, the percentage popularity for user 4 would be calculated as (1/9) * 100 = 11.11.
- User "5" has friendships with 1. Therefore, the percentage popularity for user 5 would be calculated as (1/9) * 100 = 11.11.
- User "6" has friendships with 1 and 2. Therefore, the percentage popularity for user 6 would be calculated as (2/9) * 100 = 22.22.
- User "7" has friendships with 2. Therefore, the percentage popularity for user 7 would be calculated as (1/9) * 100 = 11.11.
- User "8" has friendships with 3. Therefore, the percentage popularity for user 8 would be calculated as (1/9) * 100 = 11.11.
- User "9" has friendships with 3. Therefore, the percentage popularity for user 9 would be calculated as (1/9) * 100 = 11.11.
user1 is sorted in ascending order.
| null | null | null | null | null | null | null | null | null |
# Write your MySQL query statement below
WITH
F AS (
SELECT * FROM Friends
UNION
SELECT user2, user1 FROM Friends
),
T AS (SELECT COUNT(DISTINCT user1) AS cnt FROM F)
SELECT DISTINCT
user1,
ROUND(
(COUNT(1) OVER (PARTITION BY user1)) * 100 / (SELECT cnt FROM T),
2
) AS percentage_popularity
FROM F
ORDER BY 1;
| null | null | null | null | null | null | null | null | null | null |
Sort Array By Parity II
|
Given an array of integers
nums
, half of the integers in
nums
are
odd
, and the other half are
even
.
Sort the array so that whenever
nums[i]
is odd,
i
is
odd
, and whenever
nums[i]
is even,
i
is
even
.
Return
any answer array that satisfies this condition
.
Example 1:
Input:
nums = [4,2,5,7]
Output:
[4,5,2,7]
Explanation:
[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Example 2:
Input:
nums = [2,3]
Output:
[2,3]
Constraints:
2 <= nums.length <= 2 * 10
4
nums.length
is even.
Half of the integers in
nums
are even.
0 <= nums[i] <= 1000
Follow Up:
Could you solve it in-place?
| null | null |
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
for (int i = 0, j = 1; i < nums.size(); i += 2) {
if (nums[i] % 2) {
while (nums[j] % 2) {
j += 2;
}
swap(nums[i], nums[j]);
}
}
return nums;
}
};
| null | null |
func sortArrayByParityII(nums []int) []int {
for i, j := 0, 1; i < len(nums); i += 2 {
if nums[i]%2 == 1 {
for nums[j]%2 == 1 {
j += 2
}
nums[i], nums[j] = nums[j], nums[i]
}
}
return nums
}
|
class Solution {
public int[] sortArrayByParityII(int[] nums) {
for (int i = 0, j = 1; i < nums.length; i += 2) {
if (nums[i] % 2 == 1) {
while (nums[j] % 2 == 1) {
j += 2;
}
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
return nums;
}
}
|
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortArrayByParityII = function (nums) {
for (let i = 0, j = 1; i < nums.length; i += 2) {
if (nums[i] % 2) {
while (nums[j] % 2) {
j += 2;
}
[nums[i], nums[j]] = [nums[j], nums[i]];
}
}
return nums;
};
| null | null | null | null | null |
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
n, j = len(nums), 1
for i in range(0, n, 2):
if nums[i] % 2:
while nums[j] % 2:
j += 2
nums[i], nums[j] = nums[j], nums[i]
return nums
| null |
impl Solution {
pub fn sort_array_by_parity_ii(mut nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut j = 1;
for i in (0..n).step_by(2) {
if nums[i] % 2 != 0 {
while nums[j] % 2 != 0 {
j += 2;
}
nums.swap(i, j);
}
}
nums
}
}
| null | null | null |
function sortArrayByParityII(nums: number[]): number[] {
for (let i = 0, j = 1; i < nums.length; i += 2) {
if (nums[i] % 2) {
while (nums[j] % 2) {
j += 2;
}
[nums[i], nums[j]] = [nums[j], nums[i]];
}
}
return nums;
}
|
Minimum Number of Moves to Make Palindrome
|
You are given a string
s
consisting only of lowercase English letters.
In one
move
, you can select any two
adjacent
characters of
s
and swap them.
Return
the
minimum number of moves
needed to make
s
a palindrome
.
Note
that the input will be generated such that
s
can always be converted to a palindrome.
Example 1:
Input:
s = "aabb"
Output:
2
Explanation:
We can obtain two palindromes from s, "abba" and "baab".
- We can obtain "abba" from s in 2 moves: "a
ab
b" -> "ab
ab
" -> "abba".
- We can obtain "baab" from s in 2 moves: "a
ab
b" -> "
ab
ab" -> "baab".
Thus, the minimum number of moves needed to make s a palindrome is 2.
Example 2:
Input:
s = "letelt"
Output:
2
Explanation:
One of the palindromes we can obtain from s in 2 moves is "lettel".
One of the ways we can obtain it is "lete
lt
" -> "let
et
l" -> "lettel".
Other palindromes such as "tleelt" can also be obtained in 2 moves.
It can be shown that it is not possible to obtain a palindrome in less than 2 moves.
Constraints:
1 <= s.length <= 2000
s
consists only of lowercase English letters.
s
can be converted to a palindrome using a finite number of moves.
| null | null |
class Solution {
public:
int minMovesToMakePalindrome(string s) {
int n = s.size();
int ans = 0;
for (int i = 0, j = n - 1; i < j; ++i) {
bool even = false;
for (int k = j; k != i; --k) {
if (s[i] == s[k]) {
even = true;
for (; k < j; ++k) {
swap(s[k], s[k + 1]);
++ans;
}
--j;
break;
}
}
if (!even) ans += n / 2 - i;
}
return ans;
}
};
| null | null |
func minMovesToMakePalindrome(s string) int {
cs := []byte(s)
ans, n := 0, len(s)
for i, j := 0, n-1; i < j; i++ {
even := false
for k := j; k != i; k-- {
if cs[i] == cs[k] {
even = true
for ; k < j; k++ {
cs[k], cs[k+1] = cs[k+1], cs[k]
ans++
}
j--
break
}
}
if !even {
ans += n/2 - i
}
}
return ans
}
|
class Solution {
public int minMovesToMakePalindrome(String s) {
int n = s.length();
int ans = 0;
char[] cs = s.toCharArray();
for (int i = 0, j = n - 1; i < j; ++i) {
boolean even = false;
for (int k = j; k != i; --k) {
if (cs[i] == cs[k]) {
even = true;
for (; k < j; ++k) {
char t = cs[k];
cs[k] = cs[k + 1];
cs[k + 1] = t;
++ans;
}
--j;
break;
}
}
if (!even) {
ans += n / 2 - i;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minMovesToMakePalindrome(self, s: str) -> int:
cs = list(s)
ans, n = 0, len(s)
i, j = 0, n - 1
while i < j:
even = False
for k in range(j, i, -1):
if cs[i] == cs[k]:
even = True
while k < j:
cs[k], cs[k + 1] = cs[k + 1], cs[k]
k += 1
ans += 1
j -= 1
break
if not even:
ans += n // 2 - i
i += 1
return ans
| null | null | null | null | null | null |
Verify Preorder Serialization of a Binary Tree
|
One way to serialize a binary tree is to use
preorder traversal
. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as
'#'
.
For example, the above binary tree can be serialized to the string
"9,3,4,#,#,1,#,#,2,#,6,#,#"
, where
'#'
represents a null node.
Given a string of comma-separated values
preorder
, return
true
if it is a correct preorder traversal serialization of a binary tree.
It is
guaranteed
that each comma-separated value in the string must be either an integer or a character
'#'
representing null pointer.
You may assume that the input format is always valid.
For example, it could never contain two consecutive commas, such as
"1,,3"
.
Note:
You are not allowed to reconstruct the tree.
Example 1:
Input:
preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output:
true
Example 2:
Input:
preorder = "1,#"
Output:
false
Example 3:
Input:
preorder = "9,#,#,1"
Output:
false
Constraints:
1 <= preorder.length <= 10
4
preorder
consist of integers in the range
[0, 100]
and
'#'
separated by commas
','
.
| null | null |
class Solution {
public:
bool isValidSerialization(string preorder) {
vector<string> stk;
stringstream ss(preorder);
string s;
while (getline(ss, s, ',')) {
stk.push_back(s);
while (stk.size() >= 3 && stk[stk.size() - 1] == "#" && stk[stk.size() - 2] == "#" && stk[stk.size() - 3] != "#") {
stk.pop_back();
stk.pop_back();
stk.pop_back();
stk.push_back("#");
}
}
return stk.size() == 1 && stk[0] == "#";
}
};
| null | null |
func isValidSerialization(preorder string) bool {
stk := []string{}
for _, s := range strings.Split(preorder, ",") {
stk = append(stk, s)
for len(stk) >= 3 && stk[len(stk)-1] == "#" && stk[len(stk)-2] == "#" && stk[len(stk)-3] != "#" {
stk = stk[:len(stk)-3]
stk = append(stk, "#")
}
}
return len(stk) == 1 && stk[0] == "#"
}
|
class Solution {
public boolean isValidSerialization(String preorder) {
List<String> stk = new ArrayList<>();
for (String s : preorder.split(",")) {
stk.add(s);
while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#")
&& stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) {
stk.remove(stk.size() - 1);
stk.remove(stk.size() - 1);
stk.remove(stk.size() - 1);
stk.add("#");
}
}
return stk.size() == 1 && stk.get(0).equals("#");
}
}
| null | null | null | null | null | null |
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stk = []
for c in preorder.split(","):
stk.append(c)
while len(stk) > 2 and stk[-1] == stk[-2] == "#" and stk[-3] != "#":
stk = stk[:-3]
stk.append("#")
return len(stk) == 1 and stk[0] == "#"
| null | null | null | null | null |
function isValidSerialization(preorder: string): boolean {
const stk: string[] = [];
for (const s of preorder.split(',')) {
stk.push(s);
while (stk.length >= 3 && stk.at(-1) === '#' && stk.at(-2) === '#' && stk.at(-3) !== '#') {
stk.splice(-3, 3, '#');
}
}
return stk.length === 1 && stk[0] === '#';
}
|
Count Negative Numbers in a Sorted Matrix
|
Given a
m x n
matrix
grid
which is sorted in non-increasing order both row-wise and column-wise, return
the number of
negative
numbers in
grid
.
Example 1:
Input:
grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output:
8
Explanation:
There are 8 negatives number in the matrix.
Example 2:
Input:
grid = [[3,2],[1,0]]
Output:
0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
Follow up:
Could you find an
O(n + m)
solution?
| null | null |
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int ans = 0;
for (auto& row : grid) {
ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin();
}
return ans;
}
};
| null | null |
func countNegatives(grid [][]int) int {
ans, n := 0, len(grid[0])
for _, row := range grid {
left, right := 0, n
for left < right {
mid := (left + right) >> 1
if row[mid] < 0 {
right = mid
} else {
left = mid + 1
}
}
ans += n - left
}
return ans
}
|
class Solution {
public int countNegatives(int[][] grid) {
int ans = 0;
int n = grid[0].length;
for (int[] row : grid) {
int left = 0, right = n;
while (left < right) {
int mid = (left + right) >> 1;
if (row[mid] < 0) {
right = mid;
} else {
left = mid + 1;
}
}
ans += n - left;
}
return ans;
}
}
|
/**
* @param {number[][]} grid
* @return {number}
*/
var countNegatives = function (grid) {
const n = grid[0].length;
let ans = 0;
for (let row of grid) {
let left = 0,
right = n;
while (left < right) {
const mid = (left + right) >> 1;
if (row[mid] < 0) {
right = mid;
} else {
left = mid + 1;
}
}
ans += n - left;
}
return ans;
};
| null | null | null | null | null |
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
return sum(bisect_left(row[::-1], 0) for row in grid)
| null |
impl Solution {
pub fn count_negatives(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut i = m;
let mut j = 0;
let mut res = 0;
while i > 0 && j < n {
if grid[i - 1][j] >= 0 {
j += 1;
} else {
res += n - j;
i -= 1;
}
}
res as i32
}
}
| null | null | null |
function countNegatives(grid: number[][]): number {
const n = grid[0].length;
let ans = 0;
for (let row of grid) {
let left = 0,
right = n;
while (left < right) {
const mid = (left + right) >> 1;
if (row[mid] < 0) {
right = mid;
} else {
left = mid + 1;
}
}
ans += n - left;
}
return ans;
}
|
Alice and Bob Playing Flower Game
|
Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are
x
flowers in the clockwise direction between Alice and Bob, and
y
flowers in the anti-clockwise direction between them.
The game proceeds as follows:
Alice takes the first turn.
In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.
At the end of the turn, if there are no flowers left at all, the
current
player captures their opponent and wins the game.
Given two integers,
n
and
m
, the task is to compute the number of possible pairs
(x, y)
that satisfy the conditions:
Alice must win the game according to the described rules.
The number of flowers
x
in the clockwise direction must be in the range
[1,n]
.
The number of flowers
y
in the anti-clockwise direction must be in the range
[1,m]
.
Return
the number of possible pairs
(x, y)
that satisfy the conditions mentioned in the statement
.
Example 1:
Input:
n = 3, m = 2
Output:
3
Explanation:
The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
Example 2:
Input:
n = 1, m = 1
Output:
0
Explanation:
No pairs satisfy the conditions described in the statement.
Constraints:
1 <= n, m <= 10
5
| null | null |
class Solution {
public:
long long flowerGame(int n, int m) {
return ((long long) n * m) / 2;
}
};
| null | null |
func flowerGame(n int, m int) int64 {
return int64((n * m) / 2)
}
|
class Solution {
public long flowerGame(int n, int m) {
return ((long) n * m) / 2;
}
}
| null | null | null | null | null | null |
class Solution:
def flowerGame(self, n: int, m: int) -> int:
return (n * m) // 2
| null | null | null | null | null |
function flowerGame(n: number, m: number): number {
return Number(((BigInt(n) * BigInt(m)) / 2n) | 0n);
}
|
K Items With the Maximum Sum
|
There is a bag that consists of items, each item has a number
1
,
0
, or
-1
written on it.
You are given four
non-negative
integers
numOnes
,
numZeros
,
numNegOnes
, and
k
.
The bag initially contains:
numOnes
items with
1
s written on them.
numZeroes
items with
0
s written on them.
numNegOnes
items with
-1
s written on them.
We want to pick exactly
k
items among the available items. Return
the
maximum
possible sum of numbers written on the items
.
Example 1:
Input:
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2
Output:
2
Explanation:
We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2.
It can be proven that 2 is the maximum possible sum.
Example 2:
Input:
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
Output:
3
Explanation:
We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3.
It can be proven that 3 is the maximum possible sum.
Constraints:
0 <= numOnes, numZeros, numNegOnes <= 50
0 <= k <= numOnes + numZeros + numNegOnes
| null |
public class Solution {
public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
if (numOnes >= k) {
return k;
}
if (numZeros >= k - numOnes) {
return numOnes;
}
return numOnes - (k - numOnes - numZeros);
}
}
|
class Solution {
public:
int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
if (numOnes >= k) {
return k;
}
if (numZeros >= k - numOnes) {
return numOnes;
}
return numOnes - (k - numOnes - numZeros);
}
};
| null | null |
func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int {
if numOnes >= k {
return k
}
if numZeros >= k-numOnes {
return numOnes
}
return numOnes - (k - numOnes - numZeros)
}
|
class Solution {
public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
if (numOnes >= k) {
return k;
}
if (numZeros >= k - numOnes) {
return numOnes;
}
return numOnes - (k - numOnes - numZeros);
}
}
| null | null | null | null | null | null |
class Solution:
def kItemsWithMaximumSum(
self, numOnes: int, numZeros: int, numNegOnes: int, k: int
) -> int:
if numOnes >= k:
return k
if numZeros >= k - numOnes:
return numOnes
return numOnes - (k - numOnes - numZeros)
| null |
impl Solution {
pub fn k_items_with_maximum_sum(
num_ones: i32,
num_zeros: i32,
num_neg_ones: i32,
k: i32,
) -> i32 {
if num_ones > k {
return k;
}
if num_ones + num_zeros > k {
return num_ones;
}
num_ones - (k - num_ones - num_zeros)
}
}
| null | null | null |
function kItemsWithMaximumSum(
numOnes: number,
numZeros: number,
numNegOnes: number,
k: number,
): number {
if (numOnes >= k) {
return k;
}
if (numZeros >= k - numOnes) {
return numOnes;
}
return numOnes - (k - numOnes - numZeros);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.