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
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Check for Contradictions in Equations 🔒
|
You are given a 2D array of strings
equations
and an array of real numbers
values
, where
equations[i] = [A
i
, B
i
]
and
values[i]
means that
A
i
/ B
i
= values[i]
.
Determine if there exists a contradiction in the equations. Return
true
if there is a contradiction, or
false
otherwise
.
Note
:
When checking if two numbers are equal, check that their
absolute difference
is less than
10
-5
.
The testcases are generated such that there are no cases targeting precision, i.e. using
double
is enough to solve the problem.
Example 1:
Input:
equations = [["a","b"],["b","c"],["a","c"]], values = [3,0.5,1.5]
Output:
false
Explanation:
The given equations are: a / b = 3, b / c = 0.5, a / c = 1.5
There are no contradictions in the equations. One possible assignment to satisfy all equations is:
a = 3, b = 1 and c = 2.
Example 2:
Input:
equations = [["le","et"],["le","code"],["code","et"]], values = [2,5,0.5]
Output:
true
Explanation:
The given equations are: le / et = 2, le / code = 5, code / et = 0.5
Based on the first two equations, we get code / et = 0.4.
Since the third equation is code / et = 0.5, we get a contradiction.
Constraints:
1 <= equations.length <= 100
equations[i].length == 2
1 <= A
i
.length, B
i
.length <= 5
A
i
,
B
i
consist of lowercase English letters.
equations.length == values.length
0.0 < values[i] <= 10.0
values[i]
has a maximum of 2 decimal places.
| null | null |
class Solution {
public:
bool checkContradictions(vector<vector<string>>& equations, vector<double>& values) {
unordered_map<string, int> d;
int n = 0;
for (auto& e : equations) {
for (auto& s : e) {
if (!d.count(s)) {
d[s] = n++;
}
}
}
vector<int> p(n);
iota(p.begin(), p.end(), 0);
vector<double> w(n, 1.0);
function<int(int)> find = [&](int x) -> int {
if (p[x] != x) {
int root = find(p[x]);
w[x] *= w[p[x]];
p[x] = root;
}
return p[x];
};
for (int i = 0; i < equations.size(); ++i) {
int a = d[equations[i][0]], b = d[equations[i][1]];
double v = values[i];
int pa = find(a), pb = find(b);
if (pa != pb) {
p[pb] = pa;
w[pb] = v * w[a] / w[b];
} else if (fabs(v * w[a] - w[b]) >= 1e-5) {
return true;
}
}
return false;
}
};
| null | null |
func checkContradictions(equations [][]string, values []float64) bool {
d := make(map[string]int)
n := 0
for _, e := range equations {
for _, s := range e {
if _, ok := d[s]; !ok {
d[s] = n
n++
}
}
}
p := make([]int, n)
for i := range p {
p[i] = i
}
w := make([]float64, n)
for i := range w {
w[i] = 1.0
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
root := find(p[x])
w[x] *= w[p[x]]
p[x] = root
}
return p[x]
}
for i, e := range equations {
a, b := d[e[0]], d[e[1]]
v := values[i]
pa, pb := find(a), find(b)
if pa != pb {
p[pb] = pa
w[pb] = v * w[a] / w[b]
} else if v*w[a]-w[b] >= 1e-5 || w[b]-v*w[a] >= 1e-5 {
return true
}
}
return false
}
|
class Solution {
private int[] p;
private double[] w;
public boolean checkContradictions(List<List<String>> equations, double[] values) {
Map<String, Integer> d = new HashMap<>();
int n = 0;
for (var e : equations) {
for (var s : e) {
if (!d.containsKey(s)) {
d.put(s, n++);
}
}
}
p = new int[n];
w = new double[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
w[i] = 1.0;
}
final double eps = 1e-5;
for (int i = 0; i < equations.size(); ++i) {
int a = d.get(equations.get(i).get(0)), b = d.get(equations.get(i).get(1));
int pa = find(a), pb = find(b);
double v = values[i];
if (pa != pb) {
p[pb] = pa;
w[pb] = v * w[a] / w[b];
} else if (Math.abs(v * w[a] - w[b]) >= eps) {
return true;
}
}
return false;
}
private int find(int x) {
if (p[x] != x) {
int root = find(p[x]);
w[x] *= w[p[x]];
p[x] = root;
}
return p[x];
}
}
| null | null | null | null | null | null |
class Solution:
def checkContradictions(
self, equations: List[List[str]], values: List[float]
) -> bool:
def find(x: int) -> int:
if p[x] != x:
root = find(p[x])
w[x] *= w[p[x]]
p[x] = root
return p[x]
d = defaultdict(int)
n = 0
for e in equations:
for s in e:
if s not in d:
d[s] = n
n += 1
p = list(range(n))
w = [1.0] * n
eps = 1e-5
for (a, b), v in zip(equations, values):
a, b = d[a], d[b]
pa, pb = find(a), find(b)
if pa != pb:
p[pb] = pa
w[pb] = v * w[a] / w[b]
elif abs(v * w[a] - w[b]) >= eps:
return True
return False
| null | null | null | null | null |
function checkContradictions(equations: string[][], values: number[]): boolean {
const d: { [key: string]: number } = {};
let n = 0;
for (const e of equations) {
for (const s of e) {
if (!(s in d)) {
d[s] = n;
n++;
}
}
}
const p: number[] = Array.from({ length: n }, (_, i) => i);
const w: number[] = Array.from({ length: n }, () => 1.0);
const find = (x: number): number => {
if (p[x] !== x) {
const root = find(p[x]);
w[x] *= w[p[x]];
p[x] = root;
}
return p[x];
};
for (let i = 0; i < equations.length; i++) {
const a = d[equations[i][0]];
const b = d[equations[i][1]];
const v = values[i];
const pa = find(a);
const pb = find(b);
if (pa !== pb) {
p[pb] = pa;
w[pb] = (v * w[a]) / w[b];
} else if (Math.abs(v * w[a] - w[b]) >= 1e-5) {
return true;
}
}
return false;
}
|
Minimum Cuts to Divide a Circle
|
A
valid cut
in a circle can be:
A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or
A cut that is represented by a straight line that touches one point on the edge of the circle and its center.
Some valid and invalid cuts are shown in the figures below.
Given the integer
n
, return
the
minimum
number of cuts needed to divide a circle into
n
equal slices
.
Example 1:
Input:
n = 4
Output:
2
Explanation:
The above figure shows how cutting the circle twice through the middle divides it into 4 equal slices.
Example 2:
Input:
n = 3
Output:
3
Explanation:
At least 3 cuts are needed to divide the circle into 3 equal slices.
It can be shown that less than 3 cuts cannot result in 3 slices of equal size and shape.
Also note that the first cut will not divide the circle into distinct parts.
Constraints:
1 <= n <= 100
| null |
public class Solution {
public int NumberOfCuts(int n) {
return n > 1 && n % 2 == 1 ? n : n >> 1;
}
}
|
class Solution {
public:
int numberOfCuts(int n) {
return n > 1 && n % 2 == 1 ? n : n >> 1;
}
};
| null | null |
func numberOfCuts(n int) int {
if n > 1 && n%2 == 1 {
return n
}
return n >> 1
}
|
class Solution {
public int numberOfCuts(int n) {
return n > 1 && n % 2 == 1 ? n : n >> 1;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfCuts(self, n: int) -> int:
return n if (n > 1 and n & 1) else n >> 1
| null |
impl Solution {
pub fn number_of_cuts(n: i32) -> i32 {
if n > 1 && n % 2 == 1 {
return n;
}
n >> 1
}
}
| null | null | null |
function numberOfCuts(n: number): number {
return n > 1 && n & 1 ? n : n >> 1;
}
|
Prison Cells After N Days
|
There are
8
prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
Note
that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array
cells
where
cells[i] == 1
if the
i
th
cell is occupied and
cells[i] == 0
if the
i
th
cell is vacant, and you are given an integer
n
.
Return the state of the prison after
n
days (i.e.,
n
such changes described above).
Example 1:
Input:
cells = [0,1,0,1,1,0,0,1], n = 7
Output:
[0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input:
cells = [1,0,0,1,0,0,1,0], n = 1000000000
Output:
[0,0,1,1,1,1,1,0]
Constraints:
cells.length == 8
cells[i]
is either
0
or
1
.
1 <= n <= 10
9
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Maximum Difference Between Even and Odd Frequency I
|
You are given a string
s
consisting of lowercase English letters.
Your task is to find the
maximum
difference
diff = freq(a
1
) - freq(a
2
)
between the frequency of characters
a
1
and
a
2
in the string such that:
a
1
has an
odd frequency
in the string.
a
2
has an
even frequency
in the string.
Return this
maximum
difference.
Example 1:
Input:
s = "aaaaabbc"
Output:
3
Explanation:
The character
'a'
has an
odd frequency
of
5
,
and
'b'
has an
even frequency
of
2
.
The maximum difference is
5 - 2 = 3
.
Example 2:
Input:
s = "abcabcab"
Output:
1
Explanation:
The character
'a'
has an
odd frequency
of
3
,
and
'c'
has an
even frequency
of
2
.
The maximum difference is
3 - 2 = 1
.
Constraints:
3 <= s.length <= 100
s
consists only of lowercase English letters.
s
contains at least one character with an odd frequency and one with an even frequency.
| null |
public class Solution {
public int MaxDifference(string s) {
int[] cnt = new int[26];
foreach (char c in s) {
++cnt[c - 'a'];
}
int a = 0, b = 1 << 30;
foreach (int v in cnt) {
if (v % 2 == 1) {
a = Math.Max(a, v);
} else if (v > 0) {
b = Math.Min(b, v);
}
}
return a - b;
}
}
|
class Solution {
public:
int maxDifference(string s) {
int cnt[26]{};
for (char c : s) {
++cnt[c - 'a'];
}
int a = 0, b = 1 << 30;
for (int v : cnt) {
if (v % 2 == 1) {
a = max(a, v);
} else if (v > 0) {
b = min(b, v);
}
}
return a - b;
}
};
| null | null |
func maxDifference(s string) int {
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
a, b := 0, 1<<30
for _, v := range cnt {
if v%2 == 1 {
a = max(a, v)
} else if v > 0 {
b = min(b, v)
}
}
return a - b
}
|
class Solution {
public int maxDifference(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
int a = 0, b = 1 << 30;
for (int v : cnt) {
if (v % 2 == 1) {
a = Math.max(a, v);
} else if (v > 0) {
b = Math.min(b, v);
}
}
return a - b;
}
}
| null | null | null | null | null | null |
class Solution:
def maxDifference(self, s: str) -> int:
cnt = Counter(s)
a, b = 0, inf
for v in cnt.values():
if v % 2:
a = max(a, v)
else:
b = min(b, v)
return a - b
| null |
impl Solution {
pub fn max_difference(s: String) -> i32 {
let mut cnt = [0; 26];
for c in s.bytes() {
cnt[(c - b'a') as usize] += 1;
}
let mut a = 0;
let mut b = 1 << 30;
for &v in cnt.iter() {
if v % 2 == 1 {
a = a.max(v);
} else if v > 0 {
b = b.min(v);
}
}
a - b
}
}
| null | null | null |
function maxDifference(s: string): number {
const cnt: Record<string, number> = {};
for (const c of s) {
cnt[c] = (cnt[c] || 0) + 1;
}
let [a, b] = [0, Infinity];
for (const [_, v] of Object.entries(cnt)) {
if (v % 2 === 1) {
a = Math.max(a, v);
} else {
b = Math.min(b, v);
}
}
return a - b;
}
|
Naming a Company
|
You are given an array of strings
ideas
that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
Choose 2
distinct
names from
ideas
, call them
idea
A
and
idea
B
.
Swap the first letters of
idea
A
and
idea
B
with each other.
If
both
of the new names are not found in the original
ideas
, then the name
idea
A
idea
B
(the
concatenation
of
idea
A
and
idea
B
, separated by a space) is a valid company name.
Otherwise, it is not a valid name.
Return
the number of
distinct
valid names for the company
.
Example 1:
Input:
ideas = ["coffee","donuts","time","toffee"]
Output:
6
Explanation:
The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.
The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
Example 2:
Input:
ideas = ["lack","back"]
Output:
0
Explanation:
There are no valid selections. Therefore, 0 is returned.
Constraints:
2 <= ideas.length <= 5 * 10
4
1 <= ideas[i].length <= 10
ideas[i]
consists of lowercase English letters.
All the strings in
ideas
are
unique
.
| null | null |
class Solution {
public:
long long distinctNames(vector<string>& ideas) {
unordered_set<string> s(ideas.begin(), ideas.end());
int f[26][26]{};
for (auto v : ideas) {
int i = v[0] - 'a';
for (int j = 0; j < 26; ++j) {
v[0] = j + 'a';
if (!s.count(v)) {
++f[i][j];
}
}
}
long long ans = 0;
for (auto& v : ideas) {
int i = v[0] - 'a';
for (int j = 0; j < 26; ++j) {
v[0] = j + 'a';
if (!s.count(v)) {
ans += f[j][i];
}
}
}
return ans;
}
};
| null | null |
func distinctNames(ideas []string) (ans int64) {
s := map[string]bool{}
for _, v := range ideas {
s[v] = true
}
f := [26][26]int{}
for _, v := range ideas {
i := int(v[0] - 'a')
t := []byte(v)
for j := 0; j < 26; j++ {
t[0] = 'a' + byte(j)
if !s[string(t)] {
f[i][j]++
}
}
}
for _, v := range ideas {
i := int(v[0] - 'a')
t := []byte(v)
for j := 0; j < 26; j++ {
t[0] = 'a' + byte(j)
if !s[string(t)] {
ans += int64(f[j][i])
}
}
}
return
}
|
class Solution {
public long distinctNames(String[] ideas) {
Set<String> s = new HashSet<>();
for (String v : ideas) {
s.add(v);
}
int[][] f = new int[26][26];
for (String v : ideas) {
char[] t = v.toCharArray();
int i = t[0] - 'a';
for (int j = 0; j < 26; ++j) {
t[0] = (char) (j + 'a');
if (!s.contains(String.valueOf(t))) {
++f[i][j];
}
}
}
long ans = 0;
for (String v : ideas) {
char[] t = v.toCharArray();
int i = t[0] - 'a';
for (int j = 0; j < 26; ++j) {
t[0] = (char) (j + 'a');
if (!s.contains(String.valueOf(t))) {
ans += f[j][i];
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def distinctNames(self, ideas: List[str]) -> int:
s = set(ideas)
f = [[0] * 26 for _ in range(26)]
for v in ideas:
i = ord(v[0]) - ord('a')
t = list(v)
for j in range(26):
t[0] = chr(ord('a') + j)
if ''.join(t) not in s:
f[i][j] += 1
ans = 0
for v in ideas:
i = ord(v[0]) - ord('a')
t = list(v)
for j in range(26):
t[0] = chr(ord('a') + j)
if ''.join(t) not in s:
ans += f[j][i]
return ans
| null | null | null | null | null | null |
Find the Shortest Superstring
|
Given an array of strings
words
, return
the smallest string that contains each string in
words
as a substring
. If there are multiple valid strings of the smallest length, return
any of them
.
You may assume that no string in
words
is a substring of another string in
words
.
Example 1:
Input:
words = ["alex","loves","leetcode"]
Output:
"alexlovesleetcode"
Explanation:
All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input:
words = ["catg","ctaagt","gcta","ttca","atgcatc"]
Output:
"gctaagttcatgcatc"
Constraints:
1 <= words.length <= 12
1 <= words[i].length <= 20
words[i]
consists of lowercase English letters.
All the strings of
words
are
unique
.
| null | null |
class Solution {
public:
string shortestSuperstring(vector<string>& words) {
int n = words.size();
vector<vector<int>> g(n, vector<int>(n));
for (int i = 0; i < n; ++i) {
auto a = words[i];
for (int j = 0; j < n; ++j) {
auto b = words[j];
if (i != j) {
for (int k = min(a.size(), b.size()); k > 0; --k) {
if (a.substr(a.size() - k) == b.substr(0, k)) {
g[i][j] = k;
break;
}
}
}
}
}
vector<vector<int>> dp(1 << n, vector<int>(n));
vector<vector<int>> p(1 << n, vector<int>(n, -1));
for (int i = 0; i < 1 << n; ++i) {
for (int j = 0; j < n; ++j) {
if ((i >> j) & 1) {
int pi = i ^ (1 << j);
for (int k = 0; k < n; ++k) {
if ((pi >> k) & 1) {
int v = dp[pi][k] + g[k][j];
if (v > dp[i][j]) {
dp[i][j] = v;
p[i][j] = k;
}
}
}
}
}
}
int j = 0;
for (int i = 0; i < n; ++i) {
if (dp[(1 << n) - 1][i] > dp[(1 << n) - 1][j]) {
j = i;
}
}
vector<int> arr = {j};
for (int i = (1 << n) - 1; p[i][j] != -1;) {
int k = i;
i ^= (1 << j);
j = p[k][j];
arr.push_back(j);
}
unordered_set<int> vis(arr.begin(), arr.end());
for (int i = 0; i < n; ++i) {
if (!vis.count(i)) {
arr.push_back(i);
}
}
reverse(arr.begin(), arr.end());
string ans = words[arr[0]];
for (int i = 1; i < n; ++i) {
int k = g[arr[i - 1]][arr[i]];
ans += words[arr[i]].substr(k);
}
return ans;
}
};
| null | null |
func shortestSuperstring(words []string) string {
n := len(words)
g := make([][]int, n)
for i, a := range words {
g[i] = make([]int, n)
for j, b := range words {
if i != j {
for k := min(len(a), len(b)); k > 0; k-- {
if a[len(a)-k:] == b[:k] {
g[i][j] = k
break
}
}
}
}
}
dp := make([][]int, 1<<n)
p := make([][]int, 1<<n)
for i := 0; i < 1<<n; i++ {
dp[i] = make([]int, n)
p[i] = make([]int, n)
for j := 0; j < n; j++ {
p[i][j] = -1
if ((i >> j) & 1) == 1 {
pi := i ^ (1 << j)
for k := 0; k < n; k++ {
if ((pi >> k) & 1) == 1 {
v := dp[pi][k] + g[k][j]
if v > dp[i][j] {
dp[i][j] = v
p[i][j] = k
}
}
}
}
}
}
j := 0
for i := 0; i < n; i++ {
if dp[(1<<n)-1][i] > dp[(1<<n)-1][j] {
j = i
}
}
arr := []int{j}
vis := make([]bool, n)
vis[j] = true
for i := (1 << n) - 1; p[i][j] != -1; {
k := i
i ^= (1 << j)
j = p[k][j]
arr = append(arr, j)
vis[j] = true
}
for i := 0; i < n; i++ {
if !vis[i] {
arr = append(arr, i)
}
}
ans := &strings.Builder{}
ans.WriteString(words[arr[n-1]])
for i := n - 2; i >= 0; i-- {
k := g[arr[i+1]][arr[i]]
ans.WriteString(words[arr[i]][k:])
}
return ans.String()
}
|
class Solution {
public String shortestSuperstring(String[] words) {
int n = words.length;
int[][] g = new int[n][n];
for (int i = 0; i < n; ++i) {
String a = words[i];
for (int j = 0; j < n; ++j) {
String b = words[j];
if (i != j) {
for (int k = Math.min(a.length(), b.length()); k > 0; --k) {
if (a.substring(a.length() - k).equals(b.substring(0, k))) {
g[i][j] = k;
break;
}
}
}
}
}
int[][] dp = new int[1 << n][n];
int[][] p = new int[1 << n][n];
for (int i = 0; i < 1 << n; ++i) {
Arrays.fill(p[i], -1);
for (int j = 0; j < n; ++j) {
if (((i >> j) & 1) == 1) {
int pi = i ^ (1 << j);
for (int k = 0; k < n; ++k) {
if (((pi >> k) & 1) == 1) {
int v = dp[pi][k] + g[k][j];
if (v > dp[i][j]) {
dp[i][j] = v;
p[i][j] = k;
}
}
}
}
}
}
int j = 0;
for (int i = 0; i < n; ++i) {
if (dp[(1 << n) - 1][i] > dp[(1 << n) - 1][j]) {
j = i;
}
}
List<Integer> arr = new ArrayList<>();
arr.add(j);
for (int i = (1 << n) - 1; p[i][j] != -1;) {
int k = i;
i ^= (1 << j);
j = p[k][j];
arr.add(j);
}
Set<Integer> vis = new HashSet<>(arr);
for (int i = 0; i < n; ++i) {
if (!vis.contains(i)) {
arr.add(i);
}
}
Collections.reverse(arr);
StringBuilder ans = new StringBuilder(words[arr.get(0)]);
for (int i = 1; i < n; ++i) {
int k = g[arr.get(i - 1)][arr.get(i)];
ans.append(words[arr.get(i)].substring(k));
}
return ans.toString();
}
}
| null | null | null | null | null | null |
class Solution:
def shortestSuperstring(self, words: List[str]) -> str:
n = len(words)
g = [[0] * n for _ in range(n)]
for i, a in enumerate(words):
for j, b in enumerate(words):
if i != j:
for k in range(min(len(a), len(b)), 0, -1):
if a[-k:] == b[:k]:
g[i][j] = k
break
dp = [[0] * n for _ in range(1 << n)]
p = [[-1] * n for _ in range(1 << n)]
for i in range(1 << n):
for j in range(n):
if (i >> j) & 1:
pi = i ^ (1 << j)
for k in range(n):
if (pi >> k) & 1:
v = dp[pi][k] + g[k][j]
if v > dp[i][j]:
dp[i][j] = v
p[i][j] = k
j = 0
for i in range(n):
if dp[-1][i] > dp[-1][j]:
j = i
arr = [j]
i = (1 << n) - 1
while p[i][j] != -1:
i, j = i ^ (1 << j), p[i][j]
arr.append(j)
arr = arr[::-1]
vis = set(arr)
arr.extend([j for j in range(n) if j not in vis])
ans = [words[arr[0]]] + [words[j][g[i][j] :] for i, j in pairwise(arr)]
return ''.join(ans)
| null | null | null | null | null | null |
Minimum Array Sum
|
You are given an integer array
nums
and three integers
k
,
op1
, and
op2
.
You can perform the following operations on
nums
:
Operation 1
: Choose an index
i
and divide
nums[i]
by 2,
rounding up
to the nearest whole number. You can perform this operation at most
op1
times, and not more than
once
per index.
Operation 2
: Choose an index
i
and subtract
k
from
nums[i]
, but only if
nums[i]
is greater than or equal to
k
. You can perform this operation at most
op2
times, and not more than
once
per index.
Note:
Both operations can be applied to the same index, but at most once each.
Return the
minimum
possible
sum
of all elements in
nums
after performing any number of operations.
Example 1:
Input:
nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1
Output:
23
Explanation:
Apply Operation 2 to
nums[1] = 8
, making
nums[1] = 5
.
Apply Operation 1 to
nums[3] = 19
, making
nums[3] = 10
.
The resulting array becomes
[2, 5, 3, 10, 3]
, which has the minimum possible sum of 23 after applying the operations.
Example 2:
Input:
nums = [2,4,3], k = 3, op1 = 2, op2 = 1
Output:
3
Explanation:
Apply Operation 1 to
nums[0] = 2
, making
nums[0] = 1
.
Apply Operation 1 to
nums[1] = 4
, making
nums[1] = 2
.
Apply Operation 2 to
nums[2] = 3
, making
nums[2] = 0
.
The resulting array becomes
[1, 2, 0]
, which has the minimum possible sum of 3 after applying the operations.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 10
5
0 <= k <= 10
5
0 <= op1, op2 <= nums.length
| null | null |
class Solution {
public:
int minArraySum(vector<int>& nums, int d, int op1, int op2) {
int n = nums.size();
int f[n + 1][op1 + 1][op2 + 1];
memset(f, 0x3f, sizeof f);
f[0][0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums[i - 1];
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
f[i][j][k] = f[i - 1][j][k] + x;
if (j > 0) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2);
}
if (k > 0 && x >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
int y = (x + 1) / 2;
if (y >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2);
}
}
}
}
}
int ans = INT_MAX;
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
ans = min(ans, f[n][j][k]);
}
}
return ans;
}
};
| null | null |
func minArraySum(nums []int, d int, op1 int, op2 int) int {
n := len(nums)
const inf = int(1e9)
f := make([][][]int, n+1)
for i := range f {
f[i] = make([][]int, op1+1)
for j := range f[i] {
f[i][j] = make([]int, op2+1)
for k := range f[i][j] {
f[i][j][k] = inf
}
}
}
f[0][0][0] = 0
for i := 1; i <= n; i++ {
x := nums[i-1]
for j := 0; j <= op1; j++ {
for k := 0; k <= op2; k++ {
f[i][j][k] = f[i-1][j][k] + x
if j > 0 {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k]+(x+1)/2)
}
if k > 0 && x >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j][k-1]+(x-d))
}
if j > 0 && k > 0 {
y := (x + 1) / 2
if y >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(y-d))
}
if x >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(x-d+1)/2)
}
}
}
}
}
ans := inf
for j := 0; j <= op1; j++ {
for k := 0; k <= op2; k++ {
ans = min(ans, f[n][j][k])
}
}
return ans
}
|
class Solution {
public int minArraySum(int[] nums, int d, int op1, int op2) {
int n = nums.length;
int[][][] f = new int[n + 1][op1 + 1][op2 + 1];
final int inf = 1 << 29;
for (var g : f) {
for (var h : g) {
Arrays.fill(h, inf);
}
}
f[0][0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums[i - 1];
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
f[i][j][k] = f[i - 1][j][k] + x;
if (j > 0) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2);
}
if (k > 0 && x >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
int y = (x + 1) / 2;
if (y >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k]
= Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2);
}
}
}
}
}
int ans = inf;
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
ans = Math.min(ans, f[n][j][k]);
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minArraySum(self, nums: List[int], d: int, op1: int, op2: int) -> int:
n = len(nums)
f = [[[inf] * (op2 + 1) for _ in range(op1 + 1)] for _ in range(n + 1)]
f[0][0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(op1 + 1):
for k in range(op2 + 1):
f[i][j][k] = f[i - 1][j][k] + x
if j > 0:
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) // 2)
if k > 0 and x >= d:
f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d))
if j > 0 and k > 0:
y = (x + 1) // 2
if y >= d:
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + y - d)
if x >= d:
f[i][j][k] = min(
f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) // 2
)
ans = inf
for j in range(op1 + 1):
for k in range(op2 + 1):
ans = min(ans, f[n][j][k])
return ans
| null | null | null | null | null |
function minArraySum(nums: number[], d: number, op1: number, op2: number): number {
const n = nums.length;
const inf = Number.MAX_SAFE_INTEGER;
const f: number[][][] = Array.from({ length: n + 1 }, () =>
Array.from({ length: op1 + 1 }, () => Array(op2 + 1).fill(inf)),
);
f[0][0][0] = 0;
for (let i = 1; i <= n; i++) {
const x = nums[i - 1];
for (let j = 0; j <= op1; j++) {
for (let k = 0; k <= op2; k++) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + x);
if (j > 0) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + Math.floor((x + 1) / 2));
}
if (k > 0 && x >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
const y = Math.floor((x + 1) / 2);
if (y >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k] = Math.min(
f[i][j][k],
f[i - 1][j - 1][k - 1] + Math.floor((x - d + 1) / 2),
);
}
}
}
}
}
let ans = inf;
for (let j = 0; j <= op1; j++) {
for (let l = 0; l <= op2; l++) {
ans = Math.min(ans, f[n][j][l]);
}
}
return ans;
}
|
Count Number of Bad Pairs
|
You are given a
0-indexed
integer array
nums
. A pair of indices
(i, j)
is a
bad pair
if
i < j
and
j - i != nums[j] - nums[i]
.
Return
the total number of
bad pairs
in
nums
.
Example 1:
Input:
nums = [4,1,3,3]
Output:
5
Explanation:
The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.
Example 2:
Input:
nums = [1,2,3,4,5]
Output:
0
Explanation:
There are no bad pairs.
Constraints:
1 <= nums.length <= 10
5
1 <= nums[i] <= 10
9
| null | null |
class Solution {
public:
long long countBadPairs(vector<int>& nums) {
unordered_map<int, int> cnt;
long long ans = 0;
for (int i = 0; i < nums.size(); ++i) {
int x = i - nums[i];
ans += i - cnt[x]++;
}
return ans;
}
};
| null | null |
func countBadPairs(nums []int) (ans int64) {
cnt := map[int]int{}
for i, x := range nums {
x = i - x
ans += int64(i - cnt[x])
cnt[x]++
}
return
}
|
class Solution {
public long countBadPairs(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
long ans = 0;
for (int i = 0; i < nums.length; ++i) {
int x = i - nums[i];
ans += i - cnt.merge(x, 1, Integer::sum) + 1;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
cnt = Counter()
ans = 0
for i, x in enumerate(nums):
ans += i - cnt[i - x]
cnt[i - x] += 1
return ans
| null |
use std::collections::HashMap;
impl Solution {
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
let mut cnt: HashMap<i32, i64> = HashMap::new();
let mut ans: i64 = 0;
for (i, &num) in nums.iter().enumerate() {
let x = i as i32 - num;
let count = *cnt.get(&x).unwrap_or(&0);
ans += i as i64 - count;
*cnt.entry(x).or_insert(0) += 1;
}
ans
}
}
| null | null | null |
function countBadPairs(nums: number[]): number {
const cnt = new Map<number, number>();
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
const x = i - nums[i];
ans += i - (cnt.get(x) ?? 0);
cnt.set(x, (cnt.get(x) ?? 0) + 1);
}
return ans;
}
|
Minimum Division Operations to Make Array Non Decreasing
|
You are given an integer array
nums
.
Any
positive
divisor of a natural number
x
that is
strictly less
than
x
is called a
proper divisor
of
x
. For example, 2 is a
proper divisor
of 4, while 6 is not a
proper divisor
of 6.
You are allowed to perform an
operation
any number of times on
nums
, where in each
operation
you select any
one
element from
nums
and divide it by its
greatest
proper divisor
.
Return the
minimum
number of
operations
required to make the array
non-decreasing
.
If it is
not
possible to make the array
non-decreasing
using any number of operations, return
-1
.
Example 1:
Input:
nums = [25,7]
Output:
1
Explanation:
Using a single operation, 25 gets divided by 5 and
nums
becomes
[5, 7]
.
Example 2:
Input:
nums = [7,7,6]
Output:
-1
Example 3:
Input:
nums = [1,1,1,1]
Output:
0
Constraints:
1 <= nums.length <= 10
5
1 <= nums[i] <= 10
6
| null | null |
const int MX = 1e6;
int LPF[MX + 1];
auto init = [] {
for (int i = 2; i <= MX; i++) {
if (LPF[i] == 0) {
for (int j = i; j <= MX; j += i) {
if (LPF[j] == 0) {
LPF[j] = i;
}
}
}
}
return 0;
}();
class Solution {
public:
int minOperations(vector<int>& nums) {
int ans = 0;
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] > nums[i + 1]) {
nums[i] = LPF[nums[i]];
if (nums[i] > nums[i + 1]) {
return -1;
}
ans++;
}
}
return ans;
}
};
| null | null |
const mx int = 1e6
var lpf = [mx + 1]int{}
func init() {
for i := 2; i <= mx; i++ {
if lpf[i] == 0 {
for j := i; j <= mx; j += i {
if lpf[j] == 0 {
lpf[j] = i
}
}
}
}
}
func minOperations(nums []int) (ans int) {
for i := len(nums) - 2; i >= 0; i-- {
if nums[i] > nums[i+1] {
nums[i] = lpf[nums[i]]
if nums[i] > nums[i+1] {
return -1
}
ans++
}
}
return
}
|
class Solution {
private static final int MX = (int) 1e6 + 1;
private static final int[] LPF = new int[MX + 1];
static {
for (int i = 2; i <= MX; ++i) {
for (int j = i; j <= MX; j += i) {
if (LPF[j] == 0) {
LPF[j] = i;
}
}
}
}
public int minOperations(int[] nums) {
int ans = 0;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] > nums[i + 1]) {
nums[i] = LPF[nums[i]];
if (nums[i] > nums[i + 1]) {
return -1;
}
ans++;
}
}
return ans;
}
}
| null | null | null | null | null | null |
mx = 10**6 + 1
lpf = [0] * (mx + 1)
for i in range(2, mx + 1):
if lpf[i] == 0:
for j in range(i, mx + 1, i):
if lpf[j] == 0:
lpf[j] = i
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
for i in range(len(nums) - 2, -1, -1):
if nums[i] > nums[i + 1]:
nums[i] = lpf[nums[i]]
if nums[i] > nums[i + 1]:
return -1
ans += 1
return ans
| null | null | null | null | null |
const mx = 10 ** 6;
const lpf = Array(mx + 1).fill(0);
for (let i = 2; i <= mx; ++i) {
for (let j = i; j <= mx; j += i) {
if (lpf[j] === 0) {
lpf[j] = i;
}
}
}
function minOperations(nums: number[]): number {
let ans = 0;
for (let i = nums.length - 2; ~i; --i) {
if (nums[i] > nums[i + 1]) {
nums[i] = lpf[nums[i]];
if (nums[i] > nums[i + 1]) {
return -1;
}
++ans;
}
}
return ans;
}
|
Check if There is a Valid Path in a Grid
|
You are given an
m x n
grid
. Each cell of
grid
represents a street. The street of
grid[i][j]
can be:
1
which means a street connecting the left cell and the right cell.
2
which means a street connecting the upper cell and the lower cell.
3
which means a street connecting the left cell and the lower cell.
4
which means a street connecting the right cell and the lower cell.
5
which means a street connecting the left cell and the upper cell.
6
which means a street connecting the right cell and the upper cell.
You will initially start at the street of the upper-left cell
(0, 0)
. A valid path in the grid is a path that starts from the upper left cell
(0, 0)
and ends at the bottom-right cell
(m - 1, n - 1)
.
The path should only follow the streets
.
Notice
that you are
not allowed
to change any street.
Return
true
if there is a valid path in the grid or
false
otherwise
.
Example 1:
Input:
grid = [[2,4,3],[6,5,2]]
Output:
true
Explanation:
As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
Example 2:
Input:
grid = [[1,2,1],[1,2,1]]
Output:
false
Explanation:
As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
Example 3:
Input:
grid = [[1,1,2]]
Output:
false
Explanation:
You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6
| null | null |
class Solution {
public:
vector<int> p;
bool hasValidPath(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
p.resize(m * n);
for (int i = 0; i < p.size(); ++i) p[i] = i;
auto left = [&](int i, int j) {
if (j > 0 && (grid[i][j - 1] == 1 || grid[i][j - 1] == 4 || grid[i][j - 1] == 6)) {
p[find(i * n + j)] = find(i * n + j - 1);
}
};
auto right = [&](int i, int j) {
if (j < n - 1 && (grid[i][j + 1] == 1 || grid[i][j + 1] == 3 || grid[i][j + 1] == 5)) {
p[find(i * n + j)] = find(i * n + j + 1);
}
};
auto up = [&](int i, int j) {
if (i > 0 && (grid[i - 1][j] == 2 || grid[i - 1][j] == 3 || grid[i - 1][j] == 4)) {
p[find(i * n + j)] = find((i - 1) * n + j);
}
};
auto down = [&](int i, int j) {
if (i < m - 1 && (grid[i + 1][j] == 2 || grid[i + 1][j] == 5 || grid[i + 1][j] == 6)) {
p[find(i * n + j)] = find((i + 1) * n + j);
}
};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int e = grid[i][j];
if (e == 1) {
left(i, j);
right(i, j);
} else if (e == 2) {
up(i, j);
down(i, j);
} else if (e == 3) {
left(i, j);
down(i, j);
} else if (e == 4) {
right(i, j);
down(i, j);
} else if (e == 5) {
left(i, j);
up(i, j);
} else {
right(i, j);
up(i, j);
}
}
}
return find(0) == find(m * n - 1);
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
};
| null | null |
func hasValidPath(grid [][]int) bool {
m, n := len(grid), len(grid[0])
p := make([]int, m*n)
for i := range p {
p[i] = i
}
var find func(x int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
left := func(i, j int) {
if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) {
p[find(i*n+j)] = find(i*n + j - 1)
}
}
right := func(i, j int) {
if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) {
p[find(i*n+j)] = find(i*n + j + 1)
}
}
up := func(i, j int) {
if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) {
p[find(i*n+j)] = find((i-1)*n + j)
}
}
down := func(i, j int) {
if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) {
p[find(i*n+j)] = find((i+1)*n + j)
}
}
for i, row := range grid {
for j, e := range row {
if e == 1 {
left(i, j)
right(i, j)
} else if e == 2 {
up(i, j)
down(i, j)
} else if e == 3 {
left(i, j)
down(i, j)
} else if e == 4 {
right(i, j)
down(i, j)
} else if e == 5 {
left(i, j)
up(i, j)
} else {
right(i, j)
up(i, j)
}
}
}
return find(0) == find(m*n-1)
}
|
class Solution {
private int[] p;
private int[][] grid;
private int m;
private int n;
public boolean hasValidPath(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
p = new int[m * n];
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int e = grid[i][j];
if (e == 1) {
left(i, j);
right(i, j);
} else if (e == 2) {
up(i, j);
down(i, j);
} else if (e == 3) {
left(i, j);
down(i, j);
} else if (e == 4) {
right(i, j);
down(i, j);
} else if (e == 5) {
left(i, j);
up(i, j);
} else {
right(i, j);
up(i, j);
}
}
}
return find(0) == find(m * n - 1);
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private void left(int i, int j) {
if (j > 0 && (grid[i][j - 1] == 1 || grid[i][j - 1] == 4 || grid[i][j - 1] == 6)) {
p[find(i * n + j)] = find(i * n + j - 1);
}
}
private void right(int i, int j) {
if (j < n - 1 && (grid[i][j + 1] == 1 || grid[i][j + 1] == 3 || grid[i][j + 1] == 5)) {
p[find(i * n + j)] = find(i * n + j + 1);
}
}
private void up(int i, int j) {
if (i > 0 && (grid[i - 1][j] == 2 || grid[i - 1][j] == 3 || grid[i - 1][j] == 4)) {
p[find(i * n + j)] = find((i - 1) * n + j);
}
}
private void down(int i, int j) {
if (i < m - 1 && (grid[i + 1][j] == 2 || grid[i + 1][j] == 5 || grid[i + 1][j] == 6)) {
p[find(i * n + j)] = find((i + 1) * n + j);
}
}
}
| null | null | null | null | null | null |
class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
p = list(range(m * n))
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def left(i, j):
if j > 0 and grid[i][j - 1] in (1, 4, 6):
p[find(i * n + j)] = find(i * n + j - 1)
def right(i, j):
if j < n - 1 and grid[i][j + 1] in (1, 3, 5):
p[find(i * n + j)] = find(i * n + j + 1)
def up(i, j):
if i > 0 and grid[i - 1][j] in (2, 3, 4):
p[find(i * n + j)] = find((i - 1) * n + j)
def down(i, j):
if i < m - 1 and grid[i + 1][j] in (2, 5, 6):
p[find(i * n + j)] = find((i + 1) * n + j)
for i in range(m):
for j in range(n):
e = grid[i][j]
if e == 1:
left(i, j)
right(i, j)
elif e == 2:
up(i, j)
down(i, j)
elif e == 3:
left(i, j)
down(i, j)
elif e == 4:
right(i, j)
down(i, j)
elif e == 5:
left(i, j)
up(i, j)
else:
right(i, j)
up(i, j)
return find(0) == find(m * n - 1)
| null | null | null | null | null | null |
Winner of the Linked List Game 🔒
|
You are given the
head
of a linked list of
even
length containing integers.
Each
odd-indexed
node contains an odd integer and each
even-indexed
node contains an even integer.
We call each even-indexed node and its next node a
pair
, e.g., the nodes with indices
0
and
1
are a pair, the nodes with indices
2
and
3
are a pair, and so on.
For every
pair
, we compare the values of the nodes in the pair:
If the odd-indexed node is higher, the
"Odd"
team gets a point.
If the even-indexed node is higher, the
"Even"
team gets a point.
Return
the name of the team with the
higher
points, if the points are equal, return
"Tie"
.
Example 1:
Input:
head = [2,1]
Output:
"Even"
Explanation:
There is only one pair in this linked list and that is
(2,1)
. Since
2 > 1
, the Even team gets the point.
Hence, the answer would be
"Even"
.
Example 2:
Input:
head = [2,5,4,7,20,5]
Output:
"Odd"
Explanation:
There are
3
pairs in this linked list. Let's investigate each pair individually:
(2,5)
-> Since
2 < 5
, The Odd team gets the point.
(4,7)
-> Since
4 < 7
, The Odd team gets the point.
(20,5)
-> Since
20 > 5
, The Even team gets the point.
The Odd team earned
2
points while the Even team got
1
point and the Odd team has the higher points.
Hence, the answer would be
"Odd"
.
Example 3:
Input:
head = [4,5,2,1]
Output:
"Tie"
Explanation:
There are
2
pairs in this linked list. Let's investigate each pair individually:
(4,5)
-> Since
4 < 5
, the Odd team gets the point.
(2,1)
-> Since
2 > 1
, the Even team gets the point.
Both teams earned
1
point.
Hence, the answer would be
"Tie"
.
Constraints:
The number of nodes in the list is in the range
[2, 100]
.
The number of nodes in the list is even.
1 <= Node.val <= 100
The value of each odd-indexed node is odd.
The value of each even-indexed node is even.
| null | 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:
string gameResult(ListNode* head) {
int odd = 0, even = 0;
for (; head != nullptr; head = head->next->next) {
int a = head->val;
int b = head->next->val;
odd += a < b;
even += a > b;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
};
| null | null |
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func gameResult(head *ListNode) string {
var odd, even int
for ; head != nil; head = head.Next.Next {
a, b := head.Val, head.Next.Val
if a < b {
odd++
}
if a > b {
even++
}
}
if odd > even {
return "Odd"
}
if odd < even {
return "Even"
}
return "Tie"
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public String gameResult(ListNode head) {
int odd = 0, even = 0;
for (; head != null; head = head.next.next) {
int a = head.val;
int b = head.next.val;
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
}
| 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 gameResult(self, head: Optional[ListNode]) -> str:
odd = even = 0
while head:
a = head.val
b = head.next.val
odd += a < b
even += a > b
head = head.next.next
if odd > even:
return "Odd"
if odd < even:
return "Even"
return "Tie"
| null | null | 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 gameResult(head: ListNode | null): string {
let [odd, even] = [0, 0];
for (; head; head = head.next.next) {
const [a, b] = [head.val, head.next.val];
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return 'Odd';
}
if (odd < even) {
return 'Even';
}
return 'Tie';
}
|
Find the Most Competitive Subsequence
|
Given an integer array
nums
and a positive integer
k
, return
the most
competitive
subsequence of
nums
of size
k
.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence
a
is more
competitive
than a subsequence
b
(of the same length) if in the first position where
a
and
b
differ, subsequence
a
has a number
less
than the corresponding number in
b
. For example,
[1,3,4]
is more competitive than
[1,3,5]
because the first position they differ is at the final number, and
4
is less than
5
.
Example 1:
Input:
nums = [3,5,2,6], k = 2
Output:
[2,6]
Explanation:
Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
Example 2:
Input:
nums = [2,4,3,3,5,4,9,6], k = 4
Output:
[2,3,3,4]
Constraints:
1 <= nums.length <= 10
5
0 <= nums[i] <= 10
9
1 <= k <= nums.length
| null | null |
class Solution {
public:
vector<int> mostCompetitive(vector<int>& nums, int k) {
vector<int> stk;
int n = nums.size();
for (int i = 0; i < n; ++i) {
while (stk.size() && stk.back() > nums[i] && stk.size() + n - i > k) {
stk.pop_back();
}
if (stk.size() < k) {
stk.push_back(nums[i]);
}
}
return stk;
}
};
| null | null |
func mostCompetitive(nums []int, k int) []int {
stk := []int{}
n := len(nums)
for i, v := range nums {
for len(stk) > 0 && stk[len(stk)-1] > v && len(stk)+n-i > k {
stk = stk[:len(stk)-1]
}
if len(stk) < k {
stk = append(stk, v)
}
}
return stk
}
|
class Solution {
public int[] mostCompetitive(int[] nums, int k) {
Deque<Integer> stk = new ArrayDeque<>();
int n = nums.length;
for (int i = 0; i < nums.length; ++i) {
while (!stk.isEmpty() && stk.peek() > nums[i] && stk.size() + n - i > k) {
stk.pop();
}
if (stk.size() < k) {
stk.push(nums[i]);
}
}
int[] ans = new int[stk.size()];
for (int i = ans.length - 1; i >= 0; --i) {
ans[i] = stk.pop();
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def mostCompetitive(self, nums: List[int], k: int) -> List[int]:
stk = []
n = len(nums)
for i, v in enumerate(nums):
while stk and stk[-1] > v and len(stk) + n - i > k:
stk.pop()
if len(stk) < k:
stk.append(v)
return stk
| null | null | null | null | null |
function mostCompetitive(nums: number[], k: number): number[] {
const stk: number[] = [];
const n = nums.length;
for (let i = 0; i < n; ++i) {
while (stk.length && stk.at(-1)! > nums[i] && stk.length + n - i > k) {
stk.pop();
}
if (stk.length < k) {
stk.push(nums[i]);
}
}
return stk;
}
|
Get Maximum in Generated Array
|
You are given an integer
n
. A
0-indexed
integer array
nums
of length
n + 1
is generated in the following way:
nums[0] = 0
nums[1] = 1
nums[2 * i] = nums[i]
when
2 <= 2 * i <= n
nums[2 * i + 1] = nums[i] + nums[i + 1]
when
2 <= 2 * i + 1 <= n
Return
the
maximum
integer in the array
nums
.
Example 1:
Input:
n = 7
Output:
3
Explanation:
According to the given rules:
nums[0] = 0
nums[1] = 1
nums[(1 * 2) = 2] = nums[1] = 1
nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
nums[(2 * 2) = 4] = nums[2] = 1
nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
nums[(3 * 2) = 6] = nums[3] = 2
nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.
Example 2:
Input:
n = 2
Output:
1
Explanation:
According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.
Example 3:
Input:
n = 3
Output:
2
Explanation:
According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.
Constraints:
0 <= n <= 100
| null | null |
class Solution {
public:
int getMaximumGenerated(int n) {
if (n < 2) {
return n;
}
int nums[n + 1];
nums[0] = 0;
nums[1] = 1;
for (int i = 2; i <= n; ++i) {
nums[i] = i % 2 == 0 ? nums[i >> 1] : nums[i >> 1] + nums[(i >> 1) + 1];
}
return *max_element(nums, nums + n + 1);
}
};
| null | null |
func getMaximumGenerated(n int) int {
if n < 2 {
return n
}
nums := make([]int, n+1)
nums[1] = 1
for i := 2; i <= n; i++ {
if i%2 == 0 {
nums[i] = nums[i/2]
} else {
nums[i] = nums[i/2] + nums[i/2+1]
}
}
return slices.Max(nums)
}
|
class Solution {
public int getMaximumGenerated(int n) {
if (n < 2) {
return n;
}
int[] nums = new int[n + 1];
nums[1] = 1;
for (int i = 2; i <= n; ++i) {
nums[i] = i % 2 == 0 ? nums[i >> 1] : nums[i >> 1] + nums[(i >> 1) + 1];
}
return Arrays.stream(nums).max().getAsInt();
}
}
| null | null | null | null | null | null |
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n < 2:
return n
nums = [0] * (n + 1)
nums[1] = 1
for i in range(2, n + 1):
nums[i] = nums[i >> 1] if i % 2 == 0 else nums[i >> 1] + nums[(i >> 1) + 1]
return max(nums)
| null | null | null | null | null |
function getMaximumGenerated(n: number): number {
if (n === 0) {
return 0;
}
const nums: number[] = new Array(n + 1).fill(0);
nums[1] = 1;
for (let i = 2; i < n + 1; ++i) {
nums[i] = i % 2 === 0 ? nums[i >> 1] : nums[i >> 1] + nums[(i >> 1) + 1];
}
return Math.max(...nums);
}
|
Binary Tree Coloring Game
|
Two players play a turn based game on a binary tree. We are given the
root
of this binary tree, and the number of nodes
n
in the tree.
n
is odd, and each node has a distinct value from
1
to
n
.
Initially, the first player names a value
x
with
1 <= x <= n
, and the second player names a value
y
with
1 <= y <= n
and
y != x
. The first player colors the node with value
x
red, and the second player colors the node with value
y
blue.
Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an
uncolored
neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
You are the second player. If it is possible to choose such a
y
to ensure you win the game, return
true
. If it is not possible, return
false
.
Example 1:
Input:
root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output:
true
Explanation:
The second player can choose the node with value 2.
Example 2:
Input:
root = [1,2,3], n = 3, x = 1
Output:
false
Constraints:
The number of nodes in the tree is
n
.
1 <= x <= n <= 100
n
is odd.
1 <= Node.val <= n
All the values of the tree are
unique
.
| null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
auto node = dfs(root, x);
int l = count(node->left), r = count(node->right);
return max({l, r, n - l - r - 1}) > n / 2;
}
TreeNode* dfs(TreeNode* root, int x) {
if (!root || root->val == x) {
return root;
}
auto node = dfs(root->left, x);
return node ? node : dfs(root->right, x);
}
int count(TreeNode* root) {
if (!root) {
return 0;
}
return 1 + count(root->left) + count(root->right);
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func btreeGameWinningMove(root *TreeNode, n int, x int) bool {
var dfs func(*TreeNode) *TreeNode
dfs = func(root *TreeNode) *TreeNode {
if root == nil || root.Val == x {
return root
}
node := dfs(root.Left)
if node != nil {
return node
}
return dfs(root.Right)
}
var count func(*TreeNode) int
count = func(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + count(root.Left) + count(root.Right)
}
node := dfs(root)
l, r := count(node.Left), count(node.Right)
return max(max(l, r), n-l-r-1) > n/2
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
TreeNode node = dfs(root, x);
int l = count(node.left);
int r = count(node.right);
return Math.max(Math.max(l, r), n - l - r - 1) > n / 2;
}
private TreeNode dfs(TreeNode root, int x) {
if (root == null || root.val == x) {
return root;
}
TreeNode node = dfs(root.left, x);
return node == null ? dfs(root.right, x) : node;
}
private int count(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + count(root.left) + count(root.right);
}
}
|
/**
* 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} n
* @param {number} x
* @return {boolean}
*/
var btreeGameWinningMove = function (root, n, x) {
const dfs = root => {
if (!root || root.val === x) {
return root;
}
return dfs(root.left) || dfs(root.right);
};
const count = root => {
if (!root) {
return 0;
}
return 1 + count(root.left) + count(root.right);
};
const node = dfs(root);
const l = count(node.left);
const r = count(node.right);
return Math.max(l, r, n - l - r - 1) > n / 2;
};
| 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 btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
def dfs(root):
if root is None or root.val == x:
return root
return dfs(root.left) or dfs(root.right)
def count(root):
if root is None:
return 0
return 1 + count(root.left) + count(root.right)
node = dfs(root)
l, r = count(node.left), count(node.right)
return max(l, r, n - l - r - 1) > n // 2
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): boolean {
const dfs = (root: TreeNode | null): TreeNode | null => {
if (!root || root.val === x) {
return root;
}
return dfs(root.left) || dfs(root.right);
};
const count = (root: TreeNode | null): number => {
if (!root) {
return 0;
}
return 1 + count(root.left) + count(root.right);
};
const node = dfs(root);
const l = count(node.left);
const r = count(node.right);
return Math.max(l, r, n - l - r - 1) > n / 2;
}
|
Count Items Matching a Rule
|
You are given an array
items
, where each
items[i] = [type
i
, color
i
, name
i
]
describes the type, color, and name of the
i
th
item. You are also given a rule represented by two strings,
ruleKey
and
ruleValue
.
The
i
th
item is said to match the rule if
one
of the following is true:
ruleKey == "type"
and
ruleValue == type
i
.
ruleKey == "color"
and
ruleValue == color
i
.
ruleKey == "name"
and
ruleValue == name
i
.
Return
the number of items that match the given rule
.
Example 1:
Input:
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output:
1
Explanation:
There is only one item matching the given rule, which is ["computer","silver","lenovo"].
Example 2:
Input:
items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output:
2
Explanation:
There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.
Constraints:
1 <= items.length <= 10
4
1 <= type
i
.length, color
i
.length, name
i
.length, ruleValue.length <= 10
ruleKey
is equal to either
"type"
,
"color"
, or
"name"
.
All strings consist only of lowercase letters.
|
int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) {
int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1
: 2;
int res = 0;
for (int i = 0; i < itemsSize; i++) {
if (strcmp(items[i][k], ruleValue) == 0) {
res++;
}
}
return res;
}
| null |
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int i = ruleKey[0] == 't' ? 0 : (ruleKey[0] == 'c' ? 1 : 2);
return count_if(items.begin(), items.end(), [&](auto& v) { return v[i] == ruleValue; });
}
};
| null | null |
func countMatches(items [][]string, ruleKey string, ruleValue string) (ans int) {
i := map[byte]int{'t': 0, 'c': 1, 'n': 2}[ruleKey[0]]
for _, v := range items {
if v[i] == ruleValue {
ans++
}
}
return
}
|
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int i = ruleKey.charAt(0) == 't' ? 0 : (ruleKey.charAt(0) == 'c' ? 1 : 2);
int ans = 0;
for (var v : items) {
if (v.get(i).equals(ruleValue)) {
++ans;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
i = 0 if ruleKey[0] == 't' else (1 if ruleKey[0] == 'c' else 2)
return sum(v[i] == ruleValue for v in items)
| null |
impl Solution {
pub fn count_matches(items: Vec<Vec<String>>, rule_key: String, rule_value: String) -> i32 {
let key = if rule_key == "type" {
0
} else if rule_key == "color" {
1
} else {
2
};
items.iter().filter(|v| v[key] == rule_value).count() as i32
}
}
| null | null | null |
function countMatches(items: string[][], ruleKey: string, ruleValue: string): number {
const key = ruleKey === 'type' ? 0 : ruleKey === 'color' ? 1 : 2;
return items.reduce((r, v) => r + (v[key] === ruleValue ? 1 : 0), 0);
}
|
Determine the Winner of a Bowling Game
|
You are given two
0-indexed
integer arrays
player1
and
player2
, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.
The bowling game consists of
n
turns, and the number of pins in each turn is exactly 10.
Assume a player hits
x
i
pins in the i
th
turn. The value of the i
th
turn for the player is:
2x
i
if the player hits 10 pins
in either (i - 1)
th
or (i - 2)
th
turn
.
Otherwise, it is
x
i
.
The
score
of the player is the sum of the values of their
n
turns.
Return
1 if the score of player 1 is more than the score of player 2,
2 if the score of player 2 is more than the score of player 1, and
0 in case of a draw.
Example 1:
Input:
player1 = [5,10,3,2], player2 = [6,5,7,3]
Output:
1
Explanation:
The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.
The score of player 2 is 6 + 5 + 7 + 3 = 21.
Example 2:
Input:
player1 = [3,5,7,6], player2 = [8,10,10,2]
Output:
2
Explanation:
The score of player 1 is 3 + 5 + 7 + 6 = 21.
The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.
Example 3:
Input:
player1 = [2,3], player2 = [4,1]
Output:
0
Explanation:
The score of player1 is 2 + 3 = 5.
The score of player2 is 4 + 1 = 5.
Example 4:
Input:
player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]
Output:
2
Explanation:
The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.
The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.
Constraints:
n == player1.length == player2.length
1 <= n <= 1000
0 <= player1[i], player2[i] <= 10
| null | null |
class Solution {
public:
int isWinner(vector<int>& player1, vector<int>& player2) {
auto f = [](vector<int>& arr) {
int s = 0;
for (int i = 0, n = arr.size(); i < n; ++i) {
int k = (i && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1;
s += k * arr[i];
}
return s;
};
int a = f(player1), b = f(player2);
return a > b ? 1 : (b > a ? 2 : 0);
}
};
| null | null |
func isWinner(player1 []int, player2 []int) int {
f := func(arr []int) int {
s := 0
for i, x := range arr {
k := 1
if (i > 0 && arr[i-1] == 10) || (i > 1 && arr[i-2] == 10) {
k = 2
}
s += k * x
}
return s
}
a, b := f(player1), f(player2)
if a > b {
return 1
}
if b > a {
return 2
}
return 0
}
|
class Solution {
public int isWinner(int[] player1, int[] player2) {
int a = f(player1), b = f(player2);
return a > b ? 1 : b > a ? 2 : 0;
}
private int f(int[] arr) {
int s = 0;
for (int i = 0; i < arr.length; ++i) {
int k = (i > 0 && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1;
s += k * arr[i];
}
return s;
}
}
| null | null | null | null | null | null |
class Solution:
def isWinner(self, player1: List[int], player2: List[int]) -> int:
def f(arr: List[int]) -> int:
s = 0
for i, x in enumerate(arr):
k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1
s += k * x
return s
a, b = f(player1), f(player2)
return 1 if a > b else (2 if b > a else 0)
| null |
impl Solution {
pub fn is_winner(player1: Vec<i32>, player2: Vec<i32>) -> i32 {
let f = |arr: &Vec<i32>| -> i32 {
let mut s = 0;
for i in 0..arr.len() {
let mut k = 1;
if (i > 0 && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) {
k = 2;
}
s += k * arr[i];
}
s
};
let a = f(&player1);
let b = f(&player2);
if a > b {
1
} else if a < b {
2
} else {
0
}
}
}
| null | null | null |
function isWinner(player1: number[], player2: number[]): number {
const f = (arr: number[]): number => {
let s = 0;
for (let i = 0; i < arr.length; ++i) {
s += arr[i];
if ((i && arr[i - 1] === 10) || (i > 1 && arr[i - 2] === 10)) {
s += arr[i];
}
}
return s;
};
const a = f(player1);
const b = f(player2);
return a > b ? 1 : a < b ? 2 : 0;
}
|
Buddy Strings
|
Given two strings
s
and
goal
, return
true
if you can swap two letters in
s
so the result is equal to
goal
, otherwise, return
false
.
Swapping letters is defined as taking two indices
i
and
j
(0-indexed) such that
i != j
and swapping the characters at
s[i]
and
s[j]
.
For example, swapping at indices
0
and
2
in
"abcd"
results in
"cbad"
.
Example 1:
Input:
s = "ab", goal = "ba"
Output:
true
Explanation:
You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input:
s = "ab", goal = "ab"
Output:
false
Explanation:
The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input:
s = "aa", goal = "aa"
Output:
true
Explanation:
You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 10
4
s
and
goal
consist of lowercase letters.
| null | null |
class Solution {
public:
bool buddyStrings(string s, string goal) {
int m = s.size(), n = goal.size();
if (m != n) return false;
int diff = 0;
vector<int> cnt1(26);
vector<int> cnt2(26);
for (int i = 0; i < n; ++i) {
++cnt1[s[i] - 'a'];
++cnt2[goal[i] - 'a'];
if (s[i] != goal[i]) ++diff;
}
bool f = false;
for (int i = 0; i < 26; ++i) {
if (cnt1[i] != cnt2[i]) return false;
if (cnt1[i] > 1) f = true;
}
return diff == 2 || (diff == 0 && f);
}
};
| null | null |
func buddyStrings(s string, goal string) bool {
m, n := len(s), len(goal)
if m != n {
return false
}
diff := 0
cnt1 := make([]int, 26)
cnt2 := make([]int, 26)
for i := 0; i < n; i++ {
cnt1[s[i]-'a']++
cnt2[goal[i]-'a']++
if s[i] != goal[i] {
diff++
}
}
f := false
for i := 0; i < 26; i++ {
if cnt1[i] != cnt2[i] {
return false
}
if cnt1[i] > 1 {
f = true
}
}
return diff == 2 || (diff == 0 && f)
}
|
class Solution {
public boolean buddyStrings(String s, String goal) {
int m = s.length(), n = goal.length();
if (m != n) {
return false;
}
int diff = 0;
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
for (int i = 0; i < n; ++i) {
int a = s.charAt(i), b = goal.charAt(i);
++cnt1[a - 'a'];
++cnt2[b - 'a'];
if (a != b) {
++diff;
}
}
boolean f = false;
for (int i = 0; i < 26; ++i) {
if (cnt1[i] != cnt2[i]) {
return false;
}
if (cnt1[i] > 1) {
f = true;
}
}
return diff == 2 || (diff == 0 && f);
}
}
| null | null | null | null | null | null |
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
m, n = len(s), len(goal)
if m != n:
return False
cnt1, cnt2 = Counter(s), Counter(goal)
if cnt1 != cnt2:
return False
diff = sum(s[i] != goal[i] for i in range(n))
return diff == 2 or (diff == 0 and any(v > 1 for v in cnt1.values()))
| null | null | null | null | null |
function buddyStrings(s: string, goal: string): boolean {
const m = s.length;
const n = goal.length;
if (m != n) {
return false;
}
const cnt1 = new Array(26).fill(0);
const cnt2 = new Array(26).fill(0);
let diff = 0;
for (let i = 0; i < n; ++i) {
cnt1[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
cnt2[goal.charCodeAt(i) - 'a'.charCodeAt(0)]++;
if (s[i] != goal[i]) {
++diff;
}
}
for (let i = 0; i < 26; ++i) {
if (cnt1[i] != cnt2[i]) {
return false;
}
}
return diff == 2 || (diff == 0 && cnt1.some(v => v > 1));
}
|
Amount of Time for Binary Tree to Be Infected
|
You are given the
root
of a binary tree with
unique
values, and an integer
start
. At minute
0
, an
infection
starts from the node with value
start
.
Each minute, a node becomes infected if:
The node is currently uninfected.
The node is adjacent to an infected node.
Return
the number of minutes needed for the entire tree to be infected.
Example 1:
Input:
root = [1,5,3,null,4,10,6,9,2], start = 3
Output:
4
Explanation:
The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.
Example 2:
Input:
root = [1], start = 1
Output:
0
Explanation:
At minute 0, the only node in the tree is infected so we return 0.
Constraints:
The number of nodes in the tree is in the range
[1, 10
5
]
.
1 <= Node.val <= 10
5
Each node has a
unique
value.
A node with a value of
start
exists in the tree.
| null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int amountOfTime(TreeNode* root, int start) {
unordered_map<int, vector<int>> g;
function<void(TreeNode*, TreeNode*)> dfs = [&](TreeNode* node, TreeNode* fa) {
if (!node) {
return;
}
if (fa) {
g[node->val].push_back(fa->val);
g[fa->val].push_back(node->val);
}
dfs(node->left, node);
dfs(node->right, node);
};
function<int(int, int)> dfs2 = [&](int node, int fa) -> int {
int ans = 0;
for (int nxt : g[node]) {
if (nxt != fa) {
ans = max(ans, 1 + dfs2(nxt, node));
}
}
return ans;
};
dfs(root, nullptr);
return dfs2(start, -1);
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func amountOfTime(root *TreeNode, start int) int {
g := map[int][]int{}
var dfs func(*TreeNode, *TreeNode)
dfs = func(node, fa *TreeNode) {
if node == nil {
return
}
if fa != nil {
g[node.Val] = append(g[node.Val], fa.Val)
g[fa.Val] = append(g[fa.Val], node.Val)
}
dfs(node.Left, node)
dfs(node.Right, node)
}
var dfs2 func(int, int) int
dfs2 = func(node, fa int) (ans int) {
for _, nxt := range g[node] {
if nxt != fa {
ans = max(ans, 1+dfs2(nxt, node))
}
}
return
}
dfs(root, nil)
return dfs2(start, -1)
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer, List<Integer>> g = new HashMap<>();
public int amountOfTime(TreeNode root, int start) {
dfs(root, null);
return dfs2(start, -1);
}
private void dfs(TreeNode node, TreeNode fa) {
if (node == null) {
return;
}
if (fa != null) {
g.computeIfAbsent(node.val, k -> new ArrayList<>()).add(fa.val);
g.computeIfAbsent(fa.val, k -> new ArrayList<>()).add(node.val);
}
dfs(node.left, node);
dfs(node.right, node);
}
private int dfs2(int node, int fa) {
int ans = 0;
for (int nxt : g.getOrDefault(node, List.of())) {
if (nxt != fa) {
ans = Math.max(ans, 1 + dfs2(nxt, node));
}
}
return ans;
}
}
| null | null | null | null | null | null |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
def dfs(node: Optional[TreeNode], fa: Optional[TreeNode]):
if node is None:
return
if fa:
g[node.val].append(fa.val)
g[fa.val].append(node.val)
dfs(node.left, node)
dfs(node.right, node)
def dfs2(node: int, fa: int) -> int:
ans = 0
for nxt in g[node]:
if nxt != fa:
ans = max(ans, 1 + dfs2(nxt, node))
return ans
g = defaultdict(list)
dfs(root, None)
return dfs2(start, -1)
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function amountOfTime(root: TreeNode | null, start: number): number {
const g: Map<number, number[]> = new Map();
const dfs = (node: TreeNode | null, fa: TreeNode | null) => {
if (!node) {
return;
}
if (fa) {
if (!g.has(node.val)) {
g.set(node.val, []);
}
g.get(node.val)!.push(fa.val);
if (!g.has(fa.val)) {
g.set(fa.val, []);
}
g.get(fa.val)!.push(node.val);
}
dfs(node.left, node);
dfs(node.right, node);
};
const dfs2 = (node: number, fa: number): number => {
let ans = 0;
for (const nxt of g.get(node) || []) {
if (nxt !== fa) {
ans = Math.max(ans, 1 + dfs2(nxt, node));
}
}
return ans;
};
dfs(root, null);
return dfs2(start, -1);
}
|
Longest Continuous Increasing Subsequence
|
Given an unsorted array of integers
nums
, return
the length of the longest
continuous increasing subsequence
(i.e. subarray)
. The subsequence must be
strictly
increasing.
A
continuous increasing subsequence
is defined by two indices
l
and
r
(
l < r
) such that it is
[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]
and for each
l <= i < r
,
nums[i] < nums[i + 1]
.
Example 1:
Input:
nums = [1,3,5,4,7]
Output:
3
Explanation:
The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
Input:
nums = [2,2,2,2,2]
Output:
1
Explanation:
The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
Constraints:
1 <= nums.length <= 10
4
-10
9
<= nums[i] <= 10
9
| null | null |
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int ans = 1;
int n = nums.size();
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && nums[j - 1] < nums[j]) {
++j;
}
ans = max(ans, j - i);
i = j;
}
return ans;
}
};
| null | null |
func findLengthOfLCIS(nums []int) int {
ans := 1
n := len(nums)
for i := 0; i < n; {
j := i + 1
for j < n && nums[j-1] < nums[j] {
j++
}
ans = max(ans, j-i)
i = j
}
return ans
}
|
class Solution {
public int findLengthOfLCIS(int[] nums) {
int ans = 1;
int n = nums.length;
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && nums[j - 1] < nums[j]) {
++j;
}
ans = Math.max(ans, j - i);
i = j;
}
return ans;
}
}
| null | null | null | null |
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function findLengthOfLCIS($nums) {
$ans = 1;
$n = count($nums);
$i = 0;
while ($i < $n) {
$j = $i + 1;
while ($j < $n && $nums[$j - 1] < $nums[$j]) {
$j++;
}
$ans = max($ans, $j - $i);
$i = $j;
}
return $ans;
}
}
| null |
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
ans, n = 1, len(nums)
i = 0
while i < n:
j = i + 1
while j < n and nums[j - 1] < nums[j]:
j += 1
ans = max(ans, j - i)
i = j
return ans
| null |
impl Solution {
pub fn find_length_of_lcis(nums: Vec<i32>) -> i32 {
let mut ans = 1;
let n = nums.len();
let mut i = 0;
while i < n {
let mut j = i + 1;
while j < n && nums[j - 1] < nums[j] {
j += 1;
}
ans = ans.max(j - i);
i = j;
}
ans as i32
}
}
| null | null | null |
function findLengthOfLCIS(nums: number[]): number {
let ans = 1;
const n = nums.length;
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && nums[j - 1] < nums[j]) {
++j;
}
ans = Math.max(ans, j - i);
i = j;
}
return ans;
}
|
Maximum Subarray
|
Given an integer array
nums
, find the
subarray
with the largest sum, and return
its sum
.
Example 1:
Input:
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output:
6
Explanation:
The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input:
nums = [1]
Output:
1
Explanation:
The subarray [1] has the largest sum 1.
Example 3:
Input:
nums = [5,4,-1,7,8]
Output:
23
Explanation:
The subarray [5,4,-1,7,8] has the largest sum 23.
Constraints:
1 <= nums.length <= 10
5
-10
4
<= nums[i] <= 10
4
Follow up:
If you have figured out the
O(n)
solution, try coding another solution using the
divide and conquer
approach, which is more subtle.
| null |
public class Solution {
public int MaxSubArray(int[] nums) {
int ans = nums[0], f = nums[0];
for (int i = 1; i < nums.Length; ++i) {
f = Math.Max(f, 0) + nums[i];
ans = Math.Max(ans, f);
}
return ans;
}
}
|
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = nums[0], f = nums[0];
for (int i = 1; i < nums.size(); ++i) {
f = max(f, 0) + nums[i];
ans = max(ans, f);
}
return ans;
}
};
| null | null |
func maxSubArray(nums []int) int {
ans, f := nums[0], nums[0]
for _, x := range nums[1:] {
f = max(f, 0) + x
ans = max(ans, f)
}
return ans
}
|
class Solution {
public int maxSubArray(int[] nums) {
return maxSub(nums, 0, nums.length - 1);
}
private int maxSub(int[] nums, int left, int right) {
if (left == right) {
return nums[left];
}
int mid = (left + right) >>> 1;
int lsum = maxSub(nums, left, mid);
int rsum = maxSub(nums, mid + 1, right);
return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right));
}
private int crossMaxSub(int[] nums, int left, int mid, int right) {
int lsum = 0, rsum = 0;
int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE;
for (int i = mid; i >= left; --i) {
lsum += nums[i];
lmx = Math.max(lmx, lsum);
}
for (int i = mid + 1; i <= right; ++i) {
rsum += nums[i];
rmx = Math.max(rmx, rsum);
}
return lmx + rmx;
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let [ans, f] = [nums[0], nums[0]];
for (let i = 1; i < nums.length; ++i) {
f = Math.max(f, 0) + nums[i];
ans = Math.max(ans, f);
}
return ans;
};
| null | null | null | null | null |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
def crossMaxSub(nums, left, mid, right):
lsum = rsum = 0
lmx = rmx = -inf
for i in range(mid, left - 1, -1):
lsum += nums[i]
lmx = max(lmx, lsum)
for i in range(mid + 1, right + 1):
rsum += nums[i]
rmx = max(rmx, rsum)
return lmx + rmx
def maxSub(nums, left, right):
if left == right:
return nums[left]
mid = (left + right) >> 1
lsum = maxSub(nums, left, mid)
rsum = maxSub(nums, mid + 1, right)
csum = crossMaxSub(nums, left, mid, right)
return max(lsum, rsum, csum)
left, right = 0, len(nums) - 1
return maxSub(nums, left, right)
| null |
impl Solution {
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut ans = nums[0];
let mut f = nums[0];
for i in 1..n {
f = f.max(0) + nums[i];
ans = ans.max(f);
}
ans
}
}
| null | null | null |
function maxSubArray(nums: number[]): number {
let [ans, f] = [nums[0], nums[0]];
for (let i = 1; i < nums.length; ++i) {
f = Math.max(f, 0) + nums[i];
ans = Math.max(ans, f);
}
return ans;
}
|
Ternary Expression Parser 🔒
|
Given a string
expression
representing arbitrarily nested ternary expressions, evaluate the expression, and return
the result of it
.
You can always assume that the given expression is valid and only contains digits,
'?'
,
':'
,
'T'
, and
'F'
where
'T'
is true and
'F'
is false. All the numbers in the expression are
one-digit
numbers (i.e., in the range
[0, 9]
).
The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit,
'T'
or
'F'
.
Example 1:
Input:
expression = "T?2:3"
Output:
"2"
Explanation:
If true, then result is 2; otherwise result is 3.
Example 2:
Input:
expression = "F?1:T?4:5"
Output:
"4"
Explanation:
The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(F ? 1 : (T ? 4 : 5))" --> "(F ? 1 : 4)" --> "4"
or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4"
Example 3:
Input:
expression = "T?T?F:5:3"
Output:
"F"
Explanation:
The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(T ? (T ? F : 5) : 3)" --> "(T ? F : 3)" --> "F"
"(T ? (T ? F : 5) : 3)" --> "(T ? F : 5)" --> "F"
Constraints:
5 <= expression.length <= 10
4
expression
consists of digits,
'T'
,
'F'
,
'?'
, and
':'
.
It is
guaranteed
that
expression
is a valid ternary expression and that each number is a
one-digit number
.
| null | null |
class Solution {
public:
string parseTernary(string expression) {
string stk;
bool cond = false;
reverse(expression.begin(), expression.end());
for (char& c : expression) {
if (c == ':') {
continue;
}
if (c == '?') {
cond = true;
} else {
if (cond) {
if (c == 'T') {
char x = stk.back();
stk.pop_back();
stk.pop_back();
stk.push_back(x);
} else {
stk.pop_back();
}
cond = false;
} else {
stk.push_back(c);
}
}
}
return {stk[0]};
}
};
| null | null |
func parseTernary(expression string) string {
stk := []byte{}
cond := false
for i := len(expression) - 1; i >= 0; i-- {
c := expression[i]
if c == ':' {
continue
}
if c == '?' {
cond = true
} else {
if cond {
if c == 'T' {
x := stk[len(stk)-1]
stk = stk[:len(stk)-2]
stk = append(stk, x)
} else {
stk = stk[:len(stk)-1]
}
cond = false
} else {
stk = append(stk, c)
}
}
}
return string(stk[0])
}
|
class Solution {
public String parseTernary(String expression) {
Deque<Character> stk = new ArrayDeque<>();
boolean cond = false;
for (int i = expression.length() - 1; i >= 0; --i) {
char c = expression.charAt(i);
if (c == ':') {
continue;
}
if (c == '?') {
cond = true;
} else {
if (cond) {
if (c == 'T') {
char x = stk.pop();
stk.pop();
stk.push(x);
} else {
stk.pop();
}
cond = false;
} else {
stk.push(c);
}
}
}
return String.valueOf(stk.peek());
}
}
| null | null | null | null | null | null |
class Solution:
def parseTernary(self, expression: str) -> str:
stk = []
cond = False
for c in expression[::-1]:
if c == ':':
continue
if c == '?':
cond = True
else:
if cond:
if c == 'T':
x = stk.pop()
stk.pop()
stk.append(x)
else:
stk.pop()
cond = False
else:
stk.append(c)
return stk[0]
| null | null | null | null | null | null |
Zigzag Conversion
|
The string
"PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input:
s = "PAYPALISHIRING", numRows = 3
Output:
"PAHNAPLSIIGYIR"
Example 2:
Input:
s = "PAYPALISHIRING", numRows = 4
Output:
"PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input:
s = "A", numRows = 1
Output:
"A"
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case),
','
and
'.'
.
1 <= numRows <= 1000
|
char* convert(char* s, int numRows) {
if (numRows == 1) {
return strdup(s);
}
int len = strlen(s);
char** g = (char**) malloc(numRows * sizeof(char*));
int* idx = (int*) malloc(numRows * sizeof(int));
for (int i = 0; i < numRows; ++i) {
g[i] = (char*) malloc((len + 1) * sizeof(char));
idx[i] = 0;
}
int i = 0, k = -1;
for (int p = 0; p < len; ++p) {
g[i][idx[i]++] = s[p];
if (i == 0 || i == numRows - 1) {
k = -k;
}
i += k;
}
char* ans = (char*) malloc((len + 1) * sizeof(char));
int pos = 0;
for (int r = 0; r < numRows; ++r) {
for (int j = 0; j < idx[r]; ++j) {
ans[pos++] = g[r][j];
}
free(g[r]);
}
ans[pos] = '\0';
free(g);
free(idx);
return ans;
}
|
public class Solution {
public string Convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
int n = s.Length;
StringBuilder[] g = new StringBuilder[numRows];
for (int j = 0; j < numRows; ++j) {
g[j] = new StringBuilder();
}
int i = 0, k = -1;
foreach (char c in s.ToCharArray()) {
g[i].Append(c);
if (i == 0 || i == numRows - 1) {
k = -k;
}
i += k;
}
StringBuilder ans = new StringBuilder();
foreach (StringBuilder t in g) {
ans.Append(t);
}
return ans.ToString();
}
}
|
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
vector<string> g(numRows);
int i = 0, k = -1;
for (char c : s) {
g[i] += c;
if (i == 0 || i == numRows - 1) {
k = -k;
}
i += k;
}
string ans;
for (auto& t : g) {
ans += t;
}
return ans;
}
};
| null | null |
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
g := make([][]byte, numRows)
i, k := 0, -1
for _, c := range s {
g[i] = append(g[i], byte(c))
if i == 0 || i == numRows-1 {
k = -k
}
i += k
}
return string(bytes.Join(g, nil))
}
|
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder[] g = new StringBuilder[numRows];
Arrays.setAll(g, k -> new StringBuilder());
int i = 0, k = -1;
for (char c : s.toCharArray()) {
g[i].append(c);
if (i == 0 || i == numRows - 1) {
k = -k;
}
i += k;
}
return String.join("", g);
}
}
|
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function (s, numRows) {
if (numRows === 1) {
return s;
}
const g = new Array(numRows).fill(_).map(() => []);
let i = 0;
let k = -1;
for (const c of s) {
g[i].push(c);
if (i === 0 || i === numRows - 1) {
k = -k;
}
i += k;
}
return g.flat().join('');
};
| null | null | null |
class Solution {
/**
* @param String $s
* @param Integer $numRows
* @return String
*/
function convert($s, $numRows) {
if ($numRows == 1) {
return $s;
}
$g = array_fill(0, $numRows, '');
$i = 0;
$k = -1;
$length = strlen($s);
for ($j = 0; $j < $length; $j++) {
$c = $s[$j];
$g[$i] .= $c;
if ($i == 0 || $i == $numRows - 1) {
$k = -$k;
}
$i += $k;
}
return implode('', $g);
}
}
| null |
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
g = [[] for _ in range(numRows)]
i, k = 0, -1
for c in s:
g[i].append(c)
if i == 0 or i == numRows - 1:
k = -k
i += k
return ''.join(chain(*g))
| null |
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
if num_rows == 1 {
return s;
}
let num_rows = num_rows as usize;
let mut g = vec![String::new(); num_rows];
let mut i = 0;
let mut k = -1;
for c in s.chars() {
g[i].push(c);
if i == 0 || i == num_rows - 1 {
k = -k;
}
i = (i as isize + k) as usize;
}
g.concat()
}
}
| null | null | null |
function convert(s: string, numRows: number): string {
if (numRows === 1) {
return s;
}
const g: string[][] = new Array(numRows).fill(0).map(() => []);
let i = 0;
let k = -1;
for (const c of s) {
g[i].push(c);
if (i === numRows - 1 || i === 0) {
k = -k;
}
i += k;
}
return g.flat().join('');
}
|
Search in a Sorted Array of Unknown Size 🔒
|
This is an
interactive problem
.
You have a sorted array of
unique
elements and an
unknown size
. You do not have an access to the array but you can use the
ArrayReader
interface to access it. You can call
ArrayReader.get(i)
that:
returns the value at the
i
th
index (
0-indexed
) of the secret array (i.e.,
secret[i]
), or
returns
2
31
- 1
if the
i
is out of the boundary of the array.
You are also given an integer
target
.
Return the index
k
of the hidden array where
secret[k] == target
or return
-1
otherwise.
You must write an algorithm with
O(log n)
runtime complexity.
Example 1:
Input:
secret = [-1,0,3,5,9,12], target = 9
Output:
4
Explanation:
9 exists in secret and its index is 4.
Example 2:
Input:
secret = [-1,0,3,5,9,12], target = 2
Output:
-1
Explanation:
2 does not exist in secret so return -1.
Constraints:
1 <= secret.length <= 10
4
-10
4
<= secret[i], target <= 10
4
secret
is sorted in a strictly increasing order.
| null | null |
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* class ArrayReader {
* public:
* int get(int index);
* };
*/
class Solution {
public:
int search(const ArrayReader& reader, int target) {
int r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
int l = r >> 1;
while (l < r) {
int mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) == target ? l : -1;
}
};
| null | null |
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* type ArrayReader struct {
* }
*
* func (this *ArrayReader) get(index int) int {}
*/
func search(reader ArrayReader, target int) int {
r := 1
for reader.get(r) < target {
r <<= 1
}
l := r >> 1
for l < r {
mid := (l + r) >> 1
if reader.get(mid) >= target {
r = mid
} else {
l = mid + 1
}
}
if reader.get(l) == target {
return l
}
return -1
}
|
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/
class Solution {
public int search(ArrayReader reader, int target) {
int r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
int l = r >> 1;
while (l < r) {
int mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) == target ? l : -1;
}
}
| null | null | null | null | null | null |
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader: "ArrayReader", target: int) -> int:
r = 1
while reader.get(r) < target:
r <<= 1
l = r >> 1
while l < r:
mid = (l + r) >> 1
if reader.get(mid) >= target:
r = mid
else:
l = mid + 1
return l if reader.get(l) == target else -1
| null | null | null | null | null |
/**
* class ArrayReader {
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* get(index: number): number {};
* };
*/
function search(reader: ArrayReader, target: number): number {
let r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
let l = r >> 1;
while (l < r) {
const mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) === target ? l : -1;
}
|
Flower Planting With No Adjacent
|
You have
n
gardens, labeled from
1
to
n
, and an array
paths
where
paths[i] = [x
i
, y
i
]
describes a bidirectional path between garden
x
i
to garden
y
i
. In each garden, you want to plant one of 4 types of flowers.
All gardens have
at most 3
paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return
any
such a choice as an array
answer
, where
answer[i]
is the type of flower planted in the
(i+1)
th
garden. The flower types are denoted
1
,
2
,
3
, or
4
. It is guaranteed an answer exists.
Example 1:
Input:
n = 3, paths = [[1,2],[2,3],[3,1]]
Output:
[1,2,3]
Explanation:
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
Example 2:
Input:
n = 4, paths = [[1,2],[3,4]]
Output:
[1,2,1,2]
Example 3:
Input:
n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output:
[1,2,3,4]
Constraints:
1 <= n <= 10
4
0 <= paths.length <= 2 * 10
4
paths[i].length == 2
1 <= x
i
, y
i
<= n
x
i
!= y
i
Every garden has
at most 3
paths coming into or leaving it.
| null | null |
class Solution {
public:
vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) {
vector<vector<int>> g(n);
for (auto& p : paths) {
int x = p[0] - 1, y = p[1] - 1;
g[x].push_back(y);
g[y].push_back(x);
}
vector<int> ans(n);
bool used[5];
for (int x = 0; x < n; ++x) {
memset(used, false, sizeof(used));
for (int y : g[x]) {
used[ans[y]] = true;
}
for (int c = 1; c < 5; ++c) {
if (!used[c]) {
ans[x] = c;
break;
}
}
}
return ans;
}
};
| null | null |
func gardenNoAdj(n int, paths [][]int) []int {
g := make([][]int, n)
for _, p := range paths {
x, y := p[0]-1, p[1]-1
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
ans := make([]int, n)
for x := 0; x < n; x++ {
used := [5]bool{}
for _, y := range g[x] {
used[ans[y]] = true
}
for c := 1; c < 5; c++ {
if !used[c] {
ans[x] = c
break
}
}
}
return ans
}
|
class Solution {
public int[] gardenNoAdj(int n, int[][] paths) {
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var p : paths) {
int x = p[0] - 1, y = p[1] - 1;
g[x].add(y);
g[y].add(x);
}
int[] ans = new int[n];
boolean[] used = new boolean[5];
for (int x = 0; x < n; ++x) {
Arrays.fill(used, false);
for (int y : g[x]) {
used[ans[y]] = true;
}
for (int c = 1; c < 5; ++c) {
if (!used[c]) {
ans[x] = c;
break;
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
g = defaultdict(list)
for x, y in paths:
x, y = x - 1, y - 1
g[x].append(y)
g[y].append(x)
ans = [0] * n
for x in range(n):
used = {ans[y] for y in g[x]}
for c in range(1, 5):
if c not in used:
ans[x] = c
break
return ans
| null |
impl Solution {
pub fn garden_no_adj(n: i32, paths: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize;
let mut g = vec![vec![]; n];
for path in paths {
let (x, y) = (path[0] as usize - 1, path[1] as usize - 1);
g[x].push(y);
g[y].push(x);
}
let mut ans = vec![0; n];
for x in 0..n {
let mut used = [false; 5];
for &y in &g[x] {
used[ans[y] as usize] = true;
}
for c in 1..5 {
if !used[c] {
ans[x] = c as i32;
break;
}
}
}
ans
}
}
| null | null | null |
function gardenNoAdj(n: number, paths: number[][]): number[] {
const g: number[][] = Array.from({ length: n }, () => []);
for (const [x, y] of paths) {
g[x - 1].push(y - 1);
g[y - 1].push(x - 1);
}
const ans: number[] = Array(n).fill(0);
for (let x = 0; x < n; ++x) {
const used: boolean[] = Array(5).fill(false);
for (const y of g[x]) {
used[ans[y]] = true;
}
for (let c = 1; c < 5; ++c) {
if (!used[c]) {
ans[x] = c;
break;
}
}
}
return ans;
}
|
4Sum
|
Given an array
nums
of
n
integers, return
an array of all the
unique
quadruplets
[nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
,
b
,
c
, and
d
are
distinct
.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in
any order
.
Example 1:
Input:
nums = [1,0,-1,0,-2,2], target = 0
Output:
[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input:
nums = [2,2,2,2,2], target = 8
Output:
[[2,2,2,2]]
Constraints:
1 <= nums.length <= 200
-10
9
<= nums[i] <= 10
9
-10
9
<= target <= 10
9
| null |
public class Solution {
public IList<IList<int>> FourSum(int[] nums, int target) {
int n = nums.Length;
var ans = new List<IList<int>>();
if (n < 4) {
return ans;
}
Array.Sort(nums);
for (int i = 0; i < n - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n - 2; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1, l = n - 1;
while (k < l) {
long x = (long) nums[i] + nums[j] + nums[k] + nums[l];
if (x < target) {
++k;
} else if (x > target) {
--l;
} else {
ans.Add(new List<int> {nums[i], nums[j], nums[k++], nums[l--]});
while (k < l && nums[k] == nums[k - 1]) {
++k;
}
while (k < l && nums[l] == nums[l + 1]) {
--l;
}
}
}
}
}
return ans;
}
}
|
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> ans;
if (n < 4) {
return ans;
}
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 3; ++i) {
if (i && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n - 2; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1, l = n - 1;
while (k < l) {
long long x = (long long) nums[i] + nums[j] + nums[k] + nums[l];
if (x < target) {
++k;
} else if (x > target) {
--l;
} else {
ans.push_back({nums[i], nums[j], nums[k++], nums[l--]});
while (k < l && nums[k] == nums[k - 1]) {
++k;
}
while (k < l && nums[l] == nums[l + 1]) {
--l;
}
}
}
}
}
return ans;
}
};
| null | null |
func fourSum(nums []int, target int) (ans [][]int) {
n := len(nums)
if n < 4 {
return
}
sort.Ints(nums)
for i := 0; i < n-3; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < n-2; j++ {
if j > i+1 && nums[j] == nums[j-1] {
continue
}
k, l := j+1, n-1
for k < l {
x := nums[i] + nums[j] + nums[k] + nums[l]
if x < target {
k++
} else if x > target {
l--
} else {
ans = append(ans, []int{nums[i], nums[j], nums[k], nums[l]})
k++
l--
for k < l && nums[k] == nums[k-1] {
k++
}
for k < l && nums[l] == nums[l+1] {
l--
}
}
}
}
}
return
}
|
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;
List<List<Integer>> ans = new ArrayList<>();
if (n < 4) {
return ans;
}
Arrays.sort(nums);
for (int i = 0; i < n - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n - 2; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1, l = n - 1;
while (k < l) {
long x = (long) nums[i] + nums[j] + nums[k] + nums[l];
if (x < target) {
++k;
} else if (x > target) {
--l;
} else {
ans.add(List.of(nums[i], nums[j], nums[k++], nums[l--]));
while (k < l && nums[k] == nums[k - 1]) {
++k;
}
while (k < l && nums[l] == nums[l + 1]) {
--l;
}
}
}
}
}
return ans;
}
}
|
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function (nums, target) {
const n = nums.length;
const ans = [];
if (n < 4) {
return ans;
}
nums.sort((a, b) => a - b);
for (let i = 0; i < n - 3; ++i) {
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
for (let j = i + 1; j < n - 2; ++j) {
if (j > i + 1 && nums[j] === nums[j - 1]) {
continue;
}
let [k, l] = [j + 1, n - 1];
while (k < l) {
const x = nums[i] + nums[j] + nums[k] + nums[l];
if (x < target) {
++k;
} else if (x > target) {
--l;
} else {
ans.push([nums[i], nums[j], nums[k++], nums[l--]]);
while (k < l && nums[k] === nums[k - 1]) {
++k;
}
while (k < l && nums[l] === nums[l + 1]) {
--l;
}
}
}
}
}
return ans;
};
| null | null | null |
class Solution {
/**
* @param int[] $nums
* @param int $target
* @return int[][]
*/
function fourSum($nums, $target) {
$result = [];
$n = count($nums);
sort($nums);
for ($i = 0; $i < $n - 3; $i++) {
if ($i > 0 && $nums[$i] === $nums[$i - 1]) {
continue;
}
for ($j = $i + 1; $j < $n - 2; $j++) {
if ($j > $i + 1 && $nums[$j] === $nums[$j - 1]) {
continue;
}
$left = $j + 1;
$right = $n - 1;
while ($left < $right) {
$sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right];
if ($sum === $target) {
$result[] = [$nums[$i], $nums[$j], $nums[$left], $nums[$right]];
while ($left < $right && $nums[$left] === $nums[$left + 1]) {
$left++;
}
while ($left < $right && $nums[$right] === $nums[$right - 1]) {
$right--;
}
$left++;
$right--;
} elseif ($sum < $target) {
$left++;
} else {
$right--;
}
}
}
}
return $result;
}
}
| null |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
ans = []
if n < 4:
return ans
nums.sort()
for i in range(n - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
k, l = j + 1, n - 1
while k < l:
x = nums[i] + nums[j] + nums[k] + nums[l]
if x < target:
k += 1
elif x > target:
l -= 1
else:
ans.append([nums[i], nums[j], nums[k], nums[l]])
k, l = k + 1, l - 1
while k < l and nums[k] == nums[k - 1]:
k += 1
while k < l and nums[l] == nums[l + 1]:
l -= 1
return ans
| null | null | null | null | null |
function fourSum(nums: number[], target: number): number[][] {
const n = nums.length;
const ans: number[][] = [];
if (n < 4) {
return ans;
}
nums.sort((a, b) => a - b);
for (let i = 0; i < n - 3; ++i) {
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}
for (let j = i + 1; j < n - 2; ++j) {
if (j > i + 1 && nums[j] === nums[j - 1]) {
continue;
}
let [k, l] = [j + 1, n - 1];
while (k < l) {
const x = nums[i] + nums[j] + nums[k] + nums[l];
if (x < target) {
++k;
} else if (x > target) {
--l;
} else {
ans.push([nums[i], nums[j], nums[k++], nums[l--]]);
while (k < l && nums[k] === nums[k - 1]) {
++k;
}
while (k < l && nums[l] === nums[l + 1]) {
--l;
}
}
}
}
}
return ans;
}
|
Divisible and Non-divisible Sums Difference
|
You are given positive integers
n
and
m
.
Define two integers as follows:
num1
: The sum of all integers in the range
[1, n]
(both
inclusive
) that are
not divisible
by
m
.
num2
: The sum of all integers in the range
[1, n]
(both
inclusive
) that are
divisible
by
m
.
Return
the integer
num1 - num2
.
Example 1:
Input:
n = 10, m = 3
Output:
19
Explanation:
In the given example:
- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37.
- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18.
We return 37 - 18 = 19 as the answer.
Example 2:
Input:
n = 5, m = 6
Output:
15
Explanation:
In the given example:
- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15.
- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0.
We return 15 - 0 = 15 as the answer.
Example 3:
Input:
n = 5, m = 1
Output:
-15
Explanation:
In the given example:
- Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0.
- Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15.
We return 0 - 15 = -15 as the answer.
Constraints:
1 <= n, m <= 1000
| null | null |
class Solution {
public:
int differenceOfSums(int n, int m) {
int ans = 0;
for (int i = 1; i <= n; ++i) {
ans += i % m ? i : -i;
}
return ans;
}
};
| null | null |
func differenceOfSums(n int, m int) (ans int) {
for i := 1; i <= n; i++ {
if i%m == 0 {
ans -= i
} else {
ans += i
}
}
return
}
|
class Solution {
public int differenceOfSums(int n, int m) {
int ans = 0;
for (int i = 1; i <= n; ++i) {
ans += i % m == 0 ? -i : i;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
return sum(i if i % m else -i for i in range(1, n + 1))
| null |
impl Solution {
pub fn difference_of_sums(n: i32, m: i32) -> i32 {
let mut ans = 0;
for i in 1..=n {
if i % m != 0 {
ans += i;
} else {
ans -= i;
}
}
ans
}
}
| null | null | null |
function differenceOfSums(n: number, m: number): number {
let ans = 0;
for (let i = 1; i <= n; ++i) {
ans += i % m ? i : -i;
}
return ans;
}
|
Sorted GCD Pair Queries
|
You are given an integer array
nums
of length
n
and an integer array
queries
.
Let
gcdPairs
denote an array obtained by calculating the
GCD
of all possible pairs
(nums[i], nums[j])
, where
0 <= i < j < n
, and then sorting these values in
ascending
order.
For each query
queries[i]
, you need to find the element at index
queries[i]
in
gcdPairs
.
Return an integer array
answer
, where
answer[i]
is the value at
gcdPairs[queries[i]]
for each query.
The term
gcd(a, b)
denotes the
greatest common divisor
of
a
and
b
.
Example 1:
Input:
nums = [2,3,4], queries = [0,2,2]
Output:
[1,2,2]
Explanation:
gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]
.
After sorting in ascending order,
gcdPairs = [1, 1, 2]
.
So, the answer is
[gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]
.
Example 2:
Input:
nums = [4,4,2,1], queries = [5,3,1,0]
Output:
[4,2,1,1]
Explanation:
gcdPairs
sorted in ascending order is
[1, 1, 1, 2, 2, 4]
.
Example 3:
Input:
nums = [2,2], queries = [0,0]
Output:
[2,2]
Explanation:
gcdPairs = [2]
.
Constraints:
2 <= n == nums.length <= 10
5
1 <= nums[i] <= 5 * 10
4
1 <= queries.length <= 10
5
0 <= queries[i] < n * (n - 1) / 2
| null | null |
class Solution {
public:
vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) {
int mx = ranges::max(nums);
vector<int> cnt(mx + 1);
vector<long long> cntG(mx + 1);
for (int x : nums) {
++cnt[x];
}
for (int i = mx; i; --i) {
long long v = 0;
for (int j = i; j <= mx; j += i) {
v += cnt[j];
cntG[i] -= cntG[j];
}
cntG[i] += 1LL * v * (v - 1) / 2;
}
for (int i = 2; i <= mx; ++i) {
cntG[i] += cntG[i - 1];
}
vector<int> ans;
for (auto&& q : queries) {
ans.push_back(upper_bound(cntG.begin(), cntG.end(), q) - cntG.begin());
}
return ans;
}
};
| null | null |
func gcdValues(nums []int, queries []int64) (ans []int) {
mx := slices.Max(nums)
cnt := make([]int, mx+1)
cntG := make([]int, mx+1)
for _, x := range nums {
cnt[x]++
}
for i := mx; i > 0; i-- {
var v int
for j := i; j <= mx; j += i {
v += cnt[j]
cntG[i] -= cntG[j]
}
cntG[i] += v * (v - 1) / 2
}
for i := 2; i <= mx; i++ {
cntG[i] += cntG[i-1]
}
for _, q := range queries {
ans = append(ans, sort.SearchInts(cntG, int(q)+1))
}
return
}
|
class Solution {
public int[] gcdValues(int[] nums, long[] queries) {
int mx = Arrays.stream(nums).max().getAsInt();
int[] cnt = new int[mx + 1];
long[] cntG = new long[mx + 1];
for (int x : nums) {
++cnt[x];
}
for (int i = mx; i > 0; --i) {
int v = 0;
for (int j = i; j <= mx; j += i) {
v += cnt[j];
cntG[i] -= cntG[j];
}
cntG[i] += 1L * v * (v - 1) / 2;
}
for (int i = 2; i <= mx; ++i) {
cntG[i] += cntG[i - 1];
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
ans[i] = search(cntG, queries[i]);
}
return ans;
}
private int search(long[] nums, long x) {
int n = nums.length;
int l = 0, r = n;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] > x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
| null | null | null | null | null | null |
class Solution:
def gcdValues(self, nums: List[int], queries: List[int]) -> List[int]:
mx = max(nums)
cnt = Counter(nums)
cnt_g = [0] * (mx + 1)
for i in range(mx, 0, -1):
v = 0
for j in range(i, mx + 1, i):
v += cnt[j]
cnt_g[i] -= cnt_g[j]
cnt_g[i] += v * (v - 1) // 2
s = list(accumulate(cnt_g))
return [bisect_right(s, q) for q in queries]
| null | null | null | null | null | null |
Remove Interval 🔒
|
A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form
[a, b)
. A real number
x
is in the set if one of its intervals
[a, b)
contains
x
(i.e.
a <= x < b
).
You are given a
sorted
list of disjoint intervals
intervals
representing a set of real numbers as described above, where
intervals[i] = [a
i
, b
i
]
represents the interval
[a
i
, b
i
)
. You are also given another interval
toBeRemoved
.
Return
the set of real numbers with the interval
toBeRemoved
removed
from
intervals
. In other words, return the set of real numbers such that every
x
in the set is in
intervals
but
not
in
toBeRemoved
. Your answer should be a
sorted
list of disjoint intervals as described above.
Example 1:
Input:
intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output:
[[0,1],[6,7]]
Example 2:
Input:
intervals = [[0,5]], toBeRemoved = [2,3]
Output:
[[0,2],[3,5]]
Example 3:
Input:
intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
Output:
[[-5,-4],[-3,-2],[4,5],[8,9]]
Constraints:
1 <= intervals.length <= 10
4
-10
9
<= a
i
< b
i
<= 10
9
| null | null |
class Solution {
public:
vector<vector<int>> removeInterval(vector<vector<int>>& intervals, vector<int>& toBeRemoved) {
int x = toBeRemoved[0], y = toBeRemoved[1];
vector<vector<int>> ans;
for (auto& e : intervals) {
int a = e[0], b = e[1];
if (a >= y || b <= x) {
ans.push_back(e);
} else {
if (a < x) {
ans.push_back({a, x});
}
if (b > y) {
ans.push_back({y, b});
}
}
}
return ans;
}
};
| null | null |
func removeInterval(intervals [][]int, toBeRemoved []int) (ans [][]int) {
x, y := toBeRemoved[0], toBeRemoved[1]
for _, e := range intervals {
a, b := e[0], e[1]
if a >= y || b <= x {
ans = append(ans, e)
} else {
if a < x {
ans = append(ans, []int{a, x})
}
if b > y {
ans = append(ans, []int{y, b})
}
}
}
return
}
|
class Solution {
public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
int x = toBeRemoved[0], y = toBeRemoved[1];
List<List<Integer>> ans = new ArrayList<>();
for (var e : intervals) {
int a = e[0], b = e[1];
if (a >= y || b <= x) {
ans.add(Arrays.asList(a, b));
} else {
if (a < x) {
ans.add(Arrays.asList(a, x));
}
if (b > y) {
ans.add(Arrays.asList(y, b));
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def removeInterval(
self, intervals: List[List[int]], toBeRemoved: List[int]
) -> List[List[int]]:
x, y = toBeRemoved
ans = []
for a, b in intervals:
if a >= y or b <= x:
ans.append([a, b])
else:
if a < x:
ans.append([a, x])
if b > y:
ans.append([y, b])
return ans
| null | null | null | null | null | null |
Word Break II
|
Given a string
s
and a dictionary of strings
wordDict
, add spaces in
s
to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in
any order
.
Note
that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input:
s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output:
["cats and dog","cat sand dog"]
Example 2:
Input:
s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output:
["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation:
Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output:
[]
Constraints:
1 <= s.length <= 20
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 10
s
and
wordDict[i]
consist of only lowercase English letters.
All the strings of
wordDict
are
unique
.
Input is generated in a way that the length of the answer doesn't exceed 10
5
.
| null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Node
{
public int Index1 { get; set; }
public int Index2 { get; set; }
}
public class Solution {
public IList<string> WordBreak(string s, IList<string> wordDict) {
var paths = new List<Tuple<int, string>>[s.Length + 1];
paths[s.Length] = new List<Tuple<int, string>> { Tuple.Create(-1, (string)null) };
var wordDictGroup = wordDict.GroupBy(word => word.Length);
for (var i = s.Length - 1; i >= 0; --i)
{
paths[i] = new List<Tuple<int, string>>();
foreach (var wordGroup in wordDictGroup)
{
var wordLength = wordGroup.Key;
if (i + wordLength <= s.Length && paths[i + wordLength].Count > 0)
{
foreach (var word in wordGroup)
{
if (s.Substring(i, wordLength) == word)
{
paths[i].Add(Tuple.Create(i + wordLength, word));
}
}
}
}
}
return GenerateResults(paths);
}
private IList<string> GenerateResults(List<Tuple<int, string>>[] paths)
{
var results = new List<string>();
var sb = new StringBuilder();
var stack = new Stack<Node>();
stack.Push(new Node());
while (stack.Count > 0)
{
var node = stack.Peek();
if (node.Index1 == paths.Length - 1 || node.Index2 == paths[node.Index1].Count)
{
if (node.Index1 == paths.Length - 1)
{
results.Add(sb.ToString());
}
stack.Pop();
if (stack.Count > 0)
{
var parent = stack.Peek();
var length = paths[parent.Index1][parent.Index2 - 1].Item2.Length;
if (length < sb.Length) ++length;
sb.Remove(sb.Length - length, length);
}
}
else
{
var newNode = new Node { Index1 = paths[node.Index1][node.Index2].Item1, Index2 = 0 };
if (sb.Length != 0)
{
sb.Append(' ');
}
sb.Append(paths[node.Index1][node.Index2].Item2);
stack.Push(newNode);
++node.Index2;
}
}
return results;
}
}
| null | null | null |
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func (this *Trie) search(word string) bool {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}
func wordBreak(s string, wordDict []string) []string {
trie := newTrie()
for _, w := range wordDict {
trie.insert(w)
}
var dfs func(string) [][]string
dfs = func(s string) [][]string {
res := [][]string{}
if len(s) == 0 {
res = append(res, []string{})
return res
}
for i := 1; i <= len(s); i++ {
if trie.search(s[:i]) {
for _, v := range dfs(s[i:]) {
v = append([]string{s[:i]}, v...)
res = append(res, v)
}
}
}
return res
}
res := dfs(s)
ans := []string{}
for _, v := range res {
ans = append(ans, strings.Join(v, " "))
}
return ans
}
|
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> wordBreak(String s, List<String> wordDict) {
for (String w : wordDict) {
trie.insert(w);
}
List<List<String>> res = dfs(s);
return res.stream().map(e -> String.join(" ", e)).collect(Collectors.toList());
}
private List<List<String>> dfs(String s) {
List<List<String>> res = new ArrayList<>();
if ("".equals(s)) {
res.add(new ArrayList<>());
return res;
}
for (int i = 1; i <= s.length(); ++i) {
if (trie.search(s.substring(0, i))) {
for (List<String> v : dfs(s.substring(i))) {
v.add(0, s.substring(0, i));
res.add(v);
}
}
}
return res;
}
}
| null | null | null | null | null | null |
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return False
node = node.children[idx]
return node.is_end
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s):
if not s:
return [[]]
res = []
for i in range(1, len(s) + 1):
if trie.search(s[:i]):
for v in dfs(s[i:]):
res.append([s[:i]] + v)
return res
trie = Trie()
for w in wordDict:
trie.insert(w)
ans = dfs(s)
return [' '.join(v) for v in ans]
| null | null | null | null | null | null |
Kth Largest Element in an Array
|
Given an integer array
nums
and an integer
k
, return
the
k
th
largest element in the array
.
Note that it is the
k
th
largest element in the sorted order, not the
k
th
distinct element.
Can you solve it without sorting?
Example 1:
Input:
nums = [3,2,1,5,6,4], k = 2
Output:
5
Example 2:
Input:
nums = [3,2,3,1,2,4,5,5,6], k = 4
Output:
4
Constraints:
1 <= k <= nums.length <= 10
5
-10
4
<= nums[i] <= 10
4
| null | null |
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
int m = INT_MIN;
for (int x : nums) {
++cnt[x];
m = max(m, x);
}
for (int i = m;; --i) {
k -= cnt[i];
if (k <= 0) {
return i;
}
}
}
};
| null | null |
func findKthLargest(nums []int, k int) int {
cnt := map[int]int{}
m := -(1 << 30)
for _, x := range nums {
cnt[x]++
m = max(m, x)
}
for i := m; ; i-- {
k -= cnt[i]
if k <= 0 {
return i
}
}
}
|
class Solution {
public int findKthLargest(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>(nums.length);
int m = Integer.MIN_VALUE;
for (int x : nums) {
m = Math.max(m, x);
cnt.merge(x, 1, Integer::sum);
}
for (int i = m;; --i) {
k -= cnt.getOrDefault(i, 0);
if (k <= 0) {
return i;
}
}
}
}
| null | null | null | null | null | null |
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
cnt = Counter(nums)
for i in count(max(cnt), -1):
k -= cnt[i]
if k <= 0:
return i
| null |
use std::collections::HashMap;
impl Solution {
pub fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {
let mut cnt = HashMap::new();
let mut m = i32::MIN;
for &x in &nums {
*cnt.entry(x).or_insert(0) += 1;
if x > m {
m = x;
}
}
let mut k = k;
for i in (i32::MIN..=m).rev() {
if let Some(&count) = cnt.get(&i) {
k -= count;
if k <= 0 {
return i;
}
}
}
unreachable!();
}
}
| null | null | null |
function findKthLargest(nums: number[], k: number): number {
const cnt: Record<number, number> = {};
for (const x of nums) {
cnt[x] = (cnt[x] || 0) + 1;
}
const m = Math.max(...nums);
for (let i = m; ; --i) {
k -= cnt[i] || 0;
if (k <= 0) {
return i;
}
}
}
|
Left and Right Sum Differences
|
You are given a
0-indexed
integer array
nums
of size
n
.
Define two arrays
leftSum
and
rightSum
where:
leftSum[i]
is the sum of elements to the left of the index
i
in the array
nums
. If there is no such element,
leftSum[i] = 0
.
rightSum[i]
is the sum of elements to the right of the index
i
in the array
nums
. If there is no such element,
rightSum[i] = 0
.
Return an integer array
answer
of size
n
where
answer[i] = |leftSum[i] - rightSum[i]|
.
Example 1:
Input:
nums = [10,4,8,3]
Output:
[15,1,11,22]
Explanation:
The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].
The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].
Example 2:
Input:
nums = [1]
Output:
[0]
Explanation:
The array leftSum is [0] and the array rightSum is [0].
The array answer is [|0 - 0|] = [0].
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 10
5
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* leftRigthDifference(int* nums, int numsSize, int* returnSize) {
int left = 0;
int right = 0;
for (int i = 0; i < numsSize; i++) {
right += nums[i];
}
int* ans = malloc(sizeof(int) * numsSize);
for (int i = 0; i < numsSize; i++) {
right -= nums[i];
ans[i] = abs(left - right);
left += nums[i];
}
*returnSize = numsSize;
return ans;
}
| null |
class Solution {
public:
vector<int> leftRigthDifference(vector<int>& nums) {
int left = 0, right = accumulate(nums.begin(), nums.end(), 0);
vector<int> ans;
for (int& x : nums) {
right -= x;
ans.push_back(abs(left - right));
left += x;
}
return ans;
}
};
| null | null |
func leftRigthDifference(nums []int) (ans []int) {
var left, right int
for _, x := range nums {
right += x
}
for _, x := range nums {
right -= x
ans = append(ans, abs(left-right))
left += x
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
class Solution {
public int[] leftRigthDifference(int[] nums) {
int left = 0, right = Arrays.stream(nums).sum();
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
right -= nums[i];
ans[i] = Math.abs(left - right);
left += nums[i];
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def leftRigthDifference(self, nums: List[int]) -> List[int]:
left, right = 0, sum(nums)
ans = []
for x in nums:
right -= x
ans.append(abs(left - right))
left += x
return ans
| null |
impl Solution {
pub fn left_right_difference(nums: Vec<i32>) -> Vec<i32> {
let mut left = 0;
let mut right: i32 = nums.iter().sum();
let mut ans = vec![];
for &x in &nums {
right -= x;
ans.push((left - right).abs());
left += x;
}
ans
}
}
| null | null | null |
function leftRigthDifference(nums: number[]): number[] {
let left = 0;
let right = nums.reduce((r, v) => r + v);
return nums.map(v => {
right -= v;
const res = Math.abs(left - right);
left += v;
return res;
});
}
|
Kids With the Greatest Number of Candies
|
There are
n
kids with candies. You are given an integer array
candies
, where each
candies[i]
represents the number of candies the
i
th
kid has, and an integer
extraCandies
, denoting the number of extra candies that you have.
Return
a boolean array
result
of length
n
, where
result[i]
is
true
if, after giving the
i
th
kid all the
extraCandies
, they will have the
greatest
number of candies among all the kids
, or
false
otherwise
.
Note that
multiple
kids can have the
greatest
number of candies.
Example 1:
Input:
candies = [2,3,5,1,3], extraCandies = 3
Output:
[true,true,true,false,true]
Explanation:
If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
Example 2:
Input:
candies = [4,2,1,1,2], extraCandies = 1
Output:
[true,false,false,false,false]
Explanation:
There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
Example 3:
Input:
candies = [12,1,12], extraCandies = 10
Output:
[true,false,true]
Constraints:
n == candies.length
2 <= n <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50
|
#define max(a, b) (((a) > (b)) ? (a) : (b))
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize) {
int mx = 0;
for (int i = 0; i < candiesSize; i++) {
mx = max(mx, candies[i]);
}
bool* ans = malloc(candiesSize * sizeof(bool));
for (int i = 0; i < candiesSize; i++) {
ans[i] = candies[i] + extraCandies >= mx;
}
*returnSize = candiesSize;
return ans;
}
| null |
class Solution {
public:
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
int mx = *max_element(candies.begin(), candies.end());
vector<bool> res;
for (int candy : candies) {
res.push_back(candy + extraCandies >= mx);
}
return res;
}
};
| null | null |
func kidsWithCandies(candies []int, extraCandies int) (ans []bool) {
mx := slices.Max(candies)
for _, candy := range candies {
ans = append(ans, candy+extraCandies >= mx)
}
return
}
|
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int mx = 0;
for (int candy : candies) {
mx = Math.max(mx, candy);
}
List<Boolean> res = new ArrayList<>();
for (int candy : candies) {
res.add(candy + extraCandies >= mx);
}
return res;
}
}
| null | null | null | null |
class Solution {
/**
* @param Integer[] $candies
* @param Integer $extraCandies
* @return Boolean[]
*/
function kidsWithCandies($candies, $extraCandies) {
$max = max($candies);
$rs = [];
for ($i = 0; $i < count($candies); $i++) {
array_push($rs, $candies[$i] + $extraCandies >= $max);
}
return $rs;
}
}
| null |
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
mx = max(candies)
return [candy + extraCandies >= mx for candy in candies]
| null |
impl Solution {
pub fn kids_with_candies(candies: Vec<i32>, extra_candies: i32) -> Vec<bool> {
let max = *candies.iter().max().unwrap();
candies.iter().map(|v| v + extra_candies >= max).collect()
}
}
| null | null | null |
function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
const max = candies.reduce((r, v) => Math.max(r, v));
return candies.map(v => v + extraCandies >= max);
}
|
Word Ladder II
|
A
transformation sequence
from word
beginWord
to word
endWord
using a dictionary
wordList
is a sequence of words
beginWord -> s
1
-> s
2
-> ... -> s
k
such that:
Every adjacent pair of words differs by a single letter.
Every
s
i
for
1 <= i <= k
is in
wordList
. Note that
beginWord
does not need to be in
wordList
.
s
k
== endWord
Given two words,
beginWord
and
endWord
, and a dictionary
wordList
, return
all the
shortest transformation sequences
from
beginWord
to
endWord
, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words
[beginWord, s
1
, s
2
, ..., s
k
]
.
Example 1:
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation:
There are 2 shortest transformation sequences:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
"hit" -> "hot" -> "lot" -> "log" -> "cog"
Example 2:
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output:
[]
Explanation:
The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 5
endWord.length == beginWord.length
1 <= wordList.length <= 500
wordList[i].length == beginWord.length
beginWord
,
endWord
, and
wordList[i]
consist of lowercase English letters.
beginWord != endWord
All the words in
wordList
are
unique
.
The
sum
of all shortest transformation sequences does not exceed
10
5
.
| null | null | null | null | null |
func findLadders(beginWord string, endWord string, wordList []string) [][]string {
var ans [][]string
words := make(map[string]bool)
for _, word := range wordList {
words[word] = true
}
if !words[endWord] {
return ans
}
words[beginWord] = false
dist := map[string]int{beginWord: 0}
prev := map[string]map[string]bool{}
q := []string{beginWord}
found := false
step := 0
for len(q) > 0 && !found {
step++
for i := len(q); i > 0; i-- {
p := q[0]
q = q[1:]
chars := []byte(p)
for j := 0; j < len(chars); j++ {
ch := chars[j]
for k := 'a'; k <= 'z'; k++ {
chars[j] = byte(k)
t := string(chars)
if v, ok := dist[t]; ok {
if v == step {
prev[t][p] = true
}
}
if !words[t] {
continue
}
if len(prev[t]) == 0 {
prev[t] = make(map[string]bool)
}
prev[t][p] = true
words[t] = false
q = append(q, t)
dist[t] = step
if endWord == t {
found = true
}
}
chars[j] = ch
}
}
}
var dfs func(path []string, begin, cur string)
dfs = func(path []string, begin, cur string) {
if cur == beginWord {
cp := make([]string, len(path))
copy(cp, path)
ans = append(ans, cp)
return
}
for k := range prev[cur] {
path = append([]string{k}, path...)
dfs(path, beginWord, k)
path = path[1:]
}
}
if found {
path := []string{endWord}
dfs(path, beginWord, endWord)
}
return ans
}
|
class Solution {
private List<List<String>> ans;
private Map<String, Set<String>> prev;
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
ans = new ArrayList<>();
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) {
return ans;
}
words.remove(beginWord);
Map<String, Integer> dist = new HashMap<>();
dist.put(beginWord, 0);
prev = new HashMap<>();
Queue<String> q = new ArrayDeque<>();
q.offer(beginWord);
boolean found = false;
int step = 0;
while (!q.isEmpty() && !found) {
++step;
for (int i = q.size(); i > 0; --i) {
String p = q.poll();
char[] chars = p.toCharArray();
for (int j = 0; j < chars.length; ++j) {
char ch = chars[j];
for (char k = 'a'; k <= 'z'; ++k) {
chars[j] = k;
String t = new String(chars);
if (dist.getOrDefault(t, 0) == step) {
prev.get(t).add(p);
}
if (!words.contains(t)) {
continue;
}
prev.computeIfAbsent(t, key -> new HashSet<>()).add(p);
words.remove(t);
q.offer(t);
dist.put(t, step);
if (endWord.equals(t)) {
found = true;
}
}
chars[j] = ch;
}
}
}
if (found) {
Deque<String> path = new ArrayDeque<>();
path.add(endWord);
dfs(path, beginWord, endWord);
}
return ans;
}
private void dfs(Deque<String> path, String beginWord, String cur) {
if (cur.equals(beginWord)) {
ans.add(new ArrayList<>(path));
return;
}
for (String precursor : prev.get(cur)) {
path.addFirst(precursor);
dfs(path, beginWord, precursor);
path.removeFirst();
}
}
}
| null | null | null | null | null | null |
class Solution:
def findLadders(
self, beginWord: str, endWord: str, wordList: List[str]
) -> List[List[str]]:
def dfs(path, cur):
if cur == beginWord:
ans.append(path[::-1])
return
for precursor in prev[cur]:
path.append(precursor)
dfs(path, precursor)
path.pop()
ans = []
words = set(wordList)
if endWord not in words:
return ans
words.discard(beginWord)
dist = {beginWord: 0}
prev = defaultdict(set)
q = deque([beginWord])
found = False
step = 0
while q and not found:
step += 1
for i in range(len(q), 0, -1):
p = q.popleft()
s = list(p)
for i in range(len(s)):
ch = s[i]
for j in range(26):
s[i] = chr(ord('a') + j)
t = ''.join(s)
if dist.get(t, 0) == step:
prev[t].add(p)
if t not in words:
continue
prev[t].add(p)
words.discard(t)
q.append(t)
dist[t] = step
if endWord == t:
found = True
s[i] = ch
if found:
path = [endWord]
dfs(path, endWord)
return ans
| null | null | null | null | null | null |
Minimum Number of Coins for Fruits II 🔒
|
You are at a fruit market with different types of exotic fruits on display.
You are given a
1-indexed
array
prices
, where
prices[i]
denotes the number of coins needed to purchase the
i
th
fruit.
The fruit market has the following offer:
If you purchase the
i
th
fruit at
prices[i]
coins, you can get the next
i
fruits for free.
Note
that even if you
can
take fruit
j
for free, you can still purchase it for
prices[j]
coins to receive a new offer.
Return
the
minimum
number of coins needed to acquire all the fruits
.
Example 1:
Input:
prices = [3,1,2]
Output:
4
Explanation:
You can acquire the fruits as follows:
- Purchase the 1
st
fruit with 3 coins, and you are allowed to take the 2
nd
fruit for free.
- Purchase the 2
nd
fruit with 1 coin, and you are allowed to take the 3
rd
fruit for free.
- Take the 3
rd
fruit for free.
Note that even though you were allowed to take the 2
nd
fruit for free, you purchased it because it is more optimal.
It can be proven that 4 is the minimum number of coins needed to acquire all the fruits.
Example 2:
Input:
prices = [1,10,1,1]
Output:
2
Explanation:
You can acquire the fruits as follows:
- Purchase the 1
st
fruit with 1 coin, and you are allowed to take the 2
nd
fruit for free.
- Take the 2
nd
fruit for free.
- Purchase the 3
rd
fruit for 1 coin, and you are allowed to take the 4
th
fruit for free.
- Take the 4
t
h
fruit for free.
It can be proven that 2 is the minimum number of coins needed to acquire all the fruits.
Constraints:
1 <= prices.length <= 10
5
1 <= prices[i] <= 10
5
| null | null |
class Solution {
public:
int minimumCoins(vector<int>& prices) {
int n = prices.size();
deque<int> q;
for (int i = n; i; --i) {
while (q.size() && q.front() > i * 2 + 1) {
q.pop_front();
}
if (i <= (n - 1) / 2) {
prices[i - 1] += prices[q.front() - 1];
}
while (q.size() && prices[q.back() - 1] >= prices[i - 1]) {
q.pop_back();
}
q.push_back(i);
}
return prices[0];
}
};
| null | null |
func minimumCoins(prices []int) int {
n := len(prices)
q := Deque{}
for i := n; i > 0; i-- {
for q.Size() > 0 && q.Front() > i*2+1 {
q.PopFront()
}
if i <= (n-1)/2 {
prices[i-1] += prices[q.Front()-1]
}
for q.Size() > 0 && prices[q.Back()-1] >= prices[i-1] {
q.PopBack()
}
q.PushBack(i)
}
return prices[0]
}
// template
type Deque struct{ l, r []int }
func (q Deque) Empty() bool {
return len(q.l) == 0 && len(q.r) == 0
}
func (q Deque) Size() int {
return len(q.l) + len(q.r)
}
func (q *Deque) PushFront(v int) {
q.l = append(q.l, v)
}
func (q *Deque) PushBack(v int) {
q.r = append(q.r, v)
}
func (q *Deque) PopFront() (v int) {
if len(q.l) > 0 {
q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1]
} else {
v, q.r = q.r[0], q.r[1:]
}
return
}
func (q *Deque) PopBack() (v int) {
if len(q.r) > 0 {
q.r, v = q.r[:len(q.r)-1], q.r[len(q.r)-1]
} else {
v, q.l = q.l[0], q.l[1:]
}
return
}
func (q Deque) Front() int {
if len(q.l) > 0 {
return q.l[len(q.l)-1]
}
return q.r[0]
}
func (q Deque) Back() int {
if len(q.r) > 0 {
return q.r[len(q.r)-1]
}
return q.l[0]
}
func (q Deque) Get(i int) int {
if i < len(q.l) {
return q.l[len(q.l)-1-i]
}
return q.r[i-len(q.l)]
}
|
class Solution {
public int minimumCoins(int[] prices) {
int n = prices.length;
Deque<Integer> q = new ArrayDeque<>();
for (int i = n; i > 0; --i) {
while (!q.isEmpty() && q.peek() > i * 2 + 1) {
q.poll();
}
if (i <= (n - 1) / 2) {
prices[i - 1] += prices[q.peek() - 1];
}
while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) {
q.pollLast();
}
q.offer(i);
}
return prices[0];
}
}
| null | null | null | null | null | null |
class Solution:
def minimumCoins(self, prices: List[int]) -> int:
n = len(prices)
q = deque()
for i in range(n, 0, -1):
while q and q[0] > i * 2 + 1:
q.popleft()
if i <= (n - 1) // 2:
prices[i - 1] += prices[q[0] - 1]
while q and prices[q[-1] - 1] >= prices[i - 1]:
q.pop()
q.append(i)
return prices[0]
| null | null | null | null | null |
function minimumCoins(prices: number[]): number {
const n = prices.length;
const q = new Deque<number>();
for (let i = n; i; --i) {
while (q.getSize() && q.frontValue()! > i * 2 + 1) {
q.popFront();
}
if (i <= (n - 1) >> 1) {
prices[i - 1] += prices[q.frontValue()! - 1];
}
while (q.getSize() && prices[q.backValue()! - 1] >= prices[i - 1]) {
q.popBack();
}
q.pushBack(i);
}
return prices[0];
}
class Node<T> {
value: T;
next: Node<T> | null;
prev: Node<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
this.prev = null;
}
}
class Deque<T> {
private front: Node<T> | null;
private back: Node<T> | null;
private size: number;
constructor() {
this.front = null;
this.back = null;
this.size = 0;
}
pushFront(val: T): void {
const newNode = new Node(val);
if (this.isEmpty()) {
this.front = newNode;
this.back = newNode;
} else {
newNode.next = this.front;
this.front!.prev = newNode;
this.front = newNode;
}
this.size++;
}
pushBack(val: T): void {
const newNode = new Node(val);
if (this.isEmpty()) {
this.front = newNode;
this.back = newNode;
} else {
newNode.prev = this.back;
this.back!.next = newNode;
this.back = newNode;
}
this.size++;
}
popFront(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
const value = this.front!.value;
this.front = this.front!.next;
if (this.front !== null) {
this.front.prev = null;
} else {
this.back = null;
}
this.size--;
return value;
}
popBack(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
const value = this.back!.value;
this.back = this.back!.prev;
if (this.back !== null) {
this.back.next = null;
} else {
this.front = null;
}
this.size--;
return value;
}
frontValue(): T | undefined {
return this.front?.value;
}
backValue(): T | undefined {
return this.back?.value;
}
getSize(): number {
return this.size;
}
isEmpty(): boolean {
return this.size === 0;
}
}
|
Minimum Operations to Make Subarray Elements Equal 🔒
|
You are given an integer array
nums
and an integer
k
. You can perform the following operation any number of times:
Increase or decrease any element of
nums
by 1.
Return the
minimum
number of operations required to ensure that
at least
one
subarray
of size
k
in
nums
has all elements equal.
Example 1:
Input:
nums = [4,-3,2,1,-4,6], k = 3
Output:
5
Explanation:
Use 4 operations to add 4 to
nums[1]
. The resulting array is
[4, 1, 2, 1, -4, 6]
.
Use 1 operation to subtract 1 from
nums[2]
. The resulting array is
[4, 1, 1, 1, -4, 6]
.
The array now contains a subarray
[1, 1, 1]
of size
k = 3
with all elements equal. Hence, the answer is 5.
Example 2:
Input:
nums = [-2,-2,3,1,4], k = 2
Output:
0
Explanation:
The subarray
[-2, -2]
of size
k = 2
already contains all equal elements, so no operations are needed. Hence, the answer is 0.
Constraints:
2 <= nums.length <= 10
5
-10
6
<= nums[i] <= 10
6
2 <= k <= nums.length
| null | null |
class Solution {
public:
long long minOperations(vector<int>& nums, int k) {
multiset<int> l, r;
long long s1 = 0, s2 = 0, ans = 1e18;
for (int i = 0; i < nums.size(); ++i) {
l.insert(nums[i]);
s1 += nums[i];
int y = *l.rbegin();
l.erase(l.find(y));
s1 -= y;
r.insert(y);
s2 += y;
if (r.size() - l.size() > 1) {
y = *r.begin();
r.erase(r.find(y));
s2 -= y;
l.insert(y);
s1 += y;
}
if (i >= k - 1) {
long long x = *r.begin();
ans = min(ans, s2 - x * (int) r.size() + x * (int) l.size() - s1);
int j = i - k + 1;
if (r.contains(nums[j])) {
r.erase(r.find(nums[j]));
s2 -= nums[j];
} else {
l.erase(l.find(nums[j]));
s1 -= nums[j];
}
}
}
return ans;
}
};
| null | null |
func minOperations(nums []int, k int) int64 {
l := redblacktree.New[int, int]()
r := redblacktree.New[int, int]()
merge := func(st *redblacktree.Tree[int, int], x, v int) {
c, _ := st.Get(x)
if c+v == 0 {
st.Remove(x)
} else {
st.Put(x, c+v)
}
}
var s1, s2, sz1, sz2 int
ans := math.MaxInt64
for i, x := range nums {
merge(l, x, 1)
s1 += x
y := l.Right().Key
merge(l, y, -1)
s1 -= y
merge(r, y, 1)
s2 += y
sz2++
if sz2-sz1 > 1 {
y = r.Left().Key
merge(r, y, -1)
s2 -= y
sz2--
merge(l, y, 1)
s1 += y
sz1++
}
if j := i - k + 1; j >= 0 {
ans = min(ans, s2-r.Left().Key*sz2+r.Left().Key*sz1-s1)
if _, ok := r.Get(nums[j]); ok {
merge(r, nums[j], -1)
s2 -= nums[j]
sz2--
} else {
merge(l, nums[j], -1)
s1 -= nums[j]
sz1--
}
}
}
return int64(ans)
}
|
class Solution {
public long minOperations(int[] nums, int k) {
TreeMap<Integer, Integer> l = new TreeMap<>();
TreeMap<Integer, Integer> r = new TreeMap<>();
long s1 = 0, s2 = 0;
int sz1 = 0, sz2 = 0;
long ans = Long.MAX_VALUE;
for (int i = 0; i < nums.length; ++i) {
l.merge(nums[i], 1, Integer::sum);
s1 += nums[i];
++sz1;
int y = l.lastKey();
if (l.merge(y, -1, Integer::sum) == 0) {
l.remove(y);
}
s1 -= y;
--sz1;
r.merge(y, 1, Integer::sum);
s2 += y;
++sz2;
if (sz2 - sz1 > 1) {
y = r.firstKey();
if (r.merge(y, -1, Integer::sum) == 0) {
r.remove(y);
}
s2 -= y;
--sz2;
l.merge(y, 1, Integer::sum);
s1 += y;
++sz1;
}
if (i >= k - 1) {
ans = Math.min(ans, s2 - r.firstKey() * sz2 + r.firstKey() * sz1 - s1);
int j = i - k + 1;
if (r.containsKey(nums[j])) {
if (r.merge(nums[j], -1, Integer::sum) == 0) {
r.remove(nums[j]);
}
s2 -= nums[j];
--sz2;
} else {
if (l.merge(nums[j], -1, Integer::sum) == 0) {
l.remove(nums[j]);
}
s1 -= nums[j];
--sz1;
}
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
l = SortedList()
r = SortedList()
s1 = s2 = 0
ans = inf
for i, x in enumerate(nums):
l.add(x)
s1 += x
y = l.pop()
s1 -= y
r.add(y)
s2 += y
if len(r) - len(l) > 1:
y = r.pop(0)
s2 -= y
l.add(y)
s1 += y
if i >= k - 1:
ans = min(ans, s2 - r[0] * len(r) + r[0] * len(l) - s1)
j = i - k + 1
if nums[j] in r:
r.remove(nums[j])
s2 -= nums[j]
else:
l.remove(nums[j])
s1 -= nums[j]
return ans
| null | null | null | null | null | null |
Valid Phone Numbers
|
Given a text file
file.txt
that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
You may also assume each line in the text file must not contain leading or trailing white spaces.
Example:
Assume that
file.txt
has the following content:
987-123-4567
123 456 7890
(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Read from the file file.txt and output all valid phone numbers to stdout.
awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
| null | null |
N-ary Tree Postorder Traversal
|
Given the
root
of an n-ary tree, return
the postorder traversal of its nodes' values
.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input:
root = [1,null,3,2,4,null,5,6]
Output:
[5,6,3,2,4,1]
Example 2:
Input:
root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output:
[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
Constraints:
The number of nodes in the tree is in the range
[0, 10
4
]
.
0 <= Node.val <= 10
4
The height of the n-ary tree is less than or equal to
1000
.
Follow up:
Recursive solution is trivial, could you do it iteratively?
| null | null |
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> ans;
if (!root) {
return ans;
}
stack<Node*> stk{{root}};
while (!stk.empty()) {
root = stk.top();
ans.push_back(root->val);
stk.pop();
for (Node* child : root->children) {
stk.push(child);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};
| null | null |
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
func postorder(root *Node) []int {
var ans []int
if root == nil {
return ans
}
stk := []*Node{root}
for len(stk) > 0 {
root = stk[len(stk)-1]
stk = stk[:len(stk)-1]
ans = append([]int{root.Val}, ans...)
for _, child := range root.Children {
stk = append(stk, child)
}
}
return ans
}
|
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Deque<Node> stk = new ArrayDeque<>();
stk.offer(root);
while (!stk.isEmpty()) {
root = stk.pollLast();
ans.addFirst(root.val);
for (Node child : root.children) {
stk.offer(child);
}
}
return ans;
}
}
| null | null | null | null | null | null |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
ans = []
if root is None:
return ans
stk = [root]
while stk:
node = stk.pop()
ans.append(node.val)
for child in node.children:
stk.append(child)
return ans[::-1]
| null | null | null | null | null |
/**
* Definition for node.
* class Node {
* val: number
* children: Node[]
* constructor(val?: number) {
* this.val = (val===undefined ? 0 : val)
* this.children = []
* }
* }
*/
function postorder(root: Node | null): number[] {
const ans: number[] = [];
if (!root) {
return ans;
}
const stk: Node[] = [root];
while (stk.length) {
const { val, children } = stk.pop()!;
ans.push(val);
stk.push(...children);
}
return ans.reverse();
}
|
Array Prototype Last
|
Write code that enhances all arrays such that you can call the
array.last()
method on any array and it will return the last element. If there are no elements in the array, it should return
-1
.
You may assume the array is the output of
JSON.parse
.
Example 1:
Input:
nums = [null, {}, 3]
Output:
3
Explanation:
Calling nums.last() should return the last element: 3.
Example 2:
Input:
nums = []
Output:
-1
Explanation:
Because there are no elements, return -1.
Constraints:
arr
is a valid JSON array
0 <= arr.length <= 1000
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
declare global {
interface Array<T> {
last(): T | -1;
}
}
Array.prototype.last = function () {
return this.length ? this.at(-1) : -1;
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
export {};
|
Count Substrings With K-Frequency Characters II 🔒
|
Given a string
s
and an integer
k
, return the total number of
substrings
of
s
where
at least one
character appears
at least
k
times.
Example 1:
Input:
s = "abacb", k = 2
Output:
4
Explanation:
The valid substrings are:
"
aba"
(character
'a'
appears 2 times).
"abac"
(character
'a'
appears 2 times).
"abacb"
(character
'a'
appears 2 times).
"bacb"
(character
'b'
appears 2 times).
Example 2:
Input:
s = "abcde", k = 1
Output:
15
Explanation:
All substrings are valid because every character appears at least once.
Constraints:
1 <= s.length <= 3 * 10
5
1 <= k <= s.length
s
consists only of lowercase English letters.
| null | null |
class Solution {
public:
long long numberOfSubstrings(string s, int k) {
int n = s.size();
long long ans = 0, l = 0;
int cnt[26]{};
for (char& c : s) {
++cnt[c - 'a'];
while (cnt[c - 'a'] >= k) {
--cnt[s[l++] - 'a'];
}
ans += l;
}
return ans;
}
};
| null | null |
func numberOfSubstrings(s string, k int) (ans int64) {
l := 0
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
for cnt[c-'a'] >= k {
cnt[s[l]-'a']--
l++
}
ans += int64(l)
}
return
}
|
class Solution {
public long numberOfSubstrings(String s, int k) {
int[] cnt = new int[26];
long ans = 0;
for (int l = 0, r = 0; r < s.length(); ++r) {
int c = s.charAt(r) - 'a';
++cnt[c];
while (cnt[c] >= k) {
--cnt[s.charAt(l) - 'a'];
l++;
}
ans += l;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfSubstrings(self, s: str, k: int) -> int:
cnt = Counter()
ans = l = 0
for c in s:
cnt[c] += 1
while cnt[c] >= k:
cnt[s[l]] -= 1
l += 1
ans += l
return ans
| null | null | null | null | null |
function numberOfSubstrings(s: string, k: number): number {
let [ans, l] = [0, 0];
const cnt: number[] = Array(26).fill(0);
for (const c of s) {
const x = c.charCodeAt(0) - 97;
++cnt[x];
while (cnt[x] >= k) {
--cnt[s[l++].charCodeAt(0) - 97];
}
ans += l;
}
return ans;
}
|
Sort Array by Moving Items to Empty Space 🔒
|
You are given an integer array
nums
of size
n
containing
each
element from
0
to
n - 1
(
inclusive
). Each of the elements from
1
to
n - 1
represents an item, and the element
0
represents an empty space.
In one operation, you can move
any
item to the empty space.
nums
is considered to be sorted if the numbers of all the items are in
ascending
order and the empty space is either at the beginning or at the end of the array.
For example, if
n = 4
,
nums
is sorted if:
nums = [0,1,2,3]
or
nums = [1,2,3,0]
...and considered to be unsorted otherwise.
Return
the
minimum
number of operations needed to sort
nums
.
Example 1:
Input:
nums = [4,2,0,3,1]
Output:
3
Explanation:
- Move item 2 to the empty space. Now, nums = [4,0,2,3,1].
- Move item 1 to the empty space. Now, nums = [4,1,2,3,0].
- Move item 4 to the empty space. Now, nums = [0,1,2,3,4].
It can be proven that 3 is the minimum number of operations needed.
Example 2:
Input:
nums = [1,2,3,4,0]
Output:
0
Explanation:
nums is already sorted so return 0.
Example 3:
Input:
nums = [1,0,2,4,3]
Output:
2
Explanation:
- Move item 2 to the empty space. Now, nums = [1,2,0,4,3].
- Move item 3 to the empty space. Now, nums = [1,2,3,4,0].
It can be proven that 2 is the minimum number of operations needed.
Constraints:
n == nums.length
2 <= n <= 10
5
0 <= nums[i] < n
All the values of
nums
are
unique
.
| null | null |
class Solution {
public:
int sortArray(vector<int>& nums) {
int n = nums.size();
auto f = [&](vector<int>& nums, int k) {
vector<bool> vis(n);
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (i == nums[i] || vis[i]) continue;
int j = i;
++cnt;
while (!vis[j]) {
vis[j] = true;
++cnt;
j = nums[j];
}
}
if (nums[k] != k) cnt -= 2;
return cnt;
};
int a = f(nums, 0);
vector<int> arr = nums;
for (int& v : arr) v = (v - 1 + n) % n;
int b = f(arr, n - 1);
return min(a, b);
}
};
| null | null |
func sortArray(nums []int) int {
n := len(nums)
f := func(nums []int, k int) int {
vis := make([]bool, n)
cnt := 0
for i, v := range nums {
if i == v || vis[i] {
continue
}
cnt++
j := i
for !vis[j] {
vis[j] = true
cnt++
j = nums[j]
}
}
if nums[k] != k {
cnt -= 2
}
return cnt
}
a := f(nums, 0)
arr := make([]int, n)
for i, v := range nums {
arr[i] = (v - 1 + n) % n
}
b := f(arr, n-1)
return min(a, b)
}
|
class Solution {
public int sortArray(int[] nums) {
int n = nums.length;
int[] arr = new int[n];
for (int i = 0; i < n; ++i) {
arr[i] = (nums[i] - 1 + n) % n;
}
int a = f(nums, 0);
int b = f(arr, n - 1);
return Math.min(a, b);
}
private int f(int[] nums, int k) {
boolean[] vis = new boolean[nums.length];
int cnt = 0;
for (int i = 0; i < nums.length; ++i) {
if (i == nums[i] || vis[i]) {
continue;
}
++cnt;
int j = nums[i];
while (!vis[j]) {
vis[j] = true;
++cnt;
j = nums[j];
}
}
if (nums[k] != k) {
cnt -= 2;
}
return cnt;
}
}
| null | null | null | null | null | null |
class Solution:
def sortArray(self, nums: List[int]) -> int:
def f(nums, k):
vis = [False] * n
cnt = 0
for i, v in enumerate(nums):
if i == v or vis[i]:
continue
cnt += 1
j = i
while not vis[j]:
vis[j] = True
cnt += 1
j = nums[j]
return cnt - 2 * (nums[k] != k)
n = len(nums)
a = f(nums, 0)
b = f([(v - 1 + n) % n for v in nums], n - 1)
return min(a, b)
| null | null | null | null | null | null |
Minimum Operations to Form Subsequence With Target Sum
|
You are given a
0-indexed
array
nums
consisting of
non-negative
powers of
2
, and an integer
target
.
In one operation, you must apply the following changes to the array:
Choose any element of the array
nums[i]
such that
nums[i] > 1
.
Remove
nums[i]
from the array.
Add
two
occurrences of
nums[i] / 2
to the
end
of
nums
.
Return the
minimum number of operations
you need to perform so that
nums
contains a
subsequence
whose elements sum to
target
. If it is impossible to obtain such a subsequence, return
-1
.
A
subsequence
is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input:
nums = [1,2,8], target = 7
Output:
1
Explanation:
In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4].
At this stage, nums contains the subsequence [1,2,4] which sums up to 7.
It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7.
Example 2:
Input:
nums = [1,32,1,2], target = 12
Output:
2
Explanation:
In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16].
In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8]
At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12.
It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.
Example 3:
Input:
nums = [1,32,1], target = 35
Output:
-1
Explanation:
It can be shown that no sequence of operations results in a subsequence that sums up to 35.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 2
30
nums
consists only of non-negative powers of two.
1 <= target < 2
31
| null | null |
class Solution {
public:
int minOperations(vector<int>& nums, int target) {
long long s = 0;
int cnt[32]{};
for (int x : nums) {
s += x;
for (int i = 0; i < 32; ++i) {
if (x >> i & 1) {
++cnt[i];
}
}
}
if (s < target) {
return -1;
}
int i = 0, j = 0;
int ans = 0;
while (1) {
while (i < 32 && (target >> i & 1) == 0) {
++i;
}
if (i == 32) {
return ans;
}
while (j < i) {
cnt[j + 1] += cnt[j] / 2;
cnt[j] %= 2;
++j;
}
while (cnt[j] == 0) {
cnt[j] = 1;
++j;
}
ans += j - i;
--cnt[j];
j = i;
++i;
}
}
};
| null | null |
func minOperations(nums []int, target int) (ans int) {
s := 0
cnt := [32]int{}
for _, x := range nums {
s += x
for i := 0; i < 32; i++ {
if x>>i&1 > 0 {
cnt[i]++
}
}
}
if s < target {
return -1
}
var i, j int
for {
for i < 32 && target>>i&1 == 0 {
i++
}
if i == 32 {
return
}
for j < i {
cnt[j+1] += cnt[j] >> 1
cnt[j] %= 2
j++
}
for cnt[j] == 0 {
cnt[j] = 1
j++
}
ans += j - i
cnt[j]--
j = i
i++
}
}
|
class Solution {
public int minOperations(List<Integer> nums, int target) {
long s = 0;
int[] cnt = new int[32];
for (int x : nums) {
s += x;
for (int i = 0; i < 32; ++i) {
if ((x >> i & 1) == 1) {
++cnt[i];
}
}
}
if (s < target) {
return -1;
}
int i = 0, j = 0;
int ans = 0;
while (true) {
while (i < 32 && (target >> i & 1) == 0) {
++i;
}
if (i == 32) {
return ans;
}
while (j < i) {
cnt[j + 1] += cnt[j] / 2;
cnt[j] %= 2;
++j;
}
while (cnt[j] == 0) {
cnt[j] = 1;
++j;
}
ans += j - i;
--cnt[j];
j = i;
++i;
}
}
}
| null | null | null | null | null | null |
class Solution:
def minOperations(self, nums: List[int], target: int) -> int:
s = sum(nums)
if s < target:
return -1
cnt = [0] * 32
for x in nums:
for i in range(32):
if x >> i & 1:
cnt[i] += 1
i = j = 0
ans = 0
while 1:
while i < 32 and (target >> i & 1) == 0:
i += 1
if i == 32:
break
while j < i:
cnt[j + 1] += cnt[j] // 2
cnt[j] %= 2
j += 1
while cnt[j] == 0:
cnt[j] = 1
j += 1
ans += j - i
cnt[j] -= 1
j = i
i += 1
return ans
| null | null | null | null | null |
function minOperations(nums: number[], target: number): number {
let s = 0;
const cnt: number[] = Array(32).fill(0);
for (const x of nums) {
s += x;
for (let i = 0; i < 32; ++i) {
if ((x >> i) & 1) {
++cnt[i];
}
}
}
if (s < target) {
return -1;
}
let [ans, i, j] = [0, 0, 0];
while (1) {
while (i < 32 && ((target >> i) & 1) === 0) {
++i;
}
if (i === 32) {
return ans;
}
while (j < i) {
cnt[j + 1] += cnt[j] >> 1;
cnt[j] %= 2;
++j;
}
while (cnt[j] == 0) {
cnt[j] = 1;
j++;
}
ans += j - i;
cnt[j]--;
j = i;
i++;
}
}
|
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
|
Given two arrays of integers
nums1
and
nums2
, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if
nums1[i]
2
== nums2[j] * nums2[k]
where
0 <= i < nums1.length
and
0 <= j < k < nums2.length
.
Type 2: Triplet (i, j, k) if
nums2[i]
2
== nums1[j] * nums1[k]
where
0 <= i < nums2.length
and
0 <= j < k < nums1.length
.
Example 1:
Input:
nums1 = [7,4], nums2 = [5,2,8,9]
Output:
1
Explanation:
Type 1: (1, 1, 2), nums1[1]
2
= nums2[1] * nums2[2]. (4
2
= 2 * 8).
Example 2:
Input:
nums1 = [1,1], nums2 = [1,1,1]
Output:
9
Explanation:
All Triplets are valid, because 1
2
= 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]
2
= nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]
2
= nums1[j] * nums1[k].
Example 3:
Input:
nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output:
2
Explanation:
There are 2 valid triplets.
Type 1: (3,0,2). nums1[3]
2
= nums2[0] * nums2[2].
Type 2: (3,0,1). nums2[3]
2
= nums1[0] * nums1[1].
Constraints:
1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 10
5
| null | null |
class Solution {
public:
int numTriplets(vector<int>& nums1, vector<int>& nums2) {
auto cnt1 = count(nums1);
auto cnt2 = count(nums2);
return cal(cnt1, nums2) + cal(cnt2, nums1);
}
unordered_map<long long, int> count(vector<int>& nums) {
unordered_map<long long, int> cnt;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
cnt[(long long) nums[i] * nums[j]]++;
}
}
return cnt;
}
int cal(unordered_map<long long, int>& cnt, vector<int>& nums) {
int ans = 0;
for (int x : nums) {
ans += cnt[(long long) x * x];
}
return ans;
}
};
| null | null |
func numTriplets(nums1 []int, nums2 []int) int {
cnt1 := count(nums1)
cnt2 := count(nums2)
return cal(cnt1, nums2) + cal(cnt2, nums1)
}
func count(nums []int) map[int]int {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
return cnt
}
func cal(cnt map[int]int, nums []int) (ans int) {
for _, x := range nums {
for y, v1 := range cnt {
z := x * x / y
if y*z == x*x {
if v2, ok := cnt[z]; ok {
if y == z {
v2--
}
ans += v1 * v2
}
}
}
}
ans /= 2
return
}
|
class Solution {
public int numTriplets(int[] nums1, int[] nums2) {
var cnt1 = count(nums1);
var cnt2 = count(nums2);
return cal(cnt1, nums2) + cal(cnt2, nums1);
}
private Map<Integer, Integer> count(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
return cnt;
}
private int cal(Map<Integer, Integer> cnt, int[] nums) {
long ans = 0;
for (int x : nums) {
for (var e : cnt.entrySet()) {
int y = e.getKey(), v1 = e.getValue();
int z = (int) (1L * x * x / y);
if (y * z == x * x) {
int v2 = cnt.getOrDefault(z, 0);
ans += v1 * (y == z ? v2 - 1 : v2);
}
}
}
return (int) (ans / 2);
}
}
| null | null | null | null | null | null |
class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
def cal(nums: List[int], cnt: Counter) -> int:
ans = 0
for x in nums:
for y, v1 in cnt.items():
z = x * x // y
if y * z == x * x:
v2 = cnt[z]
ans += v1 * (v2 - int(y == z))
return ans // 2
cnt1 = Counter(nums1)
cnt2 = Counter(nums2)
return cal(nums1, cnt2) + cal(nums2, cnt1)
| null | null | null | null | null |
function numTriplets(nums1: number[], nums2: number[]): number {
const cnt1 = count(nums1);
const cnt2 = count(nums2);
return cal(cnt1, nums2) + cal(cnt2, nums1);
}
function count(nums: number[]): Map<number, number> {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
return cnt;
}
function cal(cnt: Map<number, number>, nums: number[]): number {
let ans: number = 0;
for (const x of nums) {
for (const [y, v1] of cnt) {
const z = Math.floor((x * x) / y);
if (y * z == x * x) {
const v2 = cnt.get(z) || 0;
ans += v1 * (y === z ? v2 - 1 : v2);
}
}
}
return ans / 2;
}
|
Shifting Letters II
|
You are given a string
s
of lowercase English letters and a 2D integer array
shifts
where
shifts[i] = [start
i
, end
i
, direction
i
]
. For every
i
,
shift
the characters in
s
from the index
start
i
to the index
end
i
(
inclusive
) forward if
direction
i
= 1
, or shift the characters backward if
direction
i
= 0
.
Shifting a character
forward
means replacing it with the
next
letter in the alphabet (wrapping around so that
'z'
becomes
'a'
). Similarly, shifting a character
backward
means replacing it with the
previous
letter in the alphabet (wrapping around so that
'a'
becomes
'z'
).
Return
the final string after all such shifts to
s
are applied
.
Example 1:
Input:
s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
Output:
"ace"
Explanation:
Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".
Example 2:
Input:
s = "dztz", shifts = [[0,0,0],[1,1,1]]
Output:
"catz"
Explanation:
Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".
Constraints:
1 <= s.length, shifts.length <= 5 * 10
4
shifts[i].length == 3
0 <= start
i
<= end
i
< s.length
0 <= direction
i
<= 1
s
consists of lowercase English letters.
| null | null |
class Solution {
public:
string shiftingLetters(string s, vector<vector<int>>& shifts) {
int n = s.size();
vector<int> d(n + 1);
for (auto& e : shifts) {
if (e[2] == 0) {
e[2]--;
}
d[e[0]] += e[2];
d[e[1] + 1] -= e[2];
}
for (int i = 1; i <= n; ++i) {
d[i] += d[i - 1];
}
string ans;
for (int i = 0; i < n; ++i) {
int j = (s[i] - 'a' + d[i] % 26 + 26) % 26;
ans += ('a' + j);
}
return ans;
}
};
| null | null |
func shiftingLetters(s string, shifts [][]int) string {
n := len(s)
d := make([]int, n+1)
for _, e := range shifts {
if e[2] == 0 {
e[2]--
}
d[e[0]] += e[2]
d[e[1]+1] -= e[2]
}
for i := 1; i <= n; i++ {
d[i] += d[i-1]
}
ans := []byte{}
for i, c := range s {
j := (int(c-'a') + d[i]%26 + 26) % 26
ans = append(ans, byte('a'+j))
}
return string(ans)
}
|
class Solution {
public String shiftingLetters(String s, int[][] shifts) {
int n = s.length();
int[] d = new int[n + 1];
for (int[] e : shifts) {
if (e[2] == 0) {
e[2]--;
}
d[e[0]] += e[2];
d[e[1] + 1] -= e[2];
}
for (int i = 1; i <= n; ++i) {
d[i] += d[i - 1];
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n; ++i) {
int j = (s.charAt(i) - 'a' + d[i] % 26 + 26) % 26;
ans.append((char) ('a' + j));
}
return ans.toString();
}
}
| null | null | null | null | null | null |
class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
n = len(s)
d = [0] * (n + 1)
for i, j, v in shifts:
if v == 0:
v = -1
d[i] += v
d[j + 1] -= v
for i in range(1, n + 1):
d[i] += d[i - 1]
return ''.join(
chr(ord('a') + (ord(s[i]) - ord('a') + d[i] + 26) % 26) for i in range(n)
)
| null | null | null | null | null |
function shiftingLetters(s: string, shifts: number[][]): string {
const n: number = s.length;
const d: number[] = new Array(n + 1).fill(0);
for (let [i, j, v] of shifts) {
if (v === 0) {
v--;
}
d[i] += v;
d[j + 1] -= v;
}
for (let i = 1; i <= n; ++i) {
d[i] += d[i - 1];
}
let ans: string = '';
for (let i = 0; i < n; ++i) {
const j = (s.charCodeAt(i) - 'a'.charCodeAt(0) + (d[i] % 26) + 26) % 26;
ans += String.fromCharCode('a'.charCodeAt(0) + j);
}
return ans;
}
|
Apply Transform Over Each Element in Array
|
Given an integer array
arr
and a mapping function
fn
, return a new array with a transformation applied to each element.
The returned array should be created such that
returnedArray[i] = fn(arr[i], i)
.
Please solve it without the built-in
Array.map
method.
Example 1:
Input:
arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output:
[2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one.
Example 2:
Input:
arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output:
[1,3,5]
Explanation:
The function increases each value by the index it resides in.
Example 3:
Input:
arr = [10,20,30], fn = function constant() { return 42; }
Output:
[42,42,42]
Explanation:
The function always returns 42.
Constraints:
0 <= arr.length <= 1000
-10
9
<= arr[i] <= 10
9
fn
returns an integer.
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
function map(arr: number[], fn: (n: number, i: number) => number): number[] {
for (let i = 0; i < arr.length; ++i) {
arr[i] = fn(arr[i], i);
}
return arr;
}
|
Check if Strings Can be Made Equal With Operations I
|
You are given two strings
s1
and
s2
, both of length
4
, consisting of
lowercase
English letters.
You can apply the following operation on any of the two strings
any
number of times:
Choose any two indices
i
and
j
such that
j - i = 2
, then
swap
the two characters at those indices in the string.
Return
true
if you can make the strings
s1
and
s2
equal, and
false
otherwise
.
Example 1:
Input:
s1 = "abcd", s2 = "cdab"
Output:
true
Explanation:
We can do the following operations on s1:
- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad".
- Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2.
Example 2:
Input:
s1 = "abcd", s2 = "dacb"
Output:
false
Explanation:
It is not possible to make the two strings equal.
Constraints:
s1.length == s2.length == 4
s1
and
s2
consist only of lowercase English letters.
| null | null |
class Solution {
public:
bool canBeEqual(string s1, string s2) {
vector<vector<int>> cnt(2, vector<int>(26, 0));
for (int i = 0; i < s1.size(); ++i) {
++cnt[i & 1][s1[i] - 'a'];
--cnt[i & 1][s2[i] - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (cnt[0][i] || cnt[1][i]) {
return false;
}
}
return true;
}
};
| null | null |
func canBeEqual(s1 string, s2 string) bool {
cnt := [2][26]int{}
for i := 0; i < len(s1); i++ {
cnt[i&1][s1[i]-'a']++
cnt[i&1][s2[i]-'a']--
}
for i := 0; i < 26; i++ {
if cnt[0][i] != 0 || cnt[1][i] != 0 {
return false
}
}
return true
}
|
class Solution {
public boolean canBeEqual(String s1, String s2) {
int[][] cnt = new int[2][26];
for (int i = 0; i < s1.length(); ++i) {
++cnt[i & 1][s1.charAt(i) - 'a'];
--cnt[i & 1][s2.charAt(i) - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (cnt[0][i] != 0 || cnt[1][i] != 0) {
return false;
}
}
return true;
}
}
| null | null | null | null | null | null |
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted(
s2[1::2]
)
| null | null | null | null | null |
function canBeEqual(s1: string, s2: string): boolean {
const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0));
for (let i = 0; i < s1.length; ++i) {
++cnt[i & 1][s1.charCodeAt(i) - 97];
--cnt[i & 1][s2.charCodeAt(i) - 97];
}
for (let i = 0; i < 26; ++i) {
if (cnt[0][i] || cnt[1][i]) {
return false;
}
}
return true;
}
|
Number of Substrings Containing All Three Characters
|
Given a string
s
consisting only of characters
a
,
b
and
c
.
Return the number of substrings containing
at least
one occurrence of all these characters
a
,
b
and
c
.
Example 1:
Input:
s = "abcabc"
Output:
10
Explanation:
The substrings containing at least one occurrence of the characters
a
,
b
and
c are "
abc
", "
abca
", "
abcab
", "
abcabc
", "
bca
", "
bcab
", "
bcabc
", "
cab
", "
cabc
"
and
"
abc
"
(
again
)
.
Example 2:
Input:
s = "aaacb"
Output:
3
Explanation:
The substrings containing at least one occurrence of the characters
a
,
b
and
c are "
aaacb
", "
aacb
"
and
"
acb
".
Example 3:
Input:
s = "abc"
Output:
1
Constraints:
3 <= s.length <= 5 x 10^4
s
only consists of
a
,
b
or
c
characters.
| null | null |
class Solution {
public:
int numberOfSubstrings(string s) {
int d[3] = {-1, -1, -1};
int ans = 0;
for (int i = 0; i < s.size(); ++i) {
d[s[i] - 'a'] = i;
ans += min(d[0], min(d[1], d[2])) + 1;
}
return ans;
}
};
| null | null |
func numberOfSubstrings(s string) (ans int) {
d := [3]int{-1, -1, -1}
for i, c := range s {
d[c-'a'] = i
ans += min(d[0], min(d[1], d[2])) + 1
}
return
}
|
class Solution {
public int numberOfSubstrings(String s) {
int[] d = new int[] {-1, -1, -1};
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
d[c - 'a'] = i;
ans += Math.min(d[0], Math.min(d[1], d[2])) + 1;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfSubstrings(self, s: str) -> int:
d = {"a": -1, "b": -1, "c": -1}
ans = 0
for i, c in enumerate(s):
d[c] = i
ans += min(d["a"], d["b"], d["c"]) + 1
return ans
| null | null | null | null | null | null |
Find the K-th Character in String Game I
|
Alice and Bob are playing a game. Initially, Alice has a string
word = "a"
.
You are given a
positive
integer
k
.
Now Bob will ask Alice to perform the following operation
forever
:
Generate a new string by
changing
each character in
word
to its
next
character in the English alphabet, and
append
it to the
original
word
.
For example, performing the operation on
"c"
generates
"cd"
and performing the operation on
"zb"
generates
"zbac"
.
Return the value of the
k
th
character in
word
, after enough operations have been done for
word
to have
at least
k
characters.
Example 1:
Input:
k = 5
Output:
"b"
Explanation:
Initially,
word = "a"
. We need to do the operation three times:
Generated string is
"b"
,
word
becomes
"ab"
.
Generated string is
"bc"
,
word
becomes
"abbc"
.
Generated string is
"bccd"
,
word
becomes
"abbcbccd"
.
Example 2:
Input:
k = 10
Output:
"c"
Constraints:
1 <= k <= 500
| null | null |
class Solution {
public:
char kthCharacter(int k) {
vector<int> word;
word.push_back(0);
while (word.size() < k) {
int m = word.size();
for (int i = 0; i < m; ++i) {
word.push_back((word[i] + 1) % 26);
}
}
return 'a' + word[k - 1];
}
};
| null | null |
func kthCharacter(k int) byte {
word := []int{0}
for len(word) < k {
m := len(word)
for i := 0; i < m; i++ {
word = append(word, (word[i]+1)%26)
}
}
return 'a' + byte(word[k-1])
}
|
class Solution {
public char kthCharacter(int k) {
List<Integer> word = new ArrayList<>();
word.add(0);
while (word.size() < k) {
for (int i = 0, m = word.size(); i < m; ++i) {
word.add((word.get(i) + 1) % 26);
}
}
return (char) ('a' + word.get(k - 1));
}
}
| null | null | null | null | null | null |
class Solution:
def kthCharacter(self, k: int) -> str:
word = [0]
while len(word) < k:
word.extend([(x + 1) % 26 for x in word])
return chr(ord("a") + word[k - 1])
| null |
impl Solution {
pub fn kth_character(k: i32) -> char {
let mut word = vec![0];
while word.len() < k as usize {
let m = word.len();
for i in 0..m {
word.push((word[i] + 1) % 26);
}
}
(b'a' + word[(k - 1) as usize] as u8) as char
}
}
| null | null | null |
function kthCharacter(k: number): string {
const word: number[] = [0];
while (word.length < k) {
word.push(...word.map(x => (x + 1) % 26));
}
return String.fromCharCode(97 + word[k - 1]);
}
|
Zero Array Transformation IV
|
You are given an integer array
nums
of length
n
and a 2D array
queries
, where
queries[i] = [l
i
, r
i
, val
i
]
.
Each
queries[i]
represents the following action on
nums
:
Select a
subset
of indices in the range
[l
i
, r
i
]
from
nums
.
Decrement the value at each selected index by
exactly
val
i
.
A
Zero Array
is an array with all its elements equal to 0.
Return the
minimum
possible
non-negative
value of
k
, such that after processing the first
k
queries in
sequence
,
nums
becomes a
Zero Array
. If no such
k
exists, return -1.
Example 1:
Input:
nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]
Output:
2
Explanation:
For query 0 (l = 0, r = 2, val = 1):
Decrement the values at indices
[0, 2]
by 1.
The array will become
[1, 0, 1]
.
For query 1 (l = 0, r = 2, val = 1):
Decrement the values at indices
[0, 2]
by 1.
The array will become
[0, 0, 0]
, which is a Zero Array. Therefore, the minimum value of
k
is 2.
Example 2:
Input:
nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
Output:
-1
Explanation:
It is impossible to make nums a Zero Array even after all the queries.
Example 3:
Input:
nums = [1,2,3,2,1], queries = [[0,1,1],[1,2,1],[2,3,2],[3,4,1],[4,4,1]]
Output:
4
Explanation:
For query 0 (l = 0, r = 1, val = 1):
Decrement the values at indices
[0, 1]
by
1
.
The array will become
[0, 1, 3, 2, 1]
.
For query 1 (l = 1, r = 2, val = 1):
Decrement the values at indices
[1, 2]
by 1.
The array will become
[0, 0, 2, 2, 1]
.
For query 2 (l = 2, r = 3, val = 2):
Decrement the values at indices
[2, 3]
by 2.
The array will become
[0, 0, 0, 0, 1]
.
For query 3 (l = 3, r = 4, val = 1):
Decrement the value at index 4 by 1.
The array will become
[0, 0, 0, 0, 0]
. Therefore, the minimum value of
k
is 4.
Example 4:
Input:
nums = [1,2,3,2,6], queries = [[0,1,1],[0,2,1],[1,4,2],[4,4,4],[3,4,1],[4,4,5]]
Output:
4
Constraints:
1 <= nums.length <= 10
0 <= nums[i] <= 1000
1 <= queries.length <= 1000
queries[i] = [l
i
, r
i
, val
i
]
0 <= l
i
<= r
i
< nums.length
1 <= val
i
<= 10
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Number of Students Doing Homework at a Given Time
|
Given two integer arrays
startTime
and
endTime
and given an integer
queryTime
.
The
ith
student started doing their homework at the time
startTime[i]
and finished it at time
endTime[i]
.
Return
the number of students
doing their homework at time
queryTime
. More formally, return the number of students where
queryTime
lays in the interval
[startTime[i], endTime[i]]
inclusive.
Example 1:
Input:
startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output:
1
Explanation:
We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input:
startTime = [4], endTime = [4], queryTime = 4
Output:
1
Explanation:
The only student was doing their homework at the queryTime.
Constraints:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
|
int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize, int queryTime) {
int ans = 0;
for (int i = 0; i < startTimeSize; i++) {
if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
ans++;
}
}
return ans;
}
| null |
class Solution {
public:
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
int ans = 0;
for (int i = 0; i < startTime.size(); ++i) {
ans += startTime[i] <= queryTime && queryTime <= endTime[i];
}
return ans;
}
};
| null | null |
func busyStudent(startTime []int, endTime []int, queryTime int) (ans int) {
for i, x := range startTime {
if x <= queryTime && queryTime <= endTime[i] {
ans++
}
}
return
}
|
class Solution {
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int ans = 0;
for (int i = 0; i < startTime.length; ++i) {
if (startTime[i] <= queryTime && queryTime <= endTime[i]) {
++ans;
}
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def busyStudent(
self, startTime: List[int], endTime: List[int], queryTime: int
) -> int:
return sum(x <= queryTime <= y for x, y in zip(startTime, endTime))
| null |
impl Solution {
pub fn busy_student(start_time: Vec<i32>, end_time: Vec<i32>, query_time: i32) -> i32 {
let mut ans = 0;
for i in 0..start_time.len() {
if start_time[i] <= query_time && end_time[i] >= query_time {
ans += 1;
}
}
ans
}
}
| null | null | null |
function busyStudent(startTime: number[], endTime: number[], queryTime: number): number {
const n = startTime.length;
let ans = 0;
for (let i = 0; i < n; i++) {
if (startTime[i] <= queryTime && queryTime <= endTime[i]) {
ans++;
}
}
return ans;
}
|
Task Scheduler II
|
You are given a
0-indexed
array of positive integers
tasks
, representing tasks that need to be completed
in order
, where
tasks[i]
represents the
type
of the
i
th
task.
You are also given a positive integer
space
, which represents the
minimum
number of days that must pass
after
the completion of a task before another task of the
same
type can be performed.
Each day, until all tasks have been completed, you must either:
Complete the next task from
tasks
, or
Take a break.
Return
the
minimum
number of days needed to complete all tasks
.
Example 1:
Input:
tasks = [1,2,1,2,3,1], space = 3
Output:
9
Explanation:
One way to complete all tasks in 9 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
Day 7: Take a break.
Day 8: Complete the 4th task.
Day 9: Complete the 5th task.
It can be shown that the tasks cannot be completed in less than 9 days.
Example 2:
Input:
tasks = [5,8,8,5], space = 2
Output:
6
Explanation:
One way to complete all tasks in 6 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
It can be shown that the tasks cannot be completed in less than 6 days.
Constraints:
1 <= tasks.length <= 10
5
1 <= tasks[i] <= 10
9
1 <= space <= tasks.length
| null | null |
class Solution {
public:
long long taskSchedulerII(vector<int>& tasks, int space) {
unordered_map<int, long long> day;
long long ans = 0;
for (int& task : tasks) {
++ans;
ans = max(ans, day[task]);
day[task] = ans + space + 1;
}
return ans;
}
};
| null | null |
func taskSchedulerII(tasks []int, space int) (ans int64) {
day := map[int]int64{}
for _, task := range tasks {
ans++
if ans < day[task] {
ans = day[task]
}
day[task] = ans + int64(space) + 1
}
return
}
|
class Solution {
public long taskSchedulerII(int[] tasks, int space) {
Map<Integer, Long> day = new HashMap<>();
long ans = 0;
for (int task : tasks) {
++ans;
ans = Math.max(ans, day.getOrDefault(task, 0L));
day.put(task, ans + space + 1);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def taskSchedulerII(self, tasks: List[int], space: int) -> int:
day = defaultdict(int)
ans = 0
for task in tasks:
ans += 1
ans = max(ans, day[task])
day[task] = ans + space + 1
return ans
| null | null | null | null | null |
function taskSchedulerII(tasks: number[], space: number): number {
const day = new Map<number, number>();
let ans = 0;
for (const task of tasks) {
++ans;
ans = Math.max(ans, day.get(task) ?? 0);
day.set(task, ans + space + 1);
}
return ans;
}
|
Number of Beautiful Pairs
|
You are given a
0-indexed
integer array
nums
. A pair of indices
i
,
j
where
0 <= i < j < nums.length
is called beautiful if the
first digit
of
nums[i]
and the
last digit
of
nums[j]
are
coprime
.
Return
the total number of beautiful pairs in
nums
.
Two integers
x
and
y
are
coprime
if there is no integer greater than 1 that divides both of them. In other words,
x
and
y
are coprime if
gcd(x, y) == 1
, where
gcd(x, y)
is the
greatest common divisor
of
x
and
y
.
Example 1:
Input:
nums = [2,5,1,4]
Output:
5
Explanation:
There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
Example 2:
Input:
nums = [11,21,12]
Output:
2
Explanation:
There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
Constraints:
2 <= nums.length <= 100
1 <= nums[i] <= 9999
nums[i] % 10 != 0
| null | null |
class Solution {
public:
int countBeautifulPairs(vector<int>& nums) {
int cnt[10]{};
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
};
| null | null |
func countBeautifulPairs(nums []int) (ans int) {
cnt := [10]int{}
for _, x := range nums {
for y := 0; y < 10; y++ {
if cnt[y] > 0 && gcd(x%10, y) == 1 {
ans += cnt[y]
}
}
for x > 9 {
x /= 10
}
cnt[x]++
}
return
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
class Solution {
public int countBeautifulPairs(int[] nums) {
int[] cnt = new int[10];
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
| null | null | null | null | null | null |
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
cnt = [0] * 10
ans = 0
for x in nums:
for y in range(10):
if cnt[y] and gcd(x % 10, y) == 1:
ans += cnt[y]
cnt[int(str(x)[0])] += 1
return ans
| null | null | null | null | null |
function countBeautifulPairs(nums: number[]): number {
const cnt: number[] = Array(10).fill(0);
let ans = 0;
for (let x of nums) {
for (let y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) === 1) {
ans += cnt[y];
}
}
while (x > 9) {
x = Math.floor(x / 10);
}
++cnt[x];
}
return ans;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
|
Count Ways To Build Good Strings
|
Given the integers
zero
,
one
,
low
, and
high
, we can construct a string by starting with an empty string, and then at each step perform either of the following:
Append the character
'0'
zero
times.
Append the character
'1'
one
times.
This can be performed any number of times.
A
good
string is a string constructed by the above process having a
length
between
low
and
high
(
inclusive
).
Return
the number of
different
good strings that can be constructed satisfying these properties.
Since the answer can be large, return it
modulo
10
9
+ 7
.
Example 1:
Input:
low = 3, high = 3, zero = 1, one = 1
Output:
8
Explanation:
One possible valid good string is "011".
It can be constructed as follows: "" -> "0" -> "01" -> "011".
All binary strings from "000" to "111" are good strings in this example.
Example 2:
Input:
low = 2, high = 3, zero = 1, one = 2
Output:
5
Explanation:
The good strings are "00", "11", "000", "110", and "011".
Constraints:
1 <= low <= high <= 10
5
1 <= zero, one <= low
| null | null |
class Solution {
public:
const int mod = 1e9 + 7;
int countGoodStrings(int low, int high, int zero, int one) {
vector<int> f(high + 1, -1);
function<int(int)> dfs = [&](int i) -> int {
if (i > high) return 0;
if (f[i] != -1) return f[i];
long ans = i >= low && i <= high;
ans += dfs(i + zero) + dfs(i + one);
ans %= mod;
f[i] = ans;
return ans;
};
return dfs(0);
}
};
| null | null |
func countGoodStrings(low int, high int, zero int, one int) int {
f := make([]int, high+1)
for i := range f {
f[i] = -1
}
const mod int = 1e9 + 7
var dfs func(i int) int
dfs = func(i int) int {
if i > high {
return 0
}
if f[i] != -1 {
return f[i]
}
ans := 0
if i >= low && i <= high {
ans++
}
ans += dfs(i+zero) + dfs(i+one)
ans %= mod
f[i] = ans
return ans
}
return dfs(0)
}
|
class Solution {
private static final int MOD = (int) 1e9 + 7;
private int[] f;
private int lo;
private int hi;
private int zero;
private int one;
public int countGoodStrings(int low, int high, int zero, int one) {
f = new int[high + 1];
Arrays.fill(f, -1);
lo = low;
hi = high;
this.zero = zero;
this.one = one;
return dfs(0);
}
private int dfs(int i) {
if (i > hi) {
return 0;
}
if (f[i] != -1) {
return f[i];
}
long ans = 0;
if (i >= lo && i <= hi) {
++ans;
}
ans += dfs(i + zero) + dfs(i + one);
ans %= MOD;
f[i] = (int) ans;
return f[i];
}
}
|
/**
* @param {number} low
* @param {number} high
* @param {number} zero
* @param {number} one
* @return {number}
*/
function countGoodStrings(low, high, zero, one) {
const mod = 10 ** 9 + 7;
const f = Array(high + 1).fill(0);
f[0] = 1;
for (let i = 1; i <= high; i++) {
if (i >= zero) f[i] += f[i - zero];
if (i >= one) f[i] += f[i - one];
f[i] %= mod;
}
const ans = f.slice(low, high + 1).reduce((acc, cur) => acc + cur, 0);
return ans % mod;
}
| null | null | null | null | null |
class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
@cache
def dfs(i):
if i > high:
return 0
ans = 0
if low <= i <= high:
ans += 1
ans += dfs(i + zero) + dfs(i + one)
return ans % mod
mod = 10**9 + 7
return dfs(0)
| null | null | null | null | null |
function countGoodStrings(low: number, high: number, zero: number, one: number): number {
const mod = 10 ** 9 + 7;
const f: number[] = new Array(high + 1).fill(0);
f[0] = 1;
for (let i = 1; i <= high; i++) {
if (i >= zero) f[i] += f[i - zero];
if (i >= one) f[i] += f[i - one];
f[i] %= mod;
}
const ans = f.slice(low, high + 1).reduce((acc, cur) => acc + cur, 0);
return ans % mod;
}
|
Baseball Game
|
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings
operations
, where
operations[i]
is the
i
th
operation you must apply to the record and is one of the following:
An integer
x
.
Record a new score of
x
.
'+'
.
Record a new score that is the sum of the previous two scores.
'D'
.
Record a new score that is the double of the previous score.
'C'
.
Invalidate the previous score, removing it from the record.
Return
the sum of all the scores on the record after applying all the operations
.
The test cases are generated such that the answer and all intermediate calculations fit in a
32-bit
integer and that all operations are valid.
Example 1:
Input:
ops = ["5","2","C","D","+"]
Output:
30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
Example 2:
Input:
ops = ["5","-2","4","C","D","9","+","+"]
Output:
27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
Example 3:
Input:
ops = ["1","C"]
Output:
0
Explanation:
"1" - Add 1 to the record, record is now [1].
"C" - Invalidate and remove the previous score, record is now [].
Since the record is empty, the total sum is 0.
Constraints:
1 <= operations.length <= 1000
operations[i]
is
"C"
,
"D"
,
"+"
, or a string representing an integer in the range
[-3 * 10
4
, 3 * 10
4
]
.
For operation
"+"
, there will always be at least two previous scores on the record.
For operations
"C"
and
"D"
, there will always be at least one previous score on the record.
| null | null |
class Solution {
public:
int calPoints(vector<string>& operations) {
vector<int> stk;
for (auto& op : operations) {
int n = stk.size();
if (op == "+") {
stk.push_back(stk[n - 1] + stk[n - 2]);
} else if (op == "D") {
stk.push_back(stk[n - 1] << 1);
} else if (op == "C") {
stk.pop_back();
} else {
stk.push_back(stoi(op));
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
| null | null |
func calPoints(operations []string) (ans int) {
var stk []int
for _, op := range operations {
n := len(stk)
switch op {
case "+":
stk = append(stk, stk[n-1]+stk[n-2])
case "D":
stk = append(stk, stk[n-1]*2)
case "C":
stk = stk[:n-1]
default:
num, _ := strconv.Atoi(op)
stk = append(stk, num)
}
}
for _, x := range stk {
ans += x
}
return
}
|
class Solution {
public int calPoints(String[] operations) {
Deque<Integer> stk = new ArrayDeque<>();
for (String op : operations) {
if ("+".equals(op)) {
int a = stk.pop();
int b = stk.peek();
stk.push(a);
stk.push(a + b);
} else if ("D".equals(op)) {
stk.push(stk.peek() << 1);
} else if ("C".equals(op)) {
stk.pop();
} else {
stk.push(Integer.valueOf(op));
}
}
return stk.stream().mapToInt(Integer::intValue).sum();
}
}
| null | null | null | null | null | null |
class Solution:
def calPoints(self, operations: List[str]) -> int:
stk = []
for op in operations:
if op == "+":
stk.append(stk[-1] + stk[-2])
elif op == "D":
stk.append(stk[-1] << 1)
elif op == "C":
stk.pop()
else:
stk.append(int(op))
return sum(stk)
| null |
impl Solution {
pub fn cal_points(operations: Vec<String>) -> i32 {
let mut stk = vec![];
for op in operations {
match op.as_str() {
"+" => {
let n = stk.len();
stk.push(stk[n - 1] + stk[n - 2]);
}
"D" => {
stk.push(stk.last().unwrap() * 2);
}
"C" => {
stk.pop();
}
n => {
stk.push(n.parse::<i32>().unwrap());
}
}
}
stk.into_iter().sum()
}
}
| null | null | null |
function calPoints(operations: string[]): number {
const stk: number[] = [];
for (const op of operations) {
if (op === '+') {
stk.push(stk.at(-1)! + stk.at(-2)!);
} else if (op === 'D') {
stk.push(stk.at(-1)! << 1);
} else if (op === 'C') {
stk.pop();
} else {
stk.push(+op);
}
}
return stk.reduce((a, b) => a + b, 0);
}
|
Number of Ways to Select Buildings
|
You are given a
0-indexed
binary string
s
which represents the types of buildings along a street where:
s[i] = '0'
denotes that the
i
th
building is an office and
s[i] = '1'
denotes that the
i
th
building is a restaurant.
As a city official, you would like to
select
3 buildings for random inspection. However, to ensure variety,
no two consecutive
buildings out of the
selected
buildings can be of the same type.
For example, given
s = "0
0
1
1
0
1
"
, we cannot select the
1
st
,
3
rd
, and
5
th
buildings as that would form
"0
11
"
which is
not
allowed due to having two consecutive buildings of the same type.
Return
the
number of valid ways
to select 3 buildings.
Example 1:
Input:
s = "001101"
Output:
6
Explanation:
The following sets of indices selected are valid:
- [0,2,4] from "
0
0
1
1
0
1" forms "010"
- [0,3,4] from "
0
01
10
1" forms "010"
- [1,2,4] from "0
01
1
0
1" forms "010"
- [1,3,4] from "0
0
1
10
1" forms "010"
- [2,4,5] from "00
1
1
01
" forms "101"
- [3,4,5] from "001
101
" forms "101"
No other selection is valid. Thus, there are 6 total ways.
Example 2:
Input:
s = "11100"
Output:
0
Explanation:
It can be shown that there are no valid selections.
Constraints:
3 <= s.length <= 10
5
s[i]
is either
'0'
or
'1'
.
| null | null |
class Solution {
public:
long long numberOfWays(string s) {
int n = s.size();
int l[2]{};
int r[2]{};
r[0] = ranges::count(s, '0');
r[1] = n - r[0];
long long ans = 0;
for (int i = 0; i < n; ++i) {
int x = s[i] - '0';
r[x]--;
ans += 1LL * l[x ^ 1] * r[x ^ 1];
l[x]++;
}
return ans;
}
};
| null | null |
func numberOfWays(s string) (ans int64) {
n := len(s)
l := [2]int{}
r := [2]int{}
r[0] = strings.Count(s, "0")
r[1] = n - r[0]
for _, c := range s {
x := int(c - '0')
r[x]--
ans += int64(l[x^1] * r[x^1])
l[x]++
}
return
}
|
class Solution {
public long numberOfWays(String s) {
int n = s.length();
int[] l = new int[2];
int[] r = new int[2];
for (int i = 0; i < n; ++i) {
r[s.charAt(i) - '0']++;
}
long ans = 0;
for (int i = 0; i < n; ++i) {
int x = s.charAt(i) - '0';
r[x]--;
ans += 1L * l[x ^ 1] * r[x ^ 1];
l[x]++;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfWays(self, s: str) -> int:
l = [0, 0]
r = [s.count("0"), s.count("1")]
ans = 0
for x in map(int, s):
r[x] -= 1
ans += l[x ^ 1] * r[x ^ 1]
l[x] += 1
return ans
| null | null | null | null | null |
function numberOfWays(s: string): number {
const n = s.length;
const l: number[] = [0, 0];
const r: number[] = [s.split('').filter(c => c === '0').length, 0];
r[1] = n - r[0];
let ans: number = 0;
for (const c of s) {
const x = c === '0' ? 0 : 1;
r[x]--;
ans += l[x ^ 1] * r[x ^ 1];
l[x]++;
}
return ans;
}
|
Count Non-Decreasing Subarrays After K Operations
|
You are given an array
nums
of
n
integers and an integer
k
.
For each subarray of
nums
, you can apply
up to
k
operations on it. In each operation, you increment any element of the subarray by 1.
Note
that each subarray is considered independently, meaning changes made to one subarray do not persist to another.
Return the number of subarrays that you can make
non-decreasing
after performing at most
k
operations.
An array is said to be
non-decreasing
if each element is greater than or equal to its previous element, if it exists.
Example 1:
Input:
nums = [6,3,1,2,4,4], k = 7
Output:
17
Explanation:
Out of all 21 possible subarrays of
nums
, only the subarrays
[6, 3, 1]
,
[6, 3, 1, 2]
,
[6, 3, 1, 2, 4]
and
[6, 3, 1, 2, 4, 4]
cannot be made non-decreasing after applying up to k = 7 operations. Thus, the number of non-decreasing subarrays is
21 - 4 = 17
.
Example 2:
Input:
nums = [6,3,1,3,6], k = 4
Output:
12
Explanation:
The subarray
[3, 1, 3, 6]
along with all subarrays of
nums
with three or fewer elements, except
[6, 3, 1]
, can be made non-decreasing after
k
operations. There are 5 subarrays of a single element, 4 subarrays of two elements, and 2 subarrays of three elements except
[6, 3, 1]
, so there are
1 + 5 + 4 + 2 = 12
subarrays that can be made non-decreasing.
Constraints:
1 <= nums.length <= 10
5
1 <= nums[i] <= 10
9
1 <= k <= 10
9
| null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null | null |
Count Univalue Subtrees 🔒
|
Given the
root
of a binary tree, return
the number of
uni-value
subtrees
.
A
uni-value subtree
means all nodes of the subtree have the same value.
Example 1:
Input:
root = [5,1,5,5,5,null,5]
Output:
4
Example 2:
Input:
root = []
Output:
0
Example 3:
Input:
root = [5,5,5,5,5,null,5]
Output:
6
Constraints:
The number of the node in the tree will be in the range
[0, 1000]
.
-1000 <= Node.val <= 1000
| null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
int ans = 0;
function<bool(TreeNode*)> dfs = [&](TreeNode* root) -> bool {
if (!root) {
return true;
}
bool l = dfs(root->left);
bool r = dfs(root->right);
if (!l || !r) {
return false;
}
int a = root->left ? root->left->val : root->val;
int b = root->right ? root->right->val : root->val;
if (a == b && b == root->val) {
++ans;
return true;
}
return false;
};
dfs(root);
return ans;
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func countUnivalSubtrees(root *TreeNode) (ans int) {
var dfs func(*TreeNode) bool
dfs = func(root *TreeNode) bool {
if root == nil {
return true
}
l, r := dfs(root.Left), dfs(root.Right)
if !l || !r {
return false
}
if root.Left != nil && root.Left.Val != root.Val {
return false
}
if root.Right != nil && root.Right.Val != root.Val {
return false
}
ans++
return true
}
dfs(root)
return
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans;
public int countUnivalSubtrees(TreeNode root) {
dfs(root);
return ans;
}
private boolean dfs(TreeNode root) {
if (root == null) {
return true;
}
boolean l = dfs(root.left);
boolean r = dfs(root.right);
if (!l || !r) {
return false;
}
int a = root.left == null ? root.val : root.left.val;
int b = root.right == null ? root.val : root.right.val;
if (a == b && b == root.val) {
++ans;
return true;
}
return false;
}
}
|
/**
* 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
* @return {number}
*/
var countUnivalSubtrees = function (root) {
let ans = 0;
const dfs = root => {
if (!root) {
return true;
}
const l = dfs(root.left);
const r = dfs(root.right);
if (!l || !r) {
return false;
}
if (root.left && root.left.val !== root.val) {
return false;
}
if (root.right && root.right.val !== root.val) {
return false;
}
++ans;
return true;
};
dfs(root);
return ans;
};
| 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 countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return True
l, r = dfs(root.left), dfs(root.right)
if not l or not r:
return False
a = root.val if root.left is None else root.left.val
b = root.val if root.right is None else root.right.val
if a == b == root.val:
nonlocal ans
ans += 1
return True
return False
ans = 0
dfs(root)
return ans
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function countUnivalSubtrees(root: TreeNode | null): number {
let ans: number = 0;
const dfs = (root: TreeNode | null): boolean => {
if (root == null) {
return true;
}
const l: boolean = dfs(root.left);
const r: boolean = dfs(root.right);
if (!l || !r) {
return false;
}
if (root.left != null && root.left.val != root.val) {
return false;
}
if (root.right != null && root.right.val != root.val) {
return false;
}
++ans;
return true;
};
dfs(root);
return ans;
}
|
Accounts Merge
|
Given a list of
accounts
where each element
accounts[i]
is a list of strings, where the first element
accounts[i][0]
is a name, and the rest of the elements are
emails
representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails
in sorted order
. The accounts themselves can be returned in
any order
.
Example 1:
Input:
accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output:
[["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Example 2:
Input:
accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output:
[["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
Constraints:
1 <= accounts.length <= 1000
2 <= accounts[i].length <= 10
1 <= accounts[i][j].length <= 30
accounts[i][0]
consists of English letters.
accounts[i][j] (for j > 0)
is a valid email.
| null | null |
class UnionFind {
public:
UnionFind(int n) {
p = vector<int>(n);
size = vector<int>(n, 1);
iota(p.begin(), p.end(), 0);
}
bool unite(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private:
vector<int> p, size;
};
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
int n = accounts.size();
UnionFind uf(n);
unordered_map<string, int> d;
for (int i = 0; i < n; ++i) {
for (int j = 1; j < accounts[i].size(); ++j) {
const string& email = accounts[i][j];
if (d.find(email) != d.end()) {
uf.unite(i, d[email]);
} else {
d[email] = i;
}
}
}
unordered_map<int, set<string>> g;
for (int i = 0; i < n; ++i) {
int root = uf.find(i);
g[root].insert(accounts[i].begin() + 1, accounts[i].end());
}
vector<vector<string>> ans;
for (const auto& [root, s] : g) {
vector<string> emails(s.begin(), s.end());
emails.insert(emails.begin(), accounts[root][0]);
ans.push_back(emails);
}
return ans;
}
};
| null | null |
type unionFind struct {
p, size []int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a), uf.find(b)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
return true
}
func accountsMerge(accounts [][]string) (ans [][]string) {
n := len(accounts)
uf := newUnionFind(n)
d := make(map[string]int)
for i := 0; i < n; i++ {
for _, email := range accounts[i][1:] {
if j, ok := d[email]; ok {
uf.union(i, j)
} else {
d[email] = i
}
}
}
g := make(map[int]map[string]struct{})
for i := 0; i < n; i++ {
root := uf.find(i)
if _, ok := g[root]; !ok {
g[root] = make(map[string]struct{})
}
for _, email := range accounts[i][1:] {
g[root][email] = struct{}{}
}
}
for root, s := range g {
emails := []string{}
for email := range s {
emails = append(emails, email)
}
sort.Strings(emails)
account := append([]string{accounts[root][0]}, emails...)
ans = append(ans, account)
}
return
}
|
class UnionFind {
private final int[] p;
private final int[] size;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
}
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
UnionFind uf = new UnionFind(n);
Map<String, Integer> d = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 1; j < accounts.get(i).size(); ++j) {
String email = accounts.get(i).get(j);
if (d.containsKey(email)) {
uf.union(i, d.get(email));
} else {
d.put(email, i);
}
}
}
Map<Integer, Set<String>> g = new HashMap<>();
for (int i = 0; i < n; ++i) {
int root = uf.find(i);
g.computeIfAbsent(root, k -> new HashSet<>())
.addAll(accounts.get(i).subList(1, accounts.get(i).size()));
}
List<List<String>> ans = new ArrayList<>();
for (var e : g.entrySet()) {
List<String> emails = new ArrayList<>(e.getValue());
Collections.sort(emails);
ans.add(new ArrayList<>());
ans.get(ans.size() - 1).add(accounts.get(e.getKey()).get(0));
ans.get(ans.size() - 1).addAll(emails);
}
return ans;
}
}
| null | null | null | null | null | null |
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
uf = UnionFind(len(accounts))
d = {}
for i, (_, *emails) in enumerate(accounts):
for email in emails:
if email in d:
uf.union(i, d[email])
else:
d[email] = i
g = defaultdict(set)
for i, (_, *emails) in enumerate(accounts):
root = uf.find(i)
g[root].update(emails)
return [[accounts[root][0]] + sorted(emails) for root, emails in g.items()]
| null | null | null | null | null |
class UnionFind {
private p: number[];
private size: number[];
constructor(n: number) {
this.p = new Array(n);
this.size = new Array(n);
for (let i = 0; i < n; ++i) {
this.p[i] = i;
this.size[i] = 1;
}
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
let pa = this.find(a),
pb = this.find(b);
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
}
function accountsMerge(accounts: string[][]): string[][] {
const n = accounts.length;
const uf = new UnionFind(n);
const d = new Map<string, number>();
for (let i = 0; i < n; ++i) {
for (let j = 1; j < accounts[i].length; ++j) {
const email = accounts[i][j];
if (d.has(email)) {
uf.union(i, d.get(email)!);
} else {
d.set(email, i);
}
}
}
const g = new Map<number, Set<string>>();
for (let i = 0; i < n; ++i) {
const root = uf.find(i);
if (!g.has(root)) {
g.set(root, new Set<string>());
}
const emailSet = g.get(root)!;
for (let j = 1; j < accounts[i].length; ++j) {
emailSet.add(accounts[i][j]);
}
}
const ans: string[][] = [];
for (const [root, emails] of g.entries()) {
const emailList = Array.from(emails).sort();
const mergedAccount = [accounts[root][0], ...emailList];
ans.push(mergedAccount);
}
return ans;
}
|
Lexicographically Smallest Equivalent String
|
You are given two strings of the same length
s1
and
s2
and a string
baseStr
.
We say
s1[i]
and
s2[i]
are equivalent characters.
For example, if
s1 = "abc"
and
s2 = "cde"
, then we have
'a' == 'c'
,
'b' == 'd'
, and
'c' == 'e'
.
Equivalent characters follow the usual rules of any equivalence relation:
Reflexivity:
'a' == 'a'
.
Symmetry:
'a' == 'b'
implies
'b' == 'a'
.
Transitivity:
'a' == 'b'
and
'b' == 'c'
implies
'a' == 'c'
.
For example, given the equivalency information from
s1 = "abc"
and
s2 = "cde"
,
"acd"
and
"aab"
are equivalent strings of
baseStr = "eed"
, and
"aab"
is the lexicographically smallest equivalent string of
baseStr
.
Return
the lexicographically smallest equivalent string of
baseStr
by using the equivalency information from
s1
and
s2
.
Example 1:
Input:
s1 = "parker", s2 = "morris", baseStr = "parser"
Output:
"makkek"
Explanation:
Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek".
Example 2:
Input:
s1 = "hello", s2 = "world", baseStr = "hold"
Output:
"hdld"
Explanation:
Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".
Example 3:
Input:
s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
Output:
"aauaaaaada"
Explanation:
We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".
Constraints:
1 <= s1.length, s2.length, baseStr <= 1000
s1.length == s2.length
s1
,
s2
, and
baseStr
consist of lowercase English letters.
| null |
public class Solution {
public string SmallestEquivalentString(string s1, string s2, string baseStr) {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = i;
}
int Find(int x) {
if (p[x] != x) {
p[x] = Find(p[x]);
}
return p[x];
}
for (int i = 0; i < s1.Length; i++) {
int x = s1[i] - 'a';
int y = s2[i] - 'a';
int px = Find(x);
int py = Find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
var res = new System.Text.StringBuilder();
foreach (char c in baseStr) {
int idx = Find(c - 'a');
res.Append((char)(idx + 'a'));
}
return res.ToString();
}
}
|
class Solution {
public:
string smallestEquivalentString(string s1, string s2, string baseStr) {
vector<int> p(26);
iota(p.begin(), p.end(), 0);
auto find = [&](this auto&& find, int x) -> int {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
for (int i = 0; i < s1.length(); ++i) {
int x = s1[i] - 'a';
int y = s2[i] - 'a';
int px = find(x), py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
string s;
for (char c : baseStr) {
s.push_back('a' + find(c - 'a'));
}
return s;
}
};
| null | null |
func smallestEquivalentString(s1 string, s2 string, baseStr string) string {
p := make([]int, 26)
for i := 0; i < 26; i++ {
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 i := 0; i < len(s1); i++ {
x := int(s1[i] - 'a')
y := int(s2[i] - 'a')
px := find(x)
py := find(y)
if px < py {
p[py] = px
} else {
p[px] = py
}
}
var s []byte
for i := 0; i < len(baseStr); i++ {
s = append(s, byte('a'+find(int(baseStr[i]-'a'))))
}
return string(s)
}
|
class Solution {
private final int[] p = new int[26];
public String smallestEquivalentString(String s1, String s2, String baseStr) {
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < s1.length(); ++i) {
int x = s1.charAt(i) - 'a';
int y = s2.charAt(i) - 'a';
int px = find(x), py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
char[] s = baseStr.toCharArray();
for (int i = 0; i < s.length; ++i) {
s[i] = (char) ('a' + find(s[i] - 'a'));
}
return String.valueOf(s);
}
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 smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(26))
for a, b in zip(s1, s2):
x, y = ord(a) - ord("a"), ord(b) - ord("a")
px, py = find(x), find(y)
if px < py:
p[py] = px
else:
p[px] = py
return "".join(chr(find(ord(c) - ord("a")) + ord("a")) for c in baseStr)
| null |
impl Solution {
pub fn smallest_equivalent_string(s1: String, s2: String, base_str: String) -> String {
fn find(x: usize, p: &mut Vec<usize>) -> usize {
if p[x] != x {
p[x] = find(p[x], p);
}
p[x]
}
let mut p = (0..26).collect::<Vec<_>>();
for (a, b) in s1.bytes().zip(s2.bytes()) {
let x = (a - b'a') as usize;
let y = (b - b'a') as usize;
let px = find(x, &mut p);
let py = find(y, &mut p);
if px < py {
p[py] = px;
} else {
p[px] = py;
}
}
base_str
.bytes()
.map(|c| (b'a' + find((c - b'a') as usize, &mut p) as u8) as char)
.collect()
}
}
| null | null | null |
function smallestEquivalentString(s1: string, s2: string, baseStr: string): string {
const p: number[] = Array.from({ length: 26 }, (_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
for (let i = 0; i < s1.length; i++) {
const x = s1.charCodeAt(i) - 'a'.charCodeAt(0);
const y = s2.charCodeAt(i) - 'a'.charCodeAt(0);
const px = find(x);
const py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
const s: string[] = [];
for (let i = 0; i < baseStr.length; i++) {
const c = baseStr.charCodeAt(i) - 'a'.charCodeAt(0);
s.push(String.fromCharCode('a'.charCodeAt(0) + find(c)));
}
return s.join('');
}
|
Longest Absolute File Path
|
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have
dir
as the only directory in the root.
dir
contains two subdirectories,
subdir1
and
subdir2
.
subdir1
contains a file
file1.ext
and subdirectory
subsubdir1
.
subdir2
contains a subdirectory
subsubdir2
, which contains a file
file2.ext
.
In text form, it looks like this (with ⟶ representing the tab character):
dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext
If we were to write this representation in code, it will look like this:
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
. Note that the
'\n'
and
'\t'
are the new-line and tab characters.
Every file and directory has a unique
absolute path
in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by
'/'s
. Using the above example, the
absolute path
to
file2.ext
is
"dir/subdir2/subsubdir2/file2.ext"
. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form
name.extension
, where
name
and
extension
consist of letters, digits, and/or spaces.
Given a string
input
representing the file system in the explained format, return
the length of the
longest absolute path
to a
file
in the abstracted file system
. If there is no file in the system, return
0
.
Note
that the testcases are generated such that the file system is valid and no file or directory name has length 0.
Example 1:
Input:
input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
Output:
20
Explanation:
We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.
Example 2:
Input:
input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
Output:
32
Explanation:
We have two files:
"dir/subdir1/file1.ext" of length 21
"dir/subdir2/subsubdir2/file2.ext" of length 32.
We return 32 since it is the longest absolute path to a file.
Example 3:
Input:
input = "a"
Output:
0
Explanation:
We do not have any files, just a single directory named "a".
Constraints:
1 <= input.length <= 10
4
input
may contain lowercase or uppercase English letters, a new line character
'\n'
, a tab character
'\t'
, a dot
'.'
, a space
' '
, and digits.
All file and directory names have
positive
length.
| null | null |
class Solution {
public:
int lengthLongestPath(string input) {
int i = 0, n = input.size();
int ans = 0;
stack<int> stk;
while (i < n) {
int ident = 0;
for (; input[i] == '\t'; ++i) {
++ident;
}
int cur = 0;
bool isFile = false;
for (; i < n && input[i] != '\n'; ++i) {
++cur;
if (input[i] == '.') {
isFile = true;
}
}
++i;
// popd
while (!stk.empty() && stk.size() > ident) {
stk.pop();
}
if (stk.size() > 0) {
cur += stk.top() + 1;
}
// pushd
if (!isFile) {
stk.push(cur);
continue;
}
ans = max(ans, cur);
}
return ans;
}
};
| null | null |
func lengthLongestPath(input string) int {
i, n := 0, len(input)
ans := 0
var stk []int
for i < n {
ident := 0
for ; input[i] == '\t'; i++ {
ident++
}
cur, isFile := 0, false
for ; i < n && input[i] != '\n'; i++ {
cur++
if input[i] == '.' {
isFile = true
}
}
i++
// popd
for len(stk) > 0 && len(stk) > ident {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
cur += stk[len(stk)-1] + 1
}
// pushd
if !isFile {
stk = append(stk, cur)
continue
}
ans = max(ans, cur)
}
return ans
}
|
class Solution {
public int lengthLongestPath(String input) {
int i = 0;
int n = input.length();
int ans = 0;
Deque<Integer> stack = new ArrayDeque<>();
while (i < n) {
int ident = 0;
for (; input.charAt(i) == '\t'; i++) {
ident++;
}
int cur = 0;
boolean isFile = false;
for (; i < n && input.charAt(i) != '\n'; i++) {
cur++;
if (input.charAt(i) == '.') {
isFile = true;
}
}
i++;
// popd
while (!stack.isEmpty() && stack.size() > ident) {
stack.pop();
}
if (stack.size() > 0) {
cur += stack.peek() + 1;
}
// pushd
if (!isFile) {
stack.push(cur);
continue;
}
ans = Math.max(ans, cur);
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def lengthLongestPath(self, input: str) -> int:
i, n = 0, len(input)
ans = 0
stk = []
while i < n:
ident = 0
while input[i] == '\t':
ident += 1
i += 1
cur, isFile = 0, False
while i < n and input[i] != '\n':
cur += 1
if input[i] == '.':
isFile = True
i += 1
i += 1
# popd
while len(stk) > 0 and len(stk) > ident:
stk.pop()
if len(stk) > 0:
cur += stk[-1] + 1
# pushd
if not isFile:
stk.append(cur)
continue
ans = max(ans, cur)
return ans
| null | null | null | null | null | null |
Minimum Number of People to Teach
|
On a social network consisting of
m
users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer
n
, an array
languages
, and an array
friendships
where:
There are
n
languages numbered
1
through
n
,
languages[i]
is the set of languages the
i
th
user knows, and
friendships[i] = [u
i
, v
i
]
denotes a friendship between the users
u
i
and
v
i
.
You can choose
one
language and teach it to some users so that all friends can communicate with each other. Return
the
minimum
number of users you need to teach.
Note that friendships are not transitive, meaning if
x
is a friend of
y
and
y
is a friend of
z
, this doesn't guarantee that
x
is a friend of
z
.
Example 1:
Input:
n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]
Output:
1
Explanation:
You can either teach user 1 the second language or user 2 the first language.
Example 2:
Input:
n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]
Output:
2
Explanation:
Teach the third language to users 1 and 3, yielding two users to teach.
Constraints:
2 <= n <= 500
languages.length == m
1 <= m <= 500
1 <= languages[i].length <= n
1 <= languages[i][j] <= n
1 <= u
i
< v
i
<= languages.length
1 <= friendships.length <= 500
All tuples
(u
i,
v
i
)
are unique
languages[i]
contains only unique values
| null | null |
class Solution {
public:
int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {
unordered_set<int> s;
for (auto& e : friendships) {
int u = e[0], v = e[1];
if (!check(u, v, languages)) {
s.insert(u);
s.insert(v);
}
}
if (s.empty()) {
return 0;
}
vector<int> cnt(n + 1);
for (int u : s) {
for (int& l : languages[u - 1]) {
++cnt[l];
}
}
return s.size() - *max_element(cnt.begin(), cnt.end());
}
bool check(int u, int v, vector<vector<int>>& languages) {
for (int x : languages[u - 1]) {
for (int y : languages[v - 1]) {
if (x == y) {
return true;
}
}
}
return false;
}
};
| null | null |
func minimumTeachings(n int, languages [][]int, friendships [][]int) int {
check := func(u, v int) bool {
for _, x := range languages[u-1] {
for _, y := range languages[v-1] {
if x == y {
return true
}
}
}
return false
}
s := map[int]bool{}
for _, e := range friendships {
u, v := e[0], e[1]
if !check(u, v) {
s[u], s[v] = true, true
}
}
if len(s) == 0 {
return 0
}
cnt := make([]int, n+1)
for u := range s {
for _, l := range languages[u-1] {
cnt[l]++
}
}
return len(s) - slices.Max(cnt)
}
|
class Solution {
public int minimumTeachings(int n, int[][] languages, int[][] friendships) {
Set<Integer> s = new HashSet<>();
for (var e : friendships) {
int u = e[0], v = e[1];
if (!check(u, v, languages)) {
s.add(u);
s.add(v);
}
}
if (s.isEmpty()) {
return 0;
}
int[] cnt = new int[n + 1];
for (int u : s) {
for (int l : languages[u - 1]) {
++cnt[l];
}
}
int mx = 0;
for (int v : cnt) {
mx = Math.max(mx, v);
}
return s.size() - mx;
}
private boolean check(int u, int v, int[][] languages) {
for (int x : languages[u - 1]) {
for (int y : languages[v - 1]) {
if (x == y) {
return true;
}
}
}
return false;
}
}
| null | null | null | null | null | null |
class Solution:
def minimumTeachings(
self, n: int, languages: List[List[int]], friendships: List[List[int]]
) -> int:
def check(u, v):
for x in languages[u - 1]:
for y in languages[v - 1]:
if x == y:
return True
return False
s = set()
for u, v in friendships:
if not check(u, v):
s.add(u)
s.add(v)
cnt = Counter()
for u in s:
for l in languages[u - 1]:
cnt[l] += 1
return len(s) - max(cnt.values(), default=0)
| null | null | null | null | null | null |
Find the Middle Index in Array
|
Given a
0-indexed
integer array
nums
, find the
leftmost
middleIndex
(i.e., the smallest amongst all the possible ones).
A
middleIndex
is an index where
nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
.
If
middleIndex == 0
, the left side sum is considered to be
0
. Similarly, if
middleIndex == nums.length - 1
, the right side sum is considered to be
0
.
Return
the
leftmost
middleIndex
that satisfies the condition, or
-1
if there is no such index
.
Example 1:
Input:
nums = [2,3,-1,
8
,4]
Output:
3
Explanation:
The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
Example 2:
Input:
nums = [1,-1,
4
]
Output:
2
Explanation:
The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
Example 3:
Input:
nums = [2,5]
Output:
-1
Explanation:
There is no valid middleIndex.
Constraints:
1 <= nums.length <= 100
-1000 <= nums[i] <= 1000
Note:
This question is the same as 724:
https://leetcode.com/problems/find-pivot-index/
| null | null |
class Solution {
public:
int findMiddleIndex(vector<int>& nums) {
int l = 0, r = accumulate(nums.begin(), nums.end(), 0);
for (int i = 0; i < nums.size(); ++i) {
r -= nums[i];
if (l == r) {
return i;
}
l += nums[i];
}
return -1;
}
};
| null | null |
func findMiddleIndex(nums []int) int {
l, r := 0, 0
for _, x := range nums {
r += x
}
for i, x := range nums {
r -= x
if l == r {
return i
}
l += x
}
return -1
}
|
class Solution {
public int findMiddleIndex(int[] nums) {
int l = 0, r = Arrays.stream(nums).sum();
for (int i = 0; i < nums.length; ++i) {
r -= nums[i];
if (l == r) {
return i;
}
l += nums[i];
}
return -1;
}
}
|
/**
* @param {number[]} nums
* @return {number}
*/
var findMiddleIndex = function (nums) {
let l = 0;
let r = nums.reduce((a, b) => a + b, 0);
for (let i = 0; i < nums.length; ++i) {
r -= nums[i];
if (l === r) {
return i;
}
l += nums[i];
}
return -1;
};
| null | null | null | null | null |
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
l, r = 0, sum(nums)
for i, x in enumerate(nums):
r -= x
if l == r:
return i
l += x
return -1
| null |
impl Solution {
pub fn find_middle_index(nums: Vec<i32>) -> i32 {
let mut l = 0;
let mut r: i32 = nums.iter().sum();
for (i, &x) in nums.iter().enumerate() {
r -= x;
if l == r {
return i as i32;
}
l += x;
}
-1
}
}
| null | null | null |
function findMiddleIndex(nums: number[]): number {
let l = 0;
let r = nums.reduce((a, b) => a + b, 0);
for (let i = 0; i < nums.length; ++i) {
r -= nums[i];
if (l === r) {
return i;
}
l += nums[i];
}
return -1;
}
|
Find Players With Zero or One Losses
|
You are given an integer array
matches
where
matches[i] = [winner
i
, loser
i
]
indicates that the player
winner
i
defeated player
loser
i
in a match.
Return
a list
answer
of size
2
where:
answer[0]
is a list of all players that have
not
lost any matches.
answer[1]
is a list of all players that have lost exactly
one
match.
The values in the two lists should be returned in
increasing
order.
Note:
You should only consider the players that have played
at least one
match.
The testcases will be generated such that
no
two matches will have the
same
outcome.
Example 1:
Input:
matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output:
[[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
Example 2:
Input:
matches = [[2,3],[1,3],[5,4],[6,4]]
Output:
[[1,2,5,6],[]]
Explanation:
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer[0] = [1,2,5,6] and answer[1] = [].
Constraints:
1 <= matches.length <= 10
5
matches[i].length == 2
1 <= winner
i
, loser
i
<= 10
5
winner
i
!= loser
i
All
matches[i]
are
unique
.
| null | null |
class Solution {
public:
vector<vector<int>> findWinners(vector<vector<int>>& matches) {
map<int, int> cnt;
for (auto& e : matches) {
if (!cnt.contains(e[0])) {
cnt[e[0]] = 0;
}
++cnt[e[1]];
}
vector<vector<int>> ans(2);
for (auto& [x, v] : cnt) {
if (v < 2) {
ans[v].push_back(x);
}
}
return ans;
}
};
| null | null |
func findWinners(matches [][]int) [][]int {
cnt := map[int]int{}
for _, e := range matches {
if _, ok := cnt[e[0]]; !ok {
cnt[e[0]] = 0
}
cnt[e[1]]++
}
ans := make([][]int, 2)
for x, v := range cnt {
if v < 2 {
ans[v] = append(ans[v], x)
}
}
sort.Ints(ans[0])
sort.Ints(ans[1])
return ans
}
|
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer, Integer> cnt = new HashMap<>();
for (var e : matches) {
cnt.putIfAbsent(e[0], 0);
cnt.merge(e[1], 1, Integer::sum);
}
List<List<Integer>> ans = List.of(new ArrayList<>(), new ArrayList<>());
for (var e : cnt.entrySet()) {
if (e.getValue() < 2) {
ans.get(e.getValue()).add(e.getKey());
}
}
Collections.sort(ans.get(0));
Collections.sort(ans.get(1));
return ans;
}
}
|
/**
* @param {number[][]} matches
* @return {number[][]}
*/
var findWinners = function (matches) {
const cnt = new Map();
for (const [winner, loser] of matches) {
if (!cnt.has(winner)) {
cnt.set(winner, 0);
}
cnt.set(loser, (cnt.get(loser) || 0) + 1);
}
const ans = [[], []];
for (const [x, v] of cnt) {
if (v < 2) {
ans[v].push(x);
}
}
ans[0].sort((a, b) => a - b);
ans[1].sort((a, b) => a - b);
return ans;
};
| null | null | null | null | null |
class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
cnt = Counter()
for winner, loser in matches:
if winner not in cnt:
cnt[winner] = 0
cnt[loser] += 1
ans = [[], []]
for x, v in sorted(cnt.items()):
if v < 2:
ans[v].append(x)
return ans
| null | null | null | null | null |
function findWinners(matches: number[][]): number[][] {
const cnt: Map<number, number> = new Map();
for (const [winner, loser] of matches) {
if (!cnt.has(winner)) {
cnt.set(winner, 0);
}
cnt.set(loser, (cnt.get(loser) || 0) + 1);
}
const ans: number[][] = [[], []];
for (const [x, v] of cnt) {
if (v < 2) {
ans[v].push(x);
}
}
ans[0].sort((a, b) => a - b);
ans[1].sort((a, b) => a - b);
return ans;
}
|
Design an ATM Machine
|
There is an ATM machine that stores banknotes of
5
denominations:
20
,
50
,
100
,
200
, and
500
dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
When withdrawing, the machine prioritizes using banknotes of
larger
values.
For example, if you want to withdraw
$300
and there are
2
$50
banknotes,
1
$100
banknote, and
1
$200
banknote, then the machine will use the
$100
and
$200
banknotes.
However, if you try to withdraw
$600
and there are
3
$200
banknotes and
1
$500
banknote, then the withdraw request will be rejected because the machine will first try to use the
$500
banknote and then be unable to use banknotes to complete the remaining
$100
. Note that the machine is
not
allowed to use the
$200
banknotes instead of the
$500
banknote.
Implement the ATM class:
ATM()
Initializes the ATM object.
void deposit(int[] banknotesCount)
Deposits new banknotes in the order
$20
,
$50
,
$100
,
$200
, and
$500
.
int[] withdraw(int amount)
Returns an array of length
5
of the number of banknotes that will be handed to the user in the order
$20
,
$50
,
$100
,
$200
, and
$500
, and update the number of banknotes in the ATM after withdrawing. Returns
[-1]
if it is not possible (do
not
withdraw any banknotes in this case).
Example 1:
Input
["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
Output
[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
Explanation
ATM atm = new ATM();
atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
// and 1 $500 banknote.
atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
// and 1 $500 banknote. The banknotes left over in the
// machine are [0,0,0,2,0].
atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
// The banknotes in the machine are now [0,1,0,3,1].
atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote
// and then be unable to complete the remaining $100,
// so the withdraw request will be rejected.
// Since the request is rejected, the number of banknotes
// in the machine is not modified.
atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
// and 1 $500 banknote.
Constraints:
banknotesCount.length == 5
0 <= banknotesCount[i] <= 10
9
1 <= amount <= 10
9
At most
5000
calls
in total
will be made to
withdraw
and
deposit
.
At least
one
call will be made to each function
withdraw
and
deposit
.
Sum of
banknotesCount[i]
in all deposits doesn't exceed
10
9
| null | null |
class ATM {
public:
ATM() {
}
void deposit(vector<int> banknotesCount) {
for (int i = 0; i < banknotesCount.size(); ++i) {
cnt[i] += banknotesCount[i];
}
}
vector<int> withdraw(int amount) {
vector<int> ans(m);
for (int i = m - 1; ~i; --i) {
ans[i] = min(1ll * amount / d[i], cnt[i]);
amount -= ans[i] * d[i];
}
if (amount > 0) {
return {-1};
}
for (int i = 0; i < m; ++i) {
cnt[i] -= ans[i];
}
return ans;
}
private:
static constexpr int d[5] = {20, 50, 100, 200, 500};
static constexpr int m = size(d);
long long cnt[m] = {0};
};
/**
* Your ATM object will be instantiated and called as such:
* ATM* obj = new ATM();
* obj->deposit(banknotesCount);
* vector<int> param_2 = obj->withdraw(amount);
*/
| null | null |
var d = [...]int{20, 50, 100, 200, 500}
const m = len(d)
type ATM [m]int
func Constructor() ATM {
return ATM{}
}
func (this *ATM) Deposit(banknotesCount []int) {
for i, x := range banknotesCount {
this[i] += x
}
}
func (this *ATM) Withdraw(amount int) []int {
ans := make([]int, m)
for i := m - 1; i >= 0; i-- {
ans[i] = min(amount/d[i], this[i])
amount -= ans[i] * d[i]
}
if amount > 0 {
return []int{-1}
}
for i, x := range ans {
this[i] -= x
}
return ans
}
/**
* Your ATM object will be instantiated and called as such:
* obj := Constructor();
* obj.Deposit(banknotesCount);
* param_2 := obj.Withdraw(amount);
*/
|
class ATM {
private int[] d = {20, 50, 100, 200, 500};
private int m = d.length;
private long[] cnt = new long[5];
public ATM() {
}
public void deposit(int[] banknotesCount) {
for (int i = 0; i < banknotesCount.length; ++i) {
cnt[i] += banknotesCount[i];
}
}
public int[] withdraw(int amount) {
int[] ans = new int[m];
for (int i = m - 1; i >= 0; --i) {
ans[i] = (int) Math.min(amount / d[i], cnt[i]);
amount -= ans[i] * d[i];
}
if (amount > 0) {
return new int[] {-1};
}
for (int i = 0; i < m; ++i) {
cnt[i] -= ans[i];
}
return ans;
}
}
/**
* Your ATM object will be instantiated and called as such:
* ATM obj = new ATM();
* obj.deposit(banknotesCount);
* int[] param_2 = obj.withdraw(amount);
*/
| null | null | null | null | null | null |
class ATM:
def __init__(self):
self.d = [20, 50, 100, 200, 500]
self.m = len(self.d)
self.cnt = [0] * self.m
def deposit(self, banknotesCount: List[int]) -> None:
for i, x in enumerate(banknotesCount):
self.cnt[i] += x
def withdraw(self, amount: int) -> List[int]:
ans = [0] * self.m
for i in reversed(range(self.m)):
ans[i] = min(amount // self.d[i], self.cnt[i])
amount -= ans[i] * self.d[i]
if amount > 0:
return [-1]
for i, x in enumerate(ans):
self.cnt[i] -= x
return ans
# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)
| null | null | null | null | null |
const d: number[] = [20, 50, 100, 200, 500];
const m = d.length;
class ATM {
private cnt: number[];
constructor() {
this.cnt = Array(m).fill(0);
}
deposit(banknotesCount: number[]): void {
for (let i = 0; i < banknotesCount.length; ++i) {
this.cnt[i] += banknotesCount[i];
}
}
withdraw(amount: number): number[] {
const ans: number[] = Array(m).fill(0);
for (let i = m - 1; i >= 0; --i) {
ans[i] = Math.min(Math.floor(amount / d[i]), this.cnt[i]);
amount -= ans[i] * d[i];
}
if (amount > 0) {
return [-1];
}
for (let i = 0; i < m; ++i) {
this.cnt[i] -= ans[i];
}
return ans;
}
}
/**
* Your ATM object will be instantiated and called as such:
* var obj = new ATM()
* obj.deposit(banknotesCount)
* var param_2 = obj.withdraw(amount)
*/
|
Spiral Matrix
|
Given an
m x n
matrix
, return
all elements of the
matrix
in spiral order
.
Example 1:
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[1,2,3,6,9,8,7,4,5]
Example 2:
Input:
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output:
[1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
| null |
public class Solution {
public IList<int> SpiralOrder(int[][] matrix) {
int m = matrix.Length, n = matrix[0].Length;
int[] dirs = { 0, 1, 0, -1, 0 };
int i = 0, j = 0, k = 0;
IList<int> ans = new List<int>();
for (int h = m * n; h > 0; --h) {
ans.Add(matrix[i][j]);
matrix[i][j] += 300;
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
for (int a = 0; a < m; ++a) {
for (int b = 0; b < n; ++b) {
matrix[a][b] -= 300;
}
}
return ans;
}
}
|
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int dirs[5] = {0, 1, 0, -1, 0};
int i = 0, j = 0, k = 0;
vector<int> ans;
for (int h = m * n; h; --h) {
ans.push_back(matrix[i][j]);
matrix[i][j] += 300;
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
matrix[i][j] -= 300;
}
}
return ans;
}
};
| null | null |
func spiralOrder(matrix [][]int) (ans []int) {
m, n := len(matrix), len(matrix[0])
dirs := [5]int{0, 1, 0, -1, 0}
i, j, k := 0, 0, 0
for h := m * n; h > 0; h-- {
ans = append(ans, matrix[i][j])
matrix[i][j] += 300
x, y := i+dirs[k], j+dirs[k+1]
if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 {
k = (k + 1) % 4
}
i, j = i+dirs[k], j+dirs[k+1]
}
for i = 0; i < m; i++ {
for j = 0; j < n; j++ {
matrix[i][j] -= 300
}
}
return
}
|
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[] dirs = {0, 1, 0, -1, 0};
int i = 0, j = 0, k = 0;
List<Integer> ans = new ArrayList<>();
for (int h = m * n; h > 0; --h) {
ans.add(matrix[i][j]);
matrix[i][j] += 300;
int x = i + dirs[k], y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
matrix[i][j] -= 300;
}
}
return ans;
}
}
|
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const m = matrix.length;
const n = matrix[0].length;
const ans = [];
const dirs = [0, 1, 0, -1, 0];
for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) {
ans.push(matrix[i][j]);
matrix[i][j] += 300;
const x = i + dirs[k];
const y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
matrix[i][j] -= 300;
}
}
return ans;
};
| null | null | null | null | null |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0)
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
matrix[i][j] += 300
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] > 100:
k = (k + 1) % 4
i += dirs[k]
j += dirs[k + 1]
for i in range(m):
for j in range(n):
matrix[i][j] -= 300
return ans
| null |
impl Solution {
pub fn spiral_order(mut matrix: Vec<Vec<i32>>) -> Vec<i32> {
let m = matrix.len();
let n = matrix[0].len();
let mut dirs = vec![0, 1, 0, -1, 0];
let mut i = 0;
let mut j = 0;
let mut k = 0;
let mut ans = Vec::new();
for _ in 0..(m * n) {
ans.push(matrix[i][j]);
matrix[i][j] += 300;
let x = i as i32 + dirs[k] as i32;
let y = j as i32 + dirs[k + 1] as i32;
if x < 0
|| x >= m as i32
|| y < 0
|| y >= n as i32
|| matrix[x as usize][y as usize] > 100
{
k = (k + 1) % 4;
}
i = (i as i32 + dirs[k] as i32) as usize;
j = (j as i32 + dirs[k + 1] as i32) as usize;
}
for i in 0..m {
for j in 0..n {
matrix[i][j] -= 300;
}
}
ans
}
}
| null | null | null |
function spiralOrder(matrix: number[][]): number[] {
const m = matrix.length;
const n = matrix[0].length;
const ans: number[] = [];
const dirs = [0, 1, 0, -1, 0];
for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) {
ans.push(matrix[i][j]);
matrix[i][j] += 300;
const x = i + dirs[k];
const y = j + dirs[k + 1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) {
k = (k + 1) % 4;
}
i += dirs[k];
j += dirs[k + 1];
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
matrix[i][j] -= 300;
}
}
return ans;
}
|
Boundary of Binary Tree 🔒
|
The
boundary
of a binary tree is the concatenation of the
root
, the
left boundary
, the
leaves
ordered from left-to-right, and the
reverse order
of the
right boundary
.
The
left boundary
is the set of nodes defined by the following:
The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is
empty
.
If a node is in the left boundary and has a left child, then the left child is in the left boundary.
If a node is in the left boundary, has
no
left child, but has a right child, then the right child is in the left boundary.
The leftmost leaf is
not
in the left boundary.
The
right boundary
is similar to the
left boundary
, except it is the right side of the root's right subtree. Again, the leaf is
not
part of the
right boundary
, and the
right boundary
is empty if the root does not have a right child.
The
leaves
are nodes that do not have any children. For this problem, the root is
not
a leaf.
Given the
root
of a binary tree, return
the values of its
boundary
.
Example 1:
Input:
root = [1,null,2,3,4]
Output:
[1,3,4,2]
Explanation:
- The left boundary is empty because the root does not have a left child.
- The right boundary follows the path starting from the root's right child 2 -> 4.
4 is a leaf, so the right boundary is [2].
- The leaves from left to right are [3,4].
Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2].
Example 2:
Input:
root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
Output:
[1,2,4,7,8,9,10,6,3]
Explanation:
- The left boundary follows the path starting from the root's left child 2 -> 4.
4 is a leaf, so the left boundary is [2].
- The right boundary follows the path starting from the root's right child 3 -> 6 -> 10.
10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3].
- The leaves from left to right are [4,7,8,9,10].
Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3].
Constraints:
The number of nodes in the tree is in the range
[1, 10
4
]
.
-1000 <= Node.val <= 1000
| null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> boundaryOfBinaryTree(TreeNode* root) {
auto dfs = [&](this auto&& dfs, vector<int>& nums, TreeNode* root, int i) -> void {
if (!root) {
return;
}
if (i == 0) {
if (root->left != root->right) {
nums.push_back(root->val);
if (root->left) {
dfs(nums, root->left, i);
} else {
dfs(nums, root->right, i);
}
}
} else if (i == 1) {
if (root->left == root->right) {
nums.push_back(root->val);
} else {
dfs(nums, root->left, i);
dfs(nums, root->right, i);
}
} else {
if (root->left != root->right) {
nums.push_back(root->val);
if (root->right) {
dfs(nums, root->right, i);
} else {
dfs(nums, root->left, i);
}
}
}
};
vector<int> ans = {root->val};
if (root->left == root->right) {
return ans;
}
vector<int> left, right, leaves;
dfs(left, root->left, 0);
dfs(leaves, root, 1);
dfs(right, root->right, 2);
ans.insert(ans.end(), left.begin(), left.end());
ans.insert(ans.end(), leaves.begin(), leaves.end());
ans.insert(ans.end(), right.rbegin(), right.rend());
return ans;
}
};
| null | null |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func boundaryOfBinaryTree(root *TreeNode) []int {
ans := []int{root.Val}
if root.Left == root.Right {
return ans
}
left, leaves, right := []int{}, []int{}, []int{}
var dfs func(nums *[]int, root *TreeNode, i int)
dfs = func(nums *[]int, root *TreeNode, i int) {
if root == nil {
return
}
if i == 0 {
if root.Left != root.Right {
*nums = append(*nums, root.Val)
if root.Left != nil {
dfs(nums, root.Left, i)
} else {
dfs(nums, root.Right, i)
}
}
} else if i == 1 {
if root.Left == root.Right {
*nums = append(*nums, root.Val)
} else {
dfs(nums, root.Left, i)
dfs(nums, root.Right, i)
}
} else {
if root.Left != root.Right {
*nums = append(*nums, root.Val)
if root.Right != nil {
dfs(nums, root.Right, i)
} else {
dfs(nums, root.Left, i)
}
}
}
}
dfs(&left, root.Left, 0)
dfs(&leaves, root, 1)
dfs(&right, root.Right, 2)
ans = append(ans, left...)
ans = append(ans, leaves...)
for i := len(right) - 1; i >= 0; i-- {
ans = append(ans, right[i])
}
return ans
}
|
class Solution {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> ans = new ArrayList<>();
ans.add(root.val);
if (root.left == root.right) {
return ans;
}
List<Integer> left = new ArrayList<>();
List<Integer> leaves = new ArrayList<>();
List<Integer> right = new ArrayList<>();
dfs(left, root.left, 0);
dfs(leaves, root, 1);
dfs(right, root.right, 2);
ans.addAll(left);
ans.addAll(leaves);
Collections.reverse(right);
ans.addAll(right);
return ans;
}
private void dfs(List<Integer> nums, TreeNode root, int i) {
if (root == null) {
return;
}
if (i == 0) {
if (root.left != root.right) {
nums.add(root.val);
if (root.left != null) {
dfs(nums, root.left, i);
} else {
dfs(nums, root.right, i);
}
}
} else if (i == 1) {
if (root.left == root.right) {
nums.add(root.val);
} else {
dfs(nums, root.left, i);
dfs(nums, root.right, i);
}
} else {
if (root.left != root.right) {
nums.add(root.val);
if (root.right != null) {
dfs(nums, root.right, i);
} else {
dfs(nums, root.left, i);
}
}
}
}
}
|
/**
* 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
* @return {number[]}
*/
var boundaryOfBinaryTree = function (root) {
const ans = [root.val];
if (root.left === root.right) {
return ans;
}
const left = [];
const leaves = [];
const right = [];
const dfs = function (nums, root, i) {
if (!root) {
return;
}
if (i === 0) {
if (root.left !== root.right) {
nums.push(root.val);
if (root.left) {
dfs(nums, root.left, i);
} else {
dfs(nums, root.right, i);
}
}
} else if (i === 1) {
if (root.left === root.right) {
nums.push(root.val);
} else {
dfs(nums, root.left, i);
dfs(nums, root.right, i);
}
} else {
if (root.left !== root.right) {
nums.push(root.val);
if (root.right) {
dfs(nums, root.right, i);
} else {
dfs(nums, root.left, i);
}
}
}
};
dfs(left, root.left, 0);
dfs(leaves, root, 1);
dfs(right, root.right, 2);
return ans.concat(left).concat(leaves).concat(right.reverse());
};
| 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 boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
def dfs(nums: List[int], root: Optional[TreeNode], i: int):
if root is None:
return
if i == 0:
if root.left != root.right:
nums.append(root.val)
if root.left:
dfs(nums, root.left, i)
else:
dfs(nums, root.right, i)
elif i == 1:
if root.left == root.right:
nums.append(root.val)
else:
dfs(nums, root.left, i)
dfs(nums, root.right, i)
else:
if root.left != root.right:
nums.append(root.val)
if root.right:
dfs(nums, root.right, i)
else:
dfs(nums, root.left, i)
ans = [root.val]
if root.left == root.right:
return ans
left, leaves, right = [], [], []
dfs(left, root.left, 0)
dfs(leaves, root, 1)
dfs(right, root.right, 2)
ans += left + leaves + right[::-1]
return ans
| null | null | null | null | null |
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function boundaryOfBinaryTree(root: TreeNode | null): number[] {
const ans: number[] = [root.val];
if (root.left === root.right) {
return ans;
}
const left: number[] = [];
const leaves: number[] = [];
const right: number[] = [];
const dfs = function (nums: number[], root: TreeNode | null, i: number) {
if (!root) {
return;
}
if (i === 0) {
if (root.left !== root.right) {
nums.push(root.val);
if (root.left) {
dfs(nums, root.left, i);
} else {
dfs(nums, root.right, i);
}
}
} else if (i === 1) {
if (root.left === root.right) {
nums.push(root.val);
} else {
dfs(nums, root.left, i);
dfs(nums, root.right, i);
}
} else {
if (root.left !== root.right) {
nums.push(root.val);
if (root.right) {
dfs(nums, root.right, i);
} else {
dfs(nums, root.left, i);
}
}
}
};
dfs(left, root.left, 0);
dfs(leaves, root, 1);
dfs(right, root.right, 2);
return ans.concat(left).concat(leaves).concat(right.reverse());
}
|
Maximum Score From Removing Substrings
|
You are given a string
s
and two integers
x
and
y
. You can perform two types of operations any number of times.
Remove substring
"ab"
and gain
x
points.
For example, when removing
"ab"
from
"c
ab
xbae"
it becomes
"cxbae"
.
Remove substring
"ba"
and gain
y
points.
For example, when removing
"ba"
from
"cabx
ba
e"
it becomes
"cabxe"
.
Return
the maximum points you can gain after applying the above operations on
s
.
Example 1:
Input:
s = "cdbcbbaaabab", x = 4, y = 5
Output:
19
Explanation:
- Remove the "ba" underlined in "cdbcbbaaa
ba
b". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaa
ab
". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcb
ba
a". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined in "cdbc
ba
". Now, s = "cdbc" and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.
Example 2:
Input:
s = "aabbaaxybbaabb", x = 5, y = 4
Output:
20
Constraints:
1 <= s.length <= 10
5
1 <= x, y <= 10
4
s
consists of lowercase English letters.
| null |
public class Solution {
public int MaximumGain(string s, int x, int y) {
char a = 'a', b = 'b';
if (x < y) {
(x, y) = (y, x);
(a, b) = (b, a);
}
int ans = 0, cnt1 = 0, cnt2 = 0;
foreach (char c in s) {
if (c == a) {
cnt1++;
} else if (c == b) {
if (cnt1 > 0) {
ans += x;
cnt1--;
} else {
cnt2++;
}
} else {
ans += Math.Min(cnt1, cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += Math.Min(cnt1, cnt2) * y;
return ans;
}
}
|
class Solution {
public:
int maximumGain(string s, int x, int y) {
char a = 'a', b = 'b';
if (x < y) {
swap(x, y);
swap(a, b);
}
int ans = 0, cnt1 = 0, cnt2 = 0;
for (char c : s) {
if (c == a) {
cnt1++;
} else if (c == b) {
if (cnt1) {
ans += x;
cnt1--;
} else {
cnt2++;
}
} else {
ans += min(cnt1, cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += min(cnt1, cnt2) * y;
return ans;
}
};
| null | null |
func maximumGain(s string, x int, y int) (ans int) {
a, b := 'a', 'b'
if x < y {
x, y = y, x
a, b = b, a
}
var cnt1, cnt2 int
for _, c := range s {
if c == a {
cnt1++
} else if c == b {
if cnt1 > 0 {
ans += x
cnt1--
} else {
cnt2++
}
} else {
ans += min(cnt1, cnt2) * y
cnt1, cnt2 = 0, 0
}
}
ans += min(cnt1, cnt2) * y
return
}
|
class Solution {
public int maximumGain(String s, int x, int y) {
char a = 'a', b = 'b';
if (x < y) {
int t = x;
x = y;
y = t;
char c = a;
a = b;
b = c;
}
int ans = 0, cnt1 = 0, cnt2 = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
if (c == a) {
cnt1++;
} else if (c == b) {
if (cnt1 > 0) {
ans += x;
cnt1--;
} else {
cnt2++;
}
} else {
ans += Math.min(cnt1, cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += Math.min(cnt1, cnt2) * y;
return ans;
}
}
|
function maximumGain(s, x, y) {
let [a, b] = ['a', 'b'];
if (x < y) {
[x, y] = [y, x];
[a, b] = [b, a];
}
let [ans, cnt1, cnt2] = [0, 0, 0];
for (let c of s) {
if (c === a) {
cnt1++;
} else if (c === b) {
if (cnt1) {
ans += x;
cnt1--;
} else {
cnt2++;
}
} else {
ans += Math.min(cnt1, cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += Math.min(cnt1, cnt2) * y;
return ans;
}
| null | null | null | null | null |
class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a, b = "a", "b"
if x < y:
x, y = y, x
a, b = b, a
ans = cnt1 = cnt2 = 0
for c in s:
if c == a:
cnt1 += 1
elif c == b:
if cnt1:
ans += x
cnt1 -= 1
else:
cnt2 += 1
else:
ans += min(cnt1, cnt2) * y
cnt1 = cnt2 = 0
ans += min(cnt1, cnt2) * y
return ans
| null |
impl Solution {
pub fn maximum_gain(s: String, mut x: i32, mut y: i32) -> i32 {
let (mut a, mut b) = ('a', 'b');
if x < y {
std::mem::swap(&mut x, &mut y);
std::mem::swap(&mut a, &mut b);
}
let mut ans = 0;
let mut cnt1 = 0;
let mut cnt2 = 0;
for c in s.chars() {
if c == a {
cnt1 += 1;
} else if c == b {
if cnt1 > 0 {
ans += x;
cnt1 -= 1;
} else {
cnt2 += 1;
}
} else {
ans += cnt1.min(cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += cnt1.min(cnt2) * y;
ans
}
}
| null | null | null |
function maximumGain(s: string, x: number, y: number): number {
let [a, b] = ['a', 'b'];
if (x < y) {
[x, y] = [y, x];
[a, b] = [b, a];
}
let [ans, cnt1, cnt2] = [0, 0, 0];
for (let c of s) {
if (c === a) {
cnt1++;
} else if (c === b) {
if (cnt1) {
ans += x;
cnt1--;
} else {
cnt2++;
}
} else {
ans += Math.min(cnt1, cnt2) * y;
cnt1 = 0;
cnt2 = 0;
}
}
ans += Math.min(cnt1, cnt2) * y;
return ans;
}
|
Removing Stars From a String
|
You are given a string
s
, which contains stars
*
.
In one operation, you can:
Choose a star in
s
.
Remove the closest
non-star
character to its
left
, as well as remove the star itself.
Return
the string after
all
stars have been removed
.
Note:
The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.
Example 1:
Input:
s = "leet**cod*e"
Output:
"lecoe"
Explanation:
Performing the removals from left to right:
- The closest character to the 1
st
star is 't' in "lee
t
**cod*e". s becomes "lee*cod*e".
- The closest character to the 2
nd
star is 'e' in "le
e
*cod*e". s becomes "lecod*e".
- The closest character to the 3
rd
star is 'd' in "leco
d
*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input:
s = "erase*****"
Output:
""
Explanation:
The entire string is removed, so we return an empty string.
Constraints:
1 <= s.length <= 10
5
s
consists of lowercase English letters and stars
*
.
The operation above can be performed on
s
.
| null | null |
class Solution {
public:
string removeStars(string s) {
string ans;
for (char c : s) {
if (c == '*') {
ans.pop_back();
} else {
ans.push_back(c);
}
}
return ans;
}
};
| null | null |
func removeStars(s string) string {
ans := []rune{}
for _, c := range s {
if c == '*' {
ans = ans[:len(ans)-1]
} else {
ans = append(ans, c)
}
}
return string(ans)
}
|
class Solution {
public String removeStars(String s) {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '*') {
ans.deleteCharAt(ans.length() - 1);
} else {
ans.append(s.charAt(i));
}
}
return ans.toString();
}
}
| null | null | null | null |
class Solution {
/**
* @param String $s
* @return String
*/
function removeStars($s) {
$ans = [];
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if ($c === '*') {
array_pop($ans);
} else {
$ans[] = $c;
}
}
return implode('', $ans);
}
}
| null |
class Solution:
def removeStars(self, s: str) -> str:
ans = []
for c in s:
if c == '*':
ans.pop()
else:
ans.append(c)
return ''.join(ans)
| null |
impl Solution {
pub fn remove_stars(s: String) -> String {
let mut ans = String::new();
for &c in s.as_bytes().iter() {
if c == b'*' {
ans.pop();
} else {
ans.push(char::from(c));
}
}
ans
}
}
| null | null | null |
function removeStars(s: string): string {
const ans: string[] = [];
for (const c of s) {
if (c === '*') {
ans.pop();
} else {
ans.push(c);
}
}
return ans.join('');
}
|
Maximum Product of First and Last Elements of a Subsequence
|
You are given an integer array
nums
and an integer
m
.
Return the
maximum
product of the first and last elements of any
subsequence
of
nums
of size
m
.
Example 1:
Input:
nums = [-1,-9,2,3,-2,-3,1], m = 1
Output:
81
Explanation:
The subsequence
[-9]
has the largest product of the first and last elements:
-9 * -9 = 81
. Therefore, the answer is 81.
Example 2:
Input:
nums = [1,3,-5,5,6,-4], m = 3
Output:
20
Explanation:
The subsequence
[-5, 6, -4]
has the largest product of the first and last elements.
Example 3:
Input:
nums = [2,-1,2,-6,5,2,-5,7], m = 2
Output:
35
Explanation:
The subsequence
[5, 7]
has the largest product of the first and last elements.
Constraints:
1 <= nums.length <= 10
5
-10
5
<= nums[i] <= 10
5
1 <= m <= nums.length
| null | null |
class Solution {
public:
long long maximumProduct(vector<int>& nums, int m) {
long long ans = LLONG_MIN;
int mx = INT_MIN;
int mi = INT_MAX;
for (int i = m - 1; i < nums.size(); ++i) {
int x = nums[i];
int y = nums[i - m + 1];
mi = min(mi, y);
mx = max(mx, y);
ans = max(ans, max(1LL * x * mi, 1LL * x * mx));
}
return ans;
}
};
| null | null |
func maximumProduct(nums []int, m int) int64 {
ans := int64(math.MinInt64)
mx := math.MinInt32
mi := math.MaxInt32
for i := m - 1; i < len(nums); i++ {
x := nums[i]
y := nums[i-m+1]
mi = min(mi, y)
mx = max(mx, y)
ans = max(ans, max(int64(x)*int64(mi), int64(x)*int64(mx)))
}
return ans
}
|
class Solution {
public long maximumProduct(int[] nums, int m) {
long ans = Long.MIN_VALUE;
int mx = Integer.MIN_VALUE;
int mi = Integer.MAX_VALUE;
for (int i = m - 1; i < nums.length; ++i) {
int x = nums[i];
int y = nums[i - m + 1];
mi = Math.min(mi, y);
mx = Math.max(mx, y);
ans = Math.max(ans, Math.max(1L * x * mi, 1L * x * mx));
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def maximumProduct(self, nums: List[int], m: int) -> int:
ans = mx = -inf
mi = inf
for i in range(m - 1, len(nums)):
x = nums[i]
y = nums[i - m + 1]
mi = min(mi, y)
mx = max(mx, y)
ans = max(ans, x * mi, x * mx)
return ans
| null | null | null | null | null |
function maximumProduct(nums: number[], m: number): number {
let ans = Number.MIN_SAFE_INTEGER;
let mx = Number.MIN_SAFE_INTEGER;
let mi = Number.MAX_SAFE_INTEGER;
for (let i = m - 1; i < nums.length; i++) {
const x = nums[i];
const y = nums[i - m + 1];
mi = Math.min(mi, y);
mx = Math.max(mx, y);
ans = Math.max(ans, x * mi, x * mx);
}
return ans;
}
|
The Number of Users That Are Eligible for Discount 🔒
|
Table:
Purchases
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| user_id | int |
| time_stamp | datetime |
| amount | int |
+-------------+----------+
(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.
Each row contains information about the purchase time and the amount paid for the user with ID user_id.
A user is eligible for a discount if they had a purchase in the inclusive interval of time
[startDate, endDate]
with at least
minAmount
amount. To convert the dates to times, both dates should be considered as the
start
of the day (i.e.,
endDate = 2022-03-05
should be considered as the time
2022-03-05 00:00:00
).
Write a solution to report the number of users that are eligible for a discount.
The result format is in the following example.
Example 1:
Input:
Purchases table:
+---------+---------------------+--------+
| user_id | time_stamp | amount |
+---------+---------------------+--------+
| 1 | 2022-04-20 09:03:00 | 4416 |
| 2 | 2022-03-19 19:24:02 | 678 |
| 3 | 2022-03-18 12:03:09 | 4523 |
| 3 | 2022-03-30 09:43:42 | 626 |
+---------+---------------------+--------+
startDate = 2022-03-08, endDate = 2022-03-20, minAmount = 1000
Output:
+----------+
| user_cnt |
+----------+
| 1 |
+----------+
Explanation:
Out of the three users, only User 3 is eligible for a discount.
- User 1 had one purchase with at least minAmount amount, but not within the time interval.
- User 2 had one purchase within the time interval, but with less than minAmount amount.
- User 3 is the only user who had a purchase that satisfies both conditions.
Important Note:
This problem is basically the same as
The Users That Are Eligible for Discount
.
| null | null | null | null | null | null | null | null | null |
CREATE FUNCTION getUserIDs(startDate DATE, endDate DATE, minAmount INT) RETURNS INT
BEGIN
RETURN (
SELECT COUNT(DISTINCT user_id) AS user_cnt
FROM Purchases
WHERE time_stamp BETWEEN startDate AND endDate AND amount >= minAmount
);
END
| null | null | null | null | null | null | null | null | null | null |
Find the Number of Good Pairs II
|
You are given 2 integer arrays
nums1
and
nums2
of lengths
n
and
m
respectively. You are also given a
positive
integer
k
.
A pair
(i, j)
is called
good
if
nums1[i]
is divisible by
nums2[j] * k
(
0 <= i <= n - 1
,
0 <= j <= m - 1
).
Return the total number of
good
pairs.
Example 1:
Input:
nums1 = [1,3,4], nums2 = [1,3,4], k = 1
Output:
5
Explanation:
The 5 good pairs are
(0, 0)
,
(1, 0)
,
(1, 1)
,
(2, 0)
, and
(2, 2)
.
Example 2:
Input:
nums1 = [1,2,4,12], nums2 = [2,4], k = 3
Output:
2
Explanation:
The 2 good pairs are
(3, 0)
and
(3, 1)
.
Constraints:
1 <= n, m <= 10
5
1 <= nums1[i], nums2[j] <= 10
6
1 <= k <= 10
3
| null | null |
class Solution {
public:
long long numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
unordered_map<int, int> cnt1;
for (int x : nums1) {
if (x % k == 0) {
cnt1[x / k]++;
}
}
if (cnt1.empty()) {
return 0;
}
unordered_map<int, int> cnt2;
for (int x : nums2) {
++cnt2[x];
}
int mx = 0;
for (auto& [x, _] : cnt1) {
mx = max(mx, x);
}
long long ans = 0;
for (auto& [x, v] : cnt2) {
long long s = 0;
for (int y = x; y <= mx; y += x) {
s += cnt1[y];
}
ans += s * v;
}
return ans;
}
};
| null | null |
func numberOfPairs(nums1 []int, nums2 []int, k int) (ans int64) {
cnt1 := map[int]int{}
for _, x := range nums1 {
if x%k == 0 {
cnt1[x/k]++
}
}
if len(cnt1) == 0 {
return 0
}
cnt2 := map[int]int{}
for _, x := range nums2 {
cnt2[x]++
}
mx := 0
for x := range cnt1 {
mx = max(mx, x)
}
for x, v := range cnt2 {
s := 0
for y := x; y <= mx; y += x {
s += cnt1[y]
}
ans += int64(s) * int64(v)
}
return
}
|
class Solution {
public long numberOfPairs(int[] nums1, int[] nums2, int k) {
Map<Integer, Integer> cnt1 = new HashMap<>();
for (int x : nums1) {
if (x % k == 0) {
cnt1.merge(x / k, 1, Integer::sum);
}
}
if (cnt1.isEmpty()) {
return 0;
}
Map<Integer, Integer> cnt2 = new HashMap<>();
for (int x : nums2) {
cnt2.merge(x, 1, Integer::sum);
}
long ans = 0;
int mx = Collections.max(cnt1.keySet());
for (var e : cnt2.entrySet()) {
int x = e.getKey(), v = e.getValue();
int s = 0;
for (int y = x; y <= mx; y += x) {
s += cnt1.getOrDefault(y, 0);
}
ans += 1L * s * v;
}
return ans;
}
}
| null | null | null | null | null | null |
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
cnt1 = Counter(x // k for x in nums1 if x % k == 0)
if not cnt1:
return 0
cnt2 = Counter(nums2)
ans = 0
mx = max(cnt1)
for x, v in cnt2.items():
s = sum(cnt1[y] for y in range(x, mx + 1, x))
ans += s * v
return ans
| null | null | null | null | null |
function numberOfPairs(nums1: number[], nums2: number[], k: number): number {
const cnt1: Map<number, number> = new Map();
for (const x of nums1) {
if (x % k === 0) {
cnt1.set((x / k) | 0, (cnt1.get((x / k) | 0) || 0) + 1);
}
}
if (cnt1.size === 0) {
return 0;
}
const cnt2: Map<number, number> = new Map();
for (const x of nums2) {
cnt2.set(x, (cnt2.get(x) || 0) + 1);
}
const mx = Math.max(...cnt1.keys());
let ans = 0;
for (const [x, v] of cnt2) {
let s = 0;
for (let y = x; y <= mx; y += x) {
s += cnt1.get(y) || 0;
}
ans += s * v;
}
return ans;
}
|
Append Characters to String to Make Subsequence
|
You are given two strings
s
and
t
consisting of only lowercase English letters.
Return
the minimum number of characters that need to be appended to the end of
s
so that
t
becomes a
subsequence
of
s
.
A
subsequence
is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input:
s = "coaching", t = "coding"
Output:
4
Explanation:
Append the characters "ding" to the end of s so that s = "coachingding".
Now, t is a subsequence of s ("
co
aching
ding
").
It can be shown that appending any 3 characters to the end of s will never make t a subsequence.
Example 2:
Input:
s = "abcde", t = "a"
Output:
0
Explanation:
t is already a subsequence of s ("
a
bcde").
Example 3:
Input:
s = "z", t = "abcde"
Output:
5
Explanation:
Append the characters "abcde" to the end of s so that s = "zabcde".
Now, t is a subsequence of s ("z
abcde
").
It can be shown that appending any 4 characters to the end of s will never make t a subsequence.
Constraints:
1 <= s.length, t.length <= 10
5
s
and
t
consist only of lowercase English letters.
| null | null |
class Solution {
public:
int appendCharacters(string s, string t) {
int n = t.length(), j = 0;
for (int i = 0; i < s.size() && j < n; ++i) {
if (s[i] == t[j]) {
++j;
}
}
return n - j;
}
};
| null | null |
func appendCharacters(s string, t string) int {
n, j := len(t), 0
for _, c := range s {
if j < n && byte(c) == t[j] {
j++
}
}
return n - j
}
|
class Solution {
public int appendCharacters(String s, String t) {
int n = t.length(), j = 0;
for (int i = 0; i < s.length() && j < n; ++i) {
if (s.charAt(i) == t.charAt(j)) {
++j;
}
}
return n - j;
}
}
| null | null | null | null | null | null |
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
n, j = len(t), 0
for c in s:
if j < n and c == t[j]:
j += 1
return n - j
| null | null | null | null | null |
function appendCharacters(s: string, t: string): number {
let j = 0;
for (const c of s) {
if (c === t[j]) {
++j;
}
}
return t.length - j;
}
|
Find the Index of the Large Integer 🔒
|
We have an integer array
arr
, where all the integers in
arr
are equal except for one integer which is
larger
than the rest of the integers. You will not be given direct access to the array, instead, you will have an
API
ArrayReader
which have the following functions:
int compareSub(int l, int r, int x, int y)
: where
0 <= l, r, x, y < ArrayReader.length()
,
l <= r and
x <= y
. The function compares the sum of sub-array
arr[l..r]
with the sum of the sub-array
arr[x..y]
and returns:
1
if
arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y]
.
0
if
arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y]
.
-1
if
arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y]
.
int length()
: Returns the size of the array.
You are allowed to call
compareSub()
20 times
at most. You can assume both functions work in
O(1)
time.
Return
the index of the array
arr
which has the largest integer
.
Example 1:
Input:
arr = [7,7,7,7,10,7,7,7]
Output:
4
Explanation:
The following calls to the API
reader.compareSub(0, 0, 1, 1) // returns 0 this is a query comparing the sub-array (0, 0) with the sub array (1, 1), (i.e. compares arr[0] with arr[1]).
Thus we know that arr[0] and arr[1] doesn't contain the largest element.
reader.compareSub(2, 2, 3, 3) // returns 0, we can exclude arr[2] and arr[3].
reader.compareSub(4, 4, 5, 5) // returns 1, thus for sure arr[4] is the largest element in the array.
Notice that we made only 3 calls, so the answer is valid.
Example 2:
Input:
nums = [6,6,12]
Output:
2
Constraints:
2 <= arr.length <= 5 * 10
5
1 <= arr[i] <= 100
All elements of
arr
are equal except for one element which is larger than all other elements.
Follow up:
What if there are two numbers in
arr
that are bigger than all other numbers?
What if there is one number that is bigger than other numbers and one number that is smaller than other numbers?
| null | null |
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* class ArrayReader {
* public:
* // Compares the sum of arr[l..r] with the sum of arr[x..y]
* // return 1 if sum(arr[l..r]) > sum(arr[x..y])
* // return 0 if sum(arr[l..r]) == sum(arr[x..y])
* // return -1 if sum(arr[l..r]) < sum(arr[x..y])
* int compareSub(int l, int r, int x, int y);
*
* // Returns the length of the array
* int length();
* };
*/
class Solution {
public:
int getIndex(ArrayReader& reader) {
int left = 0, right = reader.length() - 1;
while (left < right) {
int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1;
int cmp = reader.compareSub(t1, t2, t2 + 1, t3);
if (cmp == 0) {
left = t3 + 1;
} else if (cmp == 1) {
right = t2;
} else {
left = t2 + 1;
right = t3;
}
}
return left;
}
};
| null | null |
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* type ArrayReader struct {
* }
* // Compares the sum of arr[l..r] with the sum of arr[x..y]
* // return 1 if sum(arr[l..r]) > sum(arr[x..y])
* // return 0 if sum(arr[l..r]) == sum(arr[x..y])
* // return -1 if sum(arr[l..r]) < sum(arr[x..y])
* func (this *ArrayReader) compareSub(l, r, x, y int) int {}
*
* // Returns the length of the array
* func (this *ArrayReader) length() int {}
*/
func getIndex(reader *ArrayReader) int {
left, right := 0, reader.length()-1
for left < right {
t1, t2, t3 := left, left+(right-left)/3, left+(right-left)/3*2+1
cmp := reader.compareSub(t1, t2, t2+1, t3)
if cmp == 0 {
left = t3 + 1
} else if cmp == 1 {
right = t2
} else {
left, right = t2+1, t3
}
}
return left
}
|
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* // Compares the sum of arr[l..r] with the sum of arr[x..y]
* // return 1 if sum(arr[l..r]) > sum(arr[x..y])
* // return 0 if sum(arr[l..r]) == sum(arr[x..y])
* // return -1 if sum(arr[l..r]) < sum(arr[x..y])
* public int compareSub(int l, int r, int x, int y) {}
*
* // Returns the length of the array
* public int length() {}
* }
*/
class Solution {
public int getIndex(ArrayReader reader) {
int left = 0, right = reader.length() - 1;
while (left < right) {
int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1;
int cmp = reader.compareSub(t1, t2, t2 + 1, t3);
if (cmp == 0) {
left = t3 + 1;
} else if (cmp == 1) {
right = t2;
} else {
left = t2 + 1;
right = t3;
}
}
return left;
}
}
| null | null | null | null | null | null |
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader(object):
# # Compares the sum of arr[l..r] with the sum of arr[x..y]
# # return 1 if sum(arr[l..r]) > sum(arr[x..y])
# # return 0 if sum(arr[l..r]) == sum(arr[x..y])
# # return -1 if sum(arr[l..r]) < sum(arr[x..y])
# def compareSub(self, l: int, r: int, x: int, y: int) -> int:
#
# # Returns the length of the array
# def length(self) -> int:
#
class Solution:
def getIndex(self, reader: 'ArrayReader') -> int:
left, right = 0, reader.length() - 1
while left < right:
t1, t2, t3 = (
left,
left + (right - left) // 3,
left + ((right - left) // 3) * 2 + 1,
)
cmp = reader.compareSub(t1, t2, t2 + 1, t3)
if cmp == 0:
left = t3 + 1
elif cmp == 1:
right = t2
else:
left, right = t2 + 1, t3
return left
| null | null | null | null | null | null |
Average Value of Even Numbers That Are Divisible by Three
|
Given an integer array
nums
of
positive
integers, return
the average value of all even integers that are divisible by
3
.
Note that the
average
of
n
elements is the
sum
of the
n
elements divided by
n
and
rounded down
to the nearest integer.
Example 1:
Input:
nums = [1,3,6,10,12,15]
Output:
9
Explanation:
6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.
Example 2:
Input:
nums = [1,2,4,7,10]
Output:
0
Explanation:
There is no single number that satisfies the requirement, so return 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
|
int averageValue(int* nums, int numsSize) {
int s = 0, n = 0;
for (int i = 0; i < numsSize; ++i) {
if (nums[i] % 6 == 0) {
s += nums[i];
++n;
}
}
return n == 0 ? 0 : s / n;
}
| null |
class Solution {
public:
int averageValue(vector<int>& nums) {
int s = 0, n = 0;
for (int x : nums) {
if (x % 6 == 0) {
s += x;
++n;
}
}
return n == 0 ? 0 : s / n;
}
};
| null | null |
func averageValue(nums []int) int {
var s, n int
for _, x := range nums {
if x%6 == 0 {
s += x
n++
}
}
if n == 0 {
return 0
}
return s / n
}
|
class Solution {
public int averageValue(int[] nums) {
int s = 0, n = 0;
for (int x : nums) {
if (x % 6 == 0) {
s += x;
++n;
}
}
return n == 0 ? 0 : s / n;
}
}
| null | null | null | null | null | null |
class Solution:
def averageValue(self, nums: List[int]) -> int:
s = n = 0
for x in nums:
if x % 6 == 0:
s += x
n += 1
return 0 if n == 0 else s // n
| null |
impl Solution {
pub fn average_value(nums: Vec<i32>) -> i32 {
let filtered_nums: Vec<i32> = nums.iter().cloned().filter(|&n| n % 6 == 0).collect();
if filtered_nums.is_empty() {
return 0;
}
filtered_nums.iter().sum::<i32>() / (filtered_nums.len() as i32)
}
}
| null | null | null |
function averageValue(nums: number[]): number {
let s = 0;
let n = 0;
for (const x of nums) {
if (x % 6 === 0) {
s += x;
++n;
}
}
return n === 0 ? 0 : ~~(s / n);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.