id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
2,982
|
Find Longest Special Substring That Occurs Thrice II
|
Medium
|
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p>
<p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>"abc"</code> is not special, whereas the strings <code>"ddd"</code>, <code>"zz"</code>, and <code>"f"</code> are special.</p>
<p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p>
<p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest special substring which occurs thrice is "aa": substrings "<u><strong>aa</strong></u>aa", "a<u><strong>aa</strong></u>a", and "aa<u><strong>aa</strong></u>".
It can be shown that the maximum length achievable is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcdef"
<strong>Output:</strong> -1
<strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcaba"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest special substring which occurs thrice is "a": substrings "<u><strong>a</strong></u>bcaba", "abc<u><strong>a</strong></u>ba", and "abcab<u><strong>a</strong></u>".
It can be shown that the maximum length achievable is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Counting; Sliding Window
|
C++
|
class Solution {
public:
int maximumLength(string s) {
int n = s.size();
int l = 0, r = n;
auto check = [&](int x) {
int cnt[26]{};
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && s[j] == s[i]) {
++j;
}
int k = s[i] - 'a';
cnt[k] += max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
};
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l == 0 ? -1 : l;
}
};
|
2,982
|
Find Longest Special Substring That Occurs Thrice II
|
Medium
|
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p>
<p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>"abc"</code> is not special, whereas the strings <code>"ddd"</code>, <code>"zz"</code>, and <code>"f"</code> are special.</p>
<p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p>
<p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest special substring which occurs thrice is "aa": substrings "<u><strong>aa</strong></u>aa", "a<u><strong>aa</strong></u>a", and "aa<u><strong>aa</strong></u>".
It can be shown that the maximum length achievable is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcdef"
<strong>Output:</strong> -1
<strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcaba"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest special substring which occurs thrice is "a": substrings "<u><strong>a</strong></u>bcaba", "abc<u><strong>a</strong></u>ba", and "abcab<u><strong>a</strong></u>".
It can be shown that the maximum length achievable is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Counting; Sliding Window
|
Go
|
func maximumLength(s string) int {
n := len(s)
l, r := 0, n
check := func(x int) bool {
cnt := [26]int{}
for i := 0; i < n; {
j := i + 1
for j < n && s[j] == s[i] {
j++
}
k := s[i] - 'a'
cnt[k] += max(0, j-i-x+1)
if cnt[k] >= 3 {
return true
}
i = j
}
return false
}
for l < r {
mid := (l + r + 1) >> 1
if check(mid) {
l = mid
} else {
r = mid - 1
}
}
if l == 0 {
return -1
}
return l
}
|
2,982
|
Find Longest Special Substring That Occurs Thrice II
|
Medium
|
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p>
<p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>"abc"</code> is not special, whereas the strings <code>"ddd"</code>, <code>"zz"</code>, and <code>"f"</code> are special.</p>
<p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p>
<p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest special substring which occurs thrice is "aa": substrings "<u><strong>aa</strong></u>aa", "a<u><strong>aa</strong></u>a", and "aa<u><strong>aa</strong></u>".
It can be shown that the maximum length achievable is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcdef"
<strong>Output:</strong> -1
<strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcaba"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest special substring which occurs thrice is "a": substrings "<u><strong>a</strong></u>bcaba", "abc<u><strong>a</strong></u>ba", and "abcab<u><strong>a</strong></u>".
It can be shown that the maximum length achievable is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Counting; Sliding Window
|
Java
|
class Solution {
private String s;
private int n;
public int maximumLength(String s) {
this.s = s;
n = s.length();
int l = 0, r = n;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l == 0 ? -1 : l;
}
private boolean check(int x) {
int[] cnt = new int[26];
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && s.charAt(j) == s.charAt(i)) {
j++;
}
int k = s.charAt(i) - 'a';
cnt[k] += Math.max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
}
}
|
2,982
|
Find Longest Special Substring That Occurs Thrice II
|
Medium
|
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p>
<p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>"abc"</code> is not special, whereas the strings <code>"ddd"</code>, <code>"zz"</code>, and <code>"f"</code> are special.</p>
<p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p>
<p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest special substring which occurs thrice is "aa": substrings "<u><strong>aa</strong></u>aa", "a<u><strong>aa</strong></u>a", and "aa<u><strong>aa</strong></u>".
It can be shown that the maximum length achievable is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcdef"
<strong>Output:</strong> -1
<strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcaba"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest special substring which occurs thrice is "a": substrings "<u><strong>a</strong></u>bcaba", "abc<u><strong>a</strong></u>ba", and "abcab<u><strong>a</strong></u>".
It can be shown that the maximum length achievable is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Counting; Sliding Window
|
Python
|
class Solution:
def maximumLength(self, s: str) -> int:
def check(x: int) -> bool:
cnt = defaultdict(int)
i = 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cnt[s[i]] += max(0, j - i - x + 1)
i = j
return max(cnt.values()) >= 3
n = len(s)
l, r = 0, n
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return -1 if l == 0 else l
|
2,982
|
Find Longest Special Substring That Occurs Thrice II
|
Medium
|
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p>
<p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>"abc"</code> is not special, whereas the strings <code>"ddd"</code>, <code>"zz"</code>, and <code>"f"</code> are special.</p>
<p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p>
<p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest special substring which occurs thrice is "aa": substrings "<u><strong>aa</strong></u>aa", "a<u><strong>aa</strong></u>a", and "aa<u><strong>aa</strong></u>".
It can be shown that the maximum length achievable is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcdef"
<strong>Output:</strong> -1
<strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcaba"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The longest special substring which occurs thrice is "a": substrings "<u><strong>a</strong></u>bcaba", "abc<u><strong>a</strong></u>ba", and "abcab<u><strong>a</strong></u>".
It can be shown that the maximum length achievable is 1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Counting; Sliding Window
|
TypeScript
|
function maximumLength(s: string): number {
const n = s.length;
let [l, r] = [0, n];
const check = (x: number): boolean => {
const cnt: number[] = Array(26).fill(0);
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && s[j] === s[i]) {
j++;
}
const k = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
cnt[k] += Math.max(0, j - i - x + 1);
if (cnt[k] >= 3) {
return true;
}
i = j;
}
return false;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l === 0 ? -1 : l;
}
|
2,983
|
Palindrome Rearrangement Queries
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code> having an <strong>even</strong> length <code>n</code>.</p>
<p>You are also given a <strong>0-indexed</strong> 2D integer array, <code>queries</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, d<sub>i</sub>]</code>.</p>
<p>For each query <code>i</code>, you are allowed to perform the following operations:</p>
<ul>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[a<sub>i</sub>:b<sub>i</sub>]</code>, where <code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code>.</li>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[c<sub>i</sub>:d<sub>i</sub>]</code>, where <code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n</code>.</li>
</ul>
<p>For each query, your task is to determine whether it is possible to make <code>s</code> a <strong>palindrome</strong> by performing the operations.</p>
<p>Each query is answered <strong>independently</strong> of the others.</p>
<p>Return <em>a <strong>0-indexed</strong> array </em><code>answer</code><em>, where </em><code>answer[i] == true</code><em> if it is possible to make </em><code>s</code><em> a palindrome by performing operations specified by the </em><code>i<sup>th</sup></code><em> query, and </em><code>false</code><em> otherwise.</em></p>
<ul>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
<li><code>s[x:y]</code> represents the substring consisting of characters from the index <code>x</code> to index <code>y</code> in <code>s</code>, <strong>both inclusive</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]
<strong>Output:</strong> [true,true]
<strong>Explanation:</strong> In this example, there are two queries:
In the first query:
- a<sub>0</sub> = 1, b<sub>0</sub> = 1, c<sub>0</sub> = 3, d<sub>0</sub> = 5.
- So, you are allowed to rearrange s[1:1] => a<u>b</u>cabc and s[3:5] => abc<u>abc</u>.
- To make s a palindrome, s[3:5] can be rearranged to become => abc<u>cba</u>.
- Now, s is a palindrome. So, answer[0] = true.
In the second query:
- a<sub>1</sub> = 0, b<sub>1</sub> = 2, c<sub>1</sub> = 5, d<sub>1</sub> = 5.
- So, you are allowed to rearrange s[0:2] => <u>abc</u>abc and s[5:5] => abcab<u>c</u>.
- To make s a palindrome, s[0:2] can be rearranged to become => <u>cba</u>abc.
- Now, s is a palindrome. So, answer[1] = true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abbcdecbba", queries = [[0,2,7,9]]
<strong>Output:</strong> [false]
<strong>Explanation:</strong> In this example, there is only one query.
a<sub>0</sub> = 0, b<sub>0</sub> = 2, c<sub>0</sub> = 7, d<sub>0</sub> = 9.
So, you are allowed to rearrange s[0:2] => <u>abb</u>cdecbba and s[7:9] => abbcdec<u>bba</u>.
It is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.
So, answer[0] = false.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "acbcab", queries = [[1,2,4,5]]
<strong>Output:</strong> [true]
<strong>Explanation: </strong>In this example, there is only one query.
a<sub>0</sub> = 1, b<sub>0</sub> = 2, c<sub>0</sub> = 4, d<sub>0</sub> = 5.
So, you are allowed to rearrange s[1:2] => a<u>cb</u>cab and s[4:5] => acbc<u>ab</u>.
To make s a palindrome s[1:2] can be rearranged to become a<u>bc</u>cab.
Then, s[4:5] can be rearranged to become abcc<u>ba</u>.
Now, s is a palindrome. So, answer[0] = true.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 4</code></li>
<li><code>a<sub>i</sub> == queries[i][0], b<sub>i</sub> == queries[i][1]</code></li>
<li><code>c<sub>i</sub> == queries[i][2], d<sub>i</sub> == queries[i][3]</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code></li>
<li><code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n </code></li>
<li><code>n</code> is even.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Prefix Sum
|
C++
|
class Solution {
public:
vector<bool> canMakePalindromeQueries(string s, vector<vector<int>>& queries) {
int n = s.length();
int m = n / 2;
string t = string(s.begin() + m, s.end());
reverse(t.begin(), t.end());
s = string(s.begin(), s.begin() + m);
vector<vector<int>> pre1(m + 1, vector<int>(26));
vector<vector<int>> pre2(m + 1, vector<int>(26));
vector<int> diff(m + 1, 0);
for (int i = 1; i <= m; ++i) {
pre1[i] = pre1[i - 1];
pre2[i] = pre2[i - 1];
++pre1[i][s[i - 1] - 'a'];
++pre2[i][t[i - 1] - 'a'];
diff[i] = diff[i - 1] + (s[i - 1] == t[i - 1] ? 0 : 1);
}
vector<bool> ans(queries.size(), false);
for (int i = 0; i < queries.size(); ++i) {
vector<int> q = queries[i];
int a = q[0], b = q[1];
int c = n - 1 - q[3], d = n - 1 - q[2];
ans[i] = (a <= c) ? check(pre1, pre2, diff, a, b, c, d) : check(pre2, pre1, diff, c, d, a, b);
}
return ans;
}
private:
bool check(const vector<vector<int>>& pre1, const vector<vector<int>>& pre2, const vector<int>& diff, int a, int b, int c, int d) {
if (diff[a] > 0 || diff[diff.size() - 1] - diff[max(b, d) + 1] > 0) {
return false;
}
if (d <= b) {
return count(pre1, a, b) == count(pre2, a, b);
}
if (b < c) {
return diff[c] - diff[b + 1] == 0 && count(pre1, a, b) == count(pre2, a, b) && count(pre1, c, d) == count(pre2, c, d);
}
vector<int> cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1));
vector<int> cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d));
return cnt1 != vector<int>() && cnt2 != vector<int>() && cnt1 == cnt2;
}
vector<int> count(const vector<vector<int>>& pre, int i, int j) {
vector<int> cnt(26);
for (int k = 0; k < 26; ++k) {
cnt[k] = pre[j + 1][k] - pre[i][k];
}
return cnt;
}
vector<int> sub(const vector<int>& cnt1, const vector<int>& cnt2) {
vector<int> cnt(26);
for (int i = 0; i < 26; ++i) {
cnt[i] = cnt1[i] - cnt2[i];
if (cnt[i] < 0) {
return vector<int>();
}
}
return cnt;
}
};
|
2,983
|
Palindrome Rearrangement Queries
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code> having an <strong>even</strong> length <code>n</code>.</p>
<p>You are also given a <strong>0-indexed</strong> 2D integer array, <code>queries</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, d<sub>i</sub>]</code>.</p>
<p>For each query <code>i</code>, you are allowed to perform the following operations:</p>
<ul>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[a<sub>i</sub>:b<sub>i</sub>]</code>, where <code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code>.</li>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[c<sub>i</sub>:d<sub>i</sub>]</code>, where <code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n</code>.</li>
</ul>
<p>For each query, your task is to determine whether it is possible to make <code>s</code> a <strong>palindrome</strong> by performing the operations.</p>
<p>Each query is answered <strong>independently</strong> of the others.</p>
<p>Return <em>a <strong>0-indexed</strong> array </em><code>answer</code><em>, where </em><code>answer[i] == true</code><em> if it is possible to make </em><code>s</code><em> a palindrome by performing operations specified by the </em><code>i<sup>th</sup></code><em> query, and </em><code>false</code><em> otherwise.</em></p>
<ul>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
<li><code>s[x:y]</code> represents the substring consisting of characters from the index <code>x</code> to index <code>y</code> in <code>s</code>, <strong>both inclusive</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]
<strong>Output:</strong> [true,true]
<strong>Explanation:</strong> In this example, there are two queries:
In the first query:
- a<sub>0</sub> = 1, b<sub>0</sub> = 1, c<sub>0</sub> = 3, d<sub>0</sub> = 5.
- So, you are allowed to rearrange s[1:1] => a<u>b</u>cabc and s[3:5] => abc<u>abc</u>.
- To make s a palindrome, s[3:5] can be rearranged to become => abc<u>cba</u>.
- Now, s is a palindrome. So, answer[0] = true.
In the second query:
- a<sub>1</sub> = 0, b<sub>1</sub> = 2, c<sub>1</sub> = 5, d<sub>1</sub> = 5.
- So, you are allowed to rearrange s[0:2] => <u>abc</u>abc and s[5:5] => abcab<u>c</u>.
- To make s a palindrome, s[0:2] can be rearranged to become => <u>cba</u>abc.
- Now, s is a palindrome. So, answer[1] = true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abbcdecbba", queries = [[0,2,7,9]]
<strong>Output:</strong> [false]
<strong>Explanation:</strong> In this example, there is only one query.
a<sub>0</sub> = 0, b<sub>0</sub> = 2, c<sub>0</sub> = 7, d<sub>0</sub> = 9.
So, you are allowed to rearrange s[0:2] => <u>abb</u>cdecbba and s[7:9] => abbcdec<u>bba</u>.
It is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.
So, answer[0] = false.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "acbcab", queries = [[1,2,4,5]]
<strong>Output:</strong> [true]
<strong>Explanation: </strong>In this example, there is only one query.
a<sub>0</sub> = 1, b<sub>0</sub> = 2, c<sub>0</sub> = 4, d<sub>0</sub> = 5.
So, you are allowed to rearrange s[1:2] => a<u>cb</u>cab and s[4:5] => acbc<u>ab</u>.
To make s a palindrome s[1:2] can be rearranged to become a<u>bc</u>cab.
Then, s[4:5] can be rearranged to become abcc<u>ba</u>.
Now, s is a palindrome. So, answer[0] = true.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 4</code></li>
<li><code>a<sub>i</sub> == queries[i][0], b<sub>i</sub> == queries[i][1]</code></li>
<li><code>c<sub>i</sub> == queries[i][2], d<sub>i</sub> == queries[i][3]</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code></li>
<li><code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n </code></li>
<li><code>n</code> is even.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Prefix Sum
|
Go
|
func canMakePalindromeQueries(s string, queries [][]int) (ans []bool) {
n := len(s)
m := n / 2
t := reverse(s[m:])
s = s[:m]
pre1 := make([][]int, m+1)
pre2 := make([][]int, m+1)
diff := make([]int, m+1)
pre1[0] = make([]int, 26)
pre2[0] = make([]int, 26)
for i := 1; i <= m; i++ {
pre1[i] = slices.Clone(pre1[i-1])
pre2[i] = slices.Clone(pre2[i-1])
pre1[i][int(s[i-1]-'a')]++
pre2[i][int(t[i-1]-'a')]++
diff[i] = diff[i-1]
if s[i-1] != t[i-1] {
diff[i]++
}
}
for _, q := range queries {
a, b := q[0], q[1]
c, d := n-1-q[3], n-1-q[2]
if a <= c {
ans = append(ans, check(pre1, pre2, diff, a, b, c, d))
} else {
ans = append(ans, check(pre2, pre1, diff, c, d, a, b))
}
}
return
}
func check(pre1, pre2 [][]int, diff []int, a, b, c, d int) bool {
if diff[a] > 0 || diff[len(diff)-1]-diff[max(b, d)+1] > 0 {
return false
}
if d <= b {
return slices.Equal(count(pre1, a, b), count(pre2, a, b))
}
if b < c {
return diff[c]-diff[b+1] == 0 && slices.Equal(count(pre1, a, b), count(pre2, a, b)) && slices.Equal(count(pre1, c, d), count(pre2, c, d))
}
cnt1 := sub(count(pre1, a, b), count(pre2, a, c-1))
cnt2 := sub(count(pre2, c, d), count(pre1, b+1, d))
return !slices.Equal(cnt1, []int{}) && !slices.Equal(cnt2, []int{}) && slices.Equal(cnt1, cnt2)
}
func count(pre [][]int, i, j int) []int {
cnt := make([]int, 26)
for k := 0; k < 26; k++ {
cnt[k] = pre[j+1][k] - pre[i][k]
}
return cnt
}
func sub(cnt1, cnt2 []int) []int {
cnt := make([]int, 26)
for i := 0; i < 26; i++ {
cnt[i] = cnt1[i] - cnt2[i]
if cnt[i] < 0 {
return []int{}
}
}
return cnt
}
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
|
2,983
|
Palindrome Rearrangement Queries
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code> having an <strong>even</strong> length <code>n</code>.</p>
<p>You are also given a <strong>0-indexed</strong> 2D integer array, <code>queries</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, d<sub>i</sub>]</code>.</p>
<p>For each query <code>i</code>, you are allowed to perform the following operations:</p>
<ul>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[a<sub>i</sub>:b<sub>i</sub>]</code>, where <code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code>.</li>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[c<sub>i</sub>:d<sub>i</sub>]</code>, where <code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n</code>.</li>
</ul>
<p>For each query, your task is to determine whether it is possible to make <code>s</code> a <strong>palindrome</strong> by performing the operations.</p>
<p>Each query is answered <strong>independently</strong> of the others.</p>
<p>Return <em>a <strong>0-indexed</strong> array </em><code>answer</code><em>, where </em><code>answer[i] == true</code><em> if it is possible to make </em><code>s</code><em> a palindrome by performing operations specified by the </em><code>i<sup>th</sup></code><em> query, and </em><code>false</code><em> otherwise.</em></p>
<ul>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
<li><code>s[x:y]</code> represents the substring consisting of characters from the index <code>x</code> to index <code>y</code> in <code>s</code>, <strong>both inclusive</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]
<strong>Output:</strong> [true,true]
<strong>Explanation:</strong> In this example, there are two queries:
In the first query:
- a<sub>0</sub> = 1, b<sub>0</sub> = 1, c<sub>0</sub> = 3, d<sub>0</sub> = 5.
- So, you are allowed to rearrange s[1:1] => a<u>b</u>cabc and s[3:5] => abc<u>abc</u>.
- To make s a palindrome, s[3:5] can be rearranged to become => abc<u>cba</u>.
- Now, s is a palindrome. So, answer[0] = true.
In the second query:
- a<sub>1</sub> = 0, b<sub>1</sub> = 2, c<sub>1</sub> = 5, d<sub>1</sub> = 5.
- So, you are allowed to rearrange s[0:2] => <u>abc</u>abc and s[5:5] => abcab<u>c</u>.
- To make s a palindrome, s[0:2] can be rearranged to become => <u>cba</u>abc.
- Now, s is a palindrome. So, answer[1] = true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abbcdecbba", queries = [[0,2,7,9]]
<strong>Output:</strong> [false]
<strong>Explanation:</strong> In this example, there is only one query.
a<sub>0</sub> = 0, b<sub>0</sub> = 2, c<sub>0</sub> = 7, d<sub>0</sub> = 9.
So, you are allowed to rearrange s[0:2] => <u>abb</u>cdecbba and s[7:9] => abbcdec<u>bba</u>.
It is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.
So, answer[0] = false.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "acbcab", queries = [[1,2,4,5]]
<strong>Output:</strong> [true]
<strong>Explanation: </strong>In this example, there is only one query.
a<sub>0</sub> = 1, b<sub>0</sub> = 2, c<sub>0</sub> = 4, d<sub>0</sub> = 5.
So, you are allowed to rearrange s[1:2] => a<u>cb</u>cab and s[4:5] => acbc<u>ab</u>.
To make s a palindrome s[1:2] can be rearranged to become a<u>bc</u>cab.
Then, s[4:5] can be rearranged to become abcc<u>ba</u>.
Now, s is a palindrome. So, answer[0] = true.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 4</code></li>
<li><code>a<sub>i</sub> == queries[i][0], b<sub>i</sub> == queries[i][1]</code></li>
<li><code>c<sub>i</sub> == queries[i][2], d<sub>i</sub> == queries[i][3]</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code></li>
<li><code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n </code></li>
<li><code>n</code> is even.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Prefix Sum
|
Java
|
class Solution {
public boolean[] canMakePalindromeQueries(String s, int[][] queries) {
int n = s.length();
int m = n / 2;
String t = new StringBuilder(s.substring(m)).reverse().toString();
s = s.substring(0, m);
int[][] pre1 = new int[m + 1][0];
int[][] pre2 = new int[m + 1][0];
int[] diff = new int[m + 1];
pre1[0] = new int[26];
pre2[0] = new int[26];
for (int i = 1; i <= m; ++i) {
pre1[i] = pre1[i - 1].clone();
pre2[i] = pre2[i - 1].clone();
++pre1[i][s.charAt(i - 1) - 'a'];
++pre2[i][t.charAt(i - 1) - 'a'];
diff[i] = diff[i - 1] + (s.charAt(i - 1) == t.charAt(i - 1) ? 0 : 1);
}
boolean[] ans = new boolean[queries.length];
for (int i = 0; i < queries.length; ++i) {
int[] q = queries[i];
int a = q[0], b = q[1];
int c = n - 1 - q[3], d = n - 1 - q[2];
ans[i] = a <= c ? check(pre1, pre2, diff, a, b, c, d)
: check(pre2, pre1, diff, c, d, a, b);
}
return ans;
}
private boolean check(int[][] pre1, int[][] pre2, int[] diff, int a, int b, int c, int d) {
if (diff[a] > 0 || diff[diff.length - 1] - diff[Math.max(b, d) + 1] > 0) {
return false;
}
if (d <= b) {
return Arrays.equals(count(pre1, a, b), count(pre2, a, b));
}
if (b < c) {
return diff[c] - diff[b + 1] == 0 && Arrays.equals(count(pre1, a, b), count(pre2, a, b))
&& Arrays.equals(count(pre1, c, d), count(pre2, c, d));
}
int[] cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1));
int[] cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d));
return cnt1 != null && cnt2 != null && Arrays.equals(cnt1, cnt2);
}
private int[] count(int[][] pre, int i, int j) {
int[] cnt = new int[26];
for (int k = 0; k < 26; ++k) {
cnt[k] = pre[j + 1][k] - pre[i][k];
}
return cnt;
}
private int[] sub(int[] cnt1, int[] cnt2) {
int[] cnt = new int[26];
for (int i = 0; i < 26; ++i) {
cnt[i] = cnt1[i] - cnt2[i];
if (cnt[i] < 0) {
return null;
}
}
return cnt;
}
}
|
2,983
|
Palindrome Rearrangement Queries
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code> having an <strong>even</strong> length <code>n</code>.</p>
<p>You are also given a <strong>0-indexed</strong> 2D integer array, <code>queries</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, d<sub>i</sub>]</code>.</p>
<p>For each query <code>i</code>, you are allowed to perform the following operations:</p>
<ul>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[a<sub>i</sub>:b<sub>i</sub>]</code>, where <code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code>.</li>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[c<sub>i</sub>:d<sub>i</sub>]</code>, where <code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n</code>.</li>
</ul>
<p>For each query, your task is to determine whether it is possible to make <code>s</code> a <strong>palindrome</strong> by performing the operations.</p>
<p>Each query is answered <strong>independently</strong> of the others.</p>
<p>Return <em>a <strong>0-indexed</strong> array </em><code>answer</code><em>, where </em><code>answer[i] == true</code><em> if it is possible to make </em><code>s</code><em> a palindrome by performing operations specified by the </em><code>i<sup>th</sup></code><em> query, and </em><code>false</code><em> otherwise.</em></p>
<ul>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
<li><code>s[x:y]</code> represents the substring consisting of characters from the index <code>x</code> to index <code>y</code> in <code>s</code>, <strong>both inclusive</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]
<strong>Output:</strong> [true,true]
<strong>Explanation:</strong> In this example, there are two queries:
In the first query:
- a<sub>0</sub> = 1, b<sub>0</sub> = 1, c<sub>0</sub> = 3, d<sub>0</sub> = 5.
- So, you are allowed to rearrange s[1:1] => a<u>b</u>cabc and s[3:5] => abc<u>abc</u>.
- To make s a palindrome, s[3:5] can be rearranged to become => abc<u>cba</u>.
- Now, s is a palindrome. So, answer[0] = true.
In the second query:
- a<sub>1</sub> = 0, b<sub>1</sub> = 2, c<sub>1</sub> = 5, d<sub>1</sub> = 5.
- So, you are allowed to rearrange s[0:2] => <u>abc</u>abc and s[5:5] => abcab<u>c</u>.
- To make s a palindrome, s[0:2] can be rearranged to become => <u>cba</u>abc.
- Now, s is a palindrome. So, answer[1] = true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abbcdecbba", queries = [[0,2,7,9]]
<strong>Output:</strong> [false]
<strong>Explanation:</strong> In this example, there is only one query.
a<sub>0</sub> = 0, b<sub>0</sub> = 2, c<sub>0</sub> = 7, d<sub>0</sub> = 9.
So, you are allowed to rearrange s[0:2] => <u>abb</u>cdecbba and s[7:9] => abbcdec<u>bba</u>.
It is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.
So, answer[0] = false.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "acbcab", queries = [[1,2,4,5]]
<strong>Output:</strong> [true]
<strong>Explanation: </strong>In this example, there is only one query.
a<sub>0</sub> = 1, b<sub>0</sub> = 2, c<sub>0</sub> = 4, d<sub>0</sub> = 5.
So, you are allowed to rearrange s[1:2] => a<u>cb</u>cab and s[4:5] => acbc<u>ab</u>.
To make s a palindrome s[1:2] can be rearranged to become a<u>bc</u>cab.
Then, s[4:5] can be rearranged to become abcc<u>ba</u>.
Now, s is a palindrome. So, answer[0] = true.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 4</code></li>
<li><code>a<sub>i</sub> == queries[i][0], b<sub>i</sub> == queries[i][1]</code></li>
<li><code>c<sub>i</sub> == queries[i][2], d<sub>i</sub> == queries[i][3]</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code></li>
<li><code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n </code></li>
<li><code>n</code> is even.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Prefix Sum
|
Python
|
class Solution:
def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
def count(pre: List[List[int]], i: int, j: int) -> List[int]:
return [x - y for x, y in zip(pre[j + 1], pre[i])]
def sub(cnt1: List[int], cnt2: List[int]) -> List[int]:
res = []
for x, y in zip(cnt1, cnt2):
if x - y < 0:
return []
res.append(x - y)
return res
def check(
pre1: List[List[int]], pre2: List[List[int]], a: int, b: int, c: int, d: int
) -> bool:
if diff[a] > 0 or diff[m] - diff[max(b, d) + 1] > 0:
return False
if d <= b:
return count(pre1, a, b) == count(pre2, a, b)
if b < c:
return (
diff[c] - diff[b + 1] == 0
and count(pre1, a, b) == count(pre2, a, b)
and count(pre1, c, d) == count(pre2, c, d)
)
cnt1 = sub(count(pre1, a, b), count(pre2, a, c - 1))
cnt2 = sub(count(pre2, c, d), count(pre1, b + 1, d))
return bool(cnt1) and bool(cnt2) and cnt1 == cnt2
n = len(s)
m = n // 2
t = s[m:][::-1]
s = s[:m]
pre1 = [[0] * 26 for _ in range(m + 1)]
pre2 = [[0] * 26 for _ in range(m + 1)]
diff = [0] * (m + 1)
for i, (c1, c2) in enumerate(zip(s, t), 1):
pre1[i] = pre1[i - 1][:]
pre2[i] = pre2[i - 1][:]
pre1[i][ord(c1) - ord("a")] += 1
pre2[i][ord(c2) - ord("a")] += 1
diff[i] = diff[i - 1] + int(c1 != c2)
ans = []
for a, b, c, d in queries:
c, d = n - 1 - d, n - 1 - c
ok = (
check(pre1, pre2, a, b, c, d)
if a <= c
else check(pre2, pre1, c, d, a, b)
)
ans.append(ok)
return ans
|
2,983
|
Palindrome Rearrangement Queries
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code> having an <strong>even</strong> length <code>n</code>.</p>
<p>You are also given a <strong>0-indexed</strong> 2D integer array, <code>queries</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, d<sub>i</sub>]</code>.</p>
<p>For each query <code>i</code>, you are allowed to perform the following operations:</p>
<ul>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[a<sub>i</sub>:b<sub>i</sub>]</code>, where <code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code>.</li>
<li>Rearrange the characters within the <strong>substring</strong> <code>s[c<sub>i</sub>:d<sub>i</sub>]</code>, where <code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n</code>.</li>
</ul>
<p>For each query, your task is to determine whether it is possible to make <code>s</code> a <strong>palindrome</strong> by performing the operations.</p>
<p>Each query is answered <strong>independently</strong> of the others.</p>
<p>Return <em>a <strong>0-indexed</strong> array </em><code>answer</code><em>, where </em><code>answer[i] == true</code><em> if it is possible to make </em><code>s</code><em> a palindrome by performing operations specified by the </em><code>i<sup>th</sup></code><em> query, and </em><code>false</code><em> otherwise.</em></p>
<ul>
<li>A <strong>substring</strong> is a contiguous sequence of characters within a string.</li>
<li><code>s[x:y]</code> represents the substring consisting of characters from the index <code>x</code> to index <code>y</code> in <code>s</code>, <strong>both inclusive</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]
<strong>Output:</strong> [true,true]
<strong>Explanation:</strong> In this example, there are two queries:
In the first query:
- a<sub>0</sub> = 1, b<sub>0</sub> = 1, c<sub>0</sub> = 3, d<sub>0</sub> = 5.
- So, you are allowed to rearrange s[1:1] => a<u>b</u>cabc and s[3:5] => abc<u>abc</u>.
- To make s a palindrome, s[3:5] can be rearranged to become => abc<u>cba</u>.
- Now, s is a palindrome. So, answer[0] = true.
In the second query:
- a<sub>1</sub> = 0, b<sub>1</sub> = 2, c<sub>1</sub> = 5, d<sub>1</sub> = 5.
- So, you are allowed to rearrange s[0:2] => <u>abc</u>abc and s[5:5] => abcab<u>c</u>.
- To make s a palindrome, s[0:2] can be rearranged to become => <u>cba</u>abc.
- Now, s is a palindrome. So, answer[1] = true.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abbcdecbba", queries = [[0,2,7,9]]
<strong>Output:</strong> [false]
<strong>Explanation:</strong> In this example, there is only one query.
a<sub>0</sub> = 0, b<sub>0</sub> = 2, c<sub>0</sub> = 7, d<sub>0</sub> = 9.
So, you are allowed to rearrange s[0:2] => <u>abb</u>cdecbba and s[7:9] => abbcdec<u>bba</u>.
It is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.
So, answer[0] = false.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "acbcab", queries = [[1,2,4,5]]
<strong>Output:</strong> [true]
<strong>Explanation: </strong>In this example, there is only one query.
a<sub>0</sub> = 1, b<sub>0</sub> = 2, c<sub>0</sub> = 4, d<sub>0</sub> = 5.
So, you are allowed to rearrange s[1:2] => a<u>cb</u>cab and s[4:5] => acbc<u>ab</u>.
To make s a palindrome s[1:2] can be rearranged to become a<u>bc</u>cab.
Then, s[4:5] can be rearranged to become abcc<u>ba</u>.
Now, s is a palindrome. So, answer[0] = true.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 4</code></li>
<li><code>a<sub>i</sub> == queries[i][0], b<sub>i</sub> == queries[i][1]</code></li>
<li><code>c<sub>i</sub> == queries[i][2], d<sub>i</sub> == queries[i][3]</code></li>
<li><code>0 <= a<sub>i</sub> <= b<sub>i</sub> < n / 2</code></li>
<li><code>n / 2 <= c<sub>i</sub> <= d<sub>i</sub> < n </code></li>
<li><code>n</code> is even.</li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Prefix Sum
|
TypeScript
|
function canMakePalindromeQueries(s: string, queries: number[][]): boolean[] {
const n: number = s.length;
const m: number = n >> 1;
const t: string = s.slice(m).split('').reverse().join('');
s = s.slice(0, m);
const pre1: number[][] = Array.from({ length: m + 1 }, () => Array(26).fill(0));
const pre2: number[][] = Array.from({ length: m + 1 }, () => Array(26).fill(0));
const diff: number[] = Array(m + 1).fill(0);
for (let i = 1; i <= m; ++i) {
pre1[i] = [...pre1[i - 1]];
pre2[i] = [...pre2[i - 1]];
++pre1[i][s.charCodeAt(i - 1) - 'a'.charCodeAt(0)];
++pre2[i][t.charCodeAt(i - 1) - 'a'.charCodeAt(0)];
diff[i] = diff[i - 1] + (s[i - 1] === t[i - 1] ? 0 : 1);
}
const ans: boolean[] = Array(queries.length).fill(false);
for (let i = 0; i < queries.length; ++i) {
const q: number[] = queries[i];
const [a, b] = [q[0], q[1]];
const [c, d] = [n - 1 - q[3], n - 1 - q[2]];
ans[i] = a <= c ? check(pre1, pre2, diff, a, b, c, d) : check(pre2, pre1, diff, c, d, a, b);
}
return ans;
}
function check(
pre1: number[][],
pre2: number[][],
diff: number[],
a: number,
b: number,
c: number,
d: number,
): boolean {
if (diff[a] > 0 || diff[diff.length - 1] - diff[Math.max(b, d) + 1] > 0) {
return false;
}
if (d <= b) {
return arraysEqual(count(pre1, a, b), count(pre2, a, b));
}
if (b < c) {
return (
diff[c] - diff[b + 1] === 0 &&
arraysEqual(count(pre1, a, b), count(pre2, a, b)) &&
arraysEqual(count(pre1, c, d), count(pre2, c, d))
);
}
const cnt1: number[] | null = sub(count(pre1, a, b), count(pre2, a, c - 1));
const cnt2: number[] | null = sub(count(pre2, c, d), count(pre1, b + 1, d));
return cnt1 !== null && cnt2 !== null && arraysEqual(cnt1, cnt2);
}
function count(pre: number[][], i: number, j: number): number[] {
const cnt: number[] = new Array(26).fill(0);
for (let k = 0; k < 26; ++k) {
cnt[k] = pre[j + 1][k] - pre[i][k];
}
return cnt;
}
function sub(cnt1: number[], cnt2: number[]): number[] | null {
const cnt: number[] = new Array(26).fill(0);
for (let i = 0; i < 26; ++i) {
cnt[i] = cnt1[i] - cnt2[i];
if (cnt[i] < 0) {
return null;
}
}
return cnt;
}
function arraysEqual(arr1: number[], arr2: number[]): boolean {
return JSON.stringify(arr1) === JSON.stringify(arr2);
}
|
2,984
|
Find Peak Calling Hours for Each City
|
Medium
|
<p>Table: <code>Calls</code></p>
<pre>
+--------------+----------+
| Column Name | Type |
+--------------+----------+
| caller_id | int |
| recipient_id | int |
| call_time | datetime |
| city | varchar |
+--------------+----------+
(caller_id, recipient_id, call_time) is the primary key (combination of columns with unique values) for this table.
Each row contains caller id, recipient id, call time, and city.
</pre>
<p>Write a solution to find the <strong>peak</strong> calling <strong>hour</strong> for each <code>city</code>. If <strong>multiple hours</strong> have the <strong>same</strong> number of calls, all of those hours will be recognized as <strong>peak hours </strong>for that specific city.</p>
<p>Return <em>the result table ordered by <strong>peak calling hour</strong> and </em><code>city</code><em> in <strong>descending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Calls table:
+-----------+--------------+---------------------+----------+
| caller_id | recipient_id | call_time | city |
+-----------+--------------+---------------------+----------+
| 8 | 4 | 2021-08-24 22:46:07 | Houston |
| 4 | 8 | 2021-08-24 22:57:13 | Houston |
| 5 | 1 | 2021-08-11 21:28:44 | Houston |
| 8 | 3 | 2021-08-17 22:04:15 | Houston |
| 11 | 3 | 2021-08-17 13:07:00 | New York |
| 8 | 11 | 2021-08-17 14:22:22 | New York |
+-----------+--------------+---------------------+----------+
<strong>Output:</strong>
+----------+-------------------+-----------------+
| city | peak_calling_hour | number_of_calls |
+----------+-------------------+-----------------+
| Houston | 22 | 3 |
| New York | 14 | 1 |
| New York | 13 | 1 |
+----------+-------------------+-----------------+
<strong>Explanation:</strong>
For Houston:
- The peak time is 22:00, with a total of 3 calls recorded.
For New York:
- Both 13:00 and 14:00 hours have equal call counts of 1, so both times are considered peak hours.
Output table is ordered by peak_calling_hour and city in descending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY city
ORDER BY cnt DESC
) AS rk
FROM
(
SELECT
city,
HOUR(call_time) AS h,
COUNT(1) AS cnt
FROM Calls
GROUP BY 1, 2
) AS t
)
SELECT city, h AS peak_calling_hour, cnt AS number_of_calls
FROM T
WHERE rk = 1
ORDER BY 2 DESC, 1 DESC;
|
2,985
|
Calculate Compressed Mean
|
Easy
|
<p>Table: <code>Orders</code></p>
<pre>
+-------------------+------+
| Column Name | Type |
+-------------------+------+
| order_id | int |
| item_count | int |
| order_occurrences | int |
+-------------------+------+
order_id is column of unique values for this table.
This table contains order_id, item_count, and order_occurrences.
</pre>
<p>Write a solution to calculate the <strong>average</strong> number of items per order, rounded to <code>2</code> <strong>decimal places</strong>.</p>
<p>Return <em>the result table</em><em> in <strong>any</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Orders table:
+----------+------------+-------------------+
| order_id | item_count | order_occurrences |
+----------+------------+-------------------+
| 10 | 1 | 500 |
| 11 | 2 | 1000 |
| 12 | 3 | 800 |
| 13 | 4 | 1000 |
+----------+------------+-------------------+
<strong>Output</strong>
+-------------------------+
| average_items_per_order |
+-------------------------+
| 2.70 |
+-------------------------+
<strong>Explanation</strong>
The calculation is as follows:
- Total items: (1 * 500) + (2 * 1000) + (3 * 800) + (4 * 1000) = 8900
- Total orders: 500 + 1000 + 800 + 1000 = 3300
- Therefore, the average items per order is 8900 / 3300 = 2.70</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
ROUND(
SUM(item_count * order_occurrences) / SUM(order_occurrences),
2
) AS average_items_per_order
FROM Orders;
|
2,986
|
Find Third Transaction
|
Medium
|
<p>Table: <code>Transactions</code></p>
<pre>
+------------------+----------+
| Column Name | Type |
+------------------+----------+
| user_id | int |
| spend | decimal |
| transaction_date | datetime |
+------------------+----------+
(user_id, transaction_date) is column of unique values for this table.
This table contains user_id, spend, and transaction_date.
</pre>
<p>Write a solution to find the <strong>third transaction </strong>(if they have at least three transactions) of every user, where the <strong>spending</strong> on the preceding <strong>two transactions</strong> is <strong>lower</strong> than the spending on the <strong>third</strong> transaction.</p>
<p>Return <em>the result table by </em><code>user_id</code><em> in <strong>ascending</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Transactions table:
+---------+--------+---------------------+
| user_id | spend | transaction_date |
+---------+--------+---------------------+
| 1 | 65.56 | 2023-11-18 13:49:42 |
| 1 | 96.0 | 2023-11-30 02:47:26 |
| 1 | 7.44 | 2023-11-02 12:15:23 |
| 1 | 49.78 | 2023-11-12 00:13:46 |
| 2 | 40.89 | 2023-11-21 04:39:15 |
| 2 | 100.44 | 2023-11-20 07:39:34 |
| 3 | 37.33 | 2023-11-03 06:22:02 |
| 3 | 13.89 | 2023-11-11 16:00:14 |
| 3 | 7.0 | 2023-11-29 22:32:36 |
+---------+--------+---------------------+
<strong>Output</strong>
+---------+-------------------------+------------------------+
| user_id | third_transaction_spend | third_transaction_date |
+---------+-------------------------+------------------------+
| 1 | 65.56 | 2023-11-18 13:49:42 |
+---------+-------------------------+------------------------+
<strong>Explanation</strong>
- For user_id 1, their third transaction occurred on 2023-11-18 at 13:49:42 with an amount of $65.56, surpassing the expenditures of the previous two transactions which were $7.44 on 2023-11-02 at 12:15:23 and $49.78 on 2023-11-12 at 00:13:46. Thus, this third transaction will be included in the output table.
- user_id 2 only has a total of 2 transactions, so there isn't a third transaction to consider.
- For user_id 3, the amount of $7.0 for their third transaction is less than that of the preceding two transactions, so it won't be included.
Output table is ordered by user_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY user_id
ORDER BY transaction_date
) AS rk,
spend > (
LAG(spend) OVER (
PARTITION BY user_id
ORDER BY transaction_date
)
)
AND spend > (
LAG(spend, 2) OVER (
PARTITION BY user_id
ORDER BY transaction_date
)
) AS st
FROM Transactions
)
SELECT user_id, spend AS third_transaction_spend, transaction_date AS third_transaction_date
FROM T
WHERE rk = 3 AND st = 1;
|
2,987
|
Find Expensive Cities
|
Easy
|
<p>Table: <code>Listings</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| listing_id | int |
| city | varchar |
| price | int |
+-------------+---------+
listing_id is column of unique values for this table.
This table contains listing_id, city, and price.
</pre>
<p>Write a solution to find <strong>cities </strong>where the <strong>average home prices</strong> exceed the <strong>national</strong> average home price.</p>
<p>Return <em>the result table sorted by </em><code>city</code><em> in <strong>ascending</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Listings table:
+------------+--------------+---------+
| listing_id | city | price |
+------------+--------------+---------+
| 113 | LosAngeles | 7560386 |
| 136 | SanFrancisco | 2380268 |
| 92 | Chicago | 9833209 |
| 60 | Chicago | 5147582 |
| 8 | Chicago | 5274441 |
| 79 | SanFrancisco | 8372065 |
| 37 | Chicago | 7939595 |
| 53 | LosAngeles | 4965123 |
| 178 | SanFrancisco | 999207 |
| 51 | NewYork | 5951718 |
| 121 | NewYork | 2893760 |
+------------+--------------+---------+
<strong>Output</strong>
+------------+
| city |
+------------+
| Chicago |
| LosAngeles |
+------------+
<strong>Explanation</strong>
The national average home price is $6,122,059.45. Among the cities listed:
- Chicago has an average price of $7,048,706.75
- Los Angeles has an average price of $6,277,754.5
- San Francisco has an average price of $3,900,513.33
- New York has an average price of $4,422,739
Only Chicago and Los Angeles have average home prices exceeding the national average. Therefore, these two cities are included in the output table. The output table is sorted in ascending order based on the city names.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT city
FROM Listings
GROUP BY city
HAVING AVG(price) > (SELECT AVG(price) FROM Listings)
ORDER BY 1;
|
2,988
|
Manager of the Largest Department
|
Medium
|
<p>Table: <code>Employees</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| emp_id | int |
| emp_name | varchar |
| dep_id | int |
| position | varchar |
+-------------+---------+
emp_id is column of unique values for this table.
This table contains emp_id, emp_name, dep_id, and position.
</pre>
<p>Write a solution to find the <strong>name</strong> of the <strong>manager</strong> from the <strong>largest department</strong>. There may be multiple largest departments when the number of employees in those departments is the same.</p>
<p>Return <em>the result table sorted by </em><code>dep_id</code><em> in <strong>ascending</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Employees table:
+--------+----------+--------+---------------+
| emp_id | emp_name | dep_id | position |
+--------+----------+--------+---------------+
| 156 | Michael | 107 | Manager |
| 112 | Lucas | 107 | Consultant |
| 8 | Isabella | 101 | Manager |
| 160 | Joseph | 100 | Manager |
| 80 | Aiden | 100 | Engineer |
| 190 | Skylar | 100 | Freelancer |
| 196 | Stella | 101 | Coordinator |
| 167 | Audrey | 100 | Consultant |
| 97 | Nathan | 101 | Supervisor |
| 128 | Ian | 101 | Administrator |
| 81 | Ethan | 107 | Administrator |
+--------+----------+--------+---------------+
<strong>Output</strong>
+--------------+--------+
| manager_name | dep_id |
+--------------+--------+
| Joseph | 100 |
| Isabella | 101 |
+--------------+--------+
<strong>Explanation</strong>
- Departments with IDs 100 and 101 each has a total of 4 employees, while department 107 has 3 employees. Since both departments 100 and 101 have an equal number of employees, their respective managers will be included.
Output table is ordered by dep_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT dep_id, COUNT(1) AS cnt
FROM Employees
GROUP BY 1
)
SELECT emp_name AS manager_name, t.dep_id
FROM
T AS t
JOIN Employees AS e ON t.dep_id = e.dep_id AND e.position = 'Manager'
WHERE cnt = (SELECT MAX(cnt) FROM T)
ORDER BY 2;
|
2,989
|
Class Performance
|
Medium
|
<p>Table: <code>Scores</code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| assignment1 | int |
| assignment2 | int |
| assignment3 | int |
+--------------+---------+
student_id is column of unique values for this table.
This table contains student_id, student_name, assignment1, assignment2, and assignment3.
</pre>
<p>Write a solution to calculate the <strong>difference</strong> in the <strong>total score</strong> (sum of all <code>3</code> assignments) between the <strong>highest score</strong> obtained by students and the <strong>lowest score</strong> obtained by them.</p>
<p>Return <em>the result table in <strong>any</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Scores table:
+------------+--------------+-------------+-------------+-------------+
| student_id | student_name | assignment1 | assignment2 | assignment3 |
+------------+--------------+-------------+-------------+-------------+
| 309 | Owen | 88 | 47 | 87 |
| 321 | Claire | 98 | 95 | 37 |
| 338 | Julian | 100 | 64 | 43 |
| 423 | Peyton | 60 | 44 | 47 |
| 896 | David | 32 | 37 | 50 |
| 235 | Camila | 31 | 53 | 69 |
+------------+--------------+-------------+-------------+-------------+
<strong>Output</strong>
+---------------------+
| difference_in_score |
+---------------------+
| 111 |
+---------------------+
<strong>Explanation</strong>
- student_id 309 has a total score of 88 + 47 + 87 = 222.
- student_id 321 has a total score of 98 + 95 + 37 = 230.
- student_id 338 has a total score of 100 + 64 + 43 = 207.
- student_id 423 has a total score of 60 + 44 + 47 = 151.
- student_id 896 has a total score of 32 + 37 + 50 = 119.
- student_id 235 has a total score of 31 + 53 + 69 = 153.
student_id 321 has the highest score of 230, while student_id 896 has the lowest score of 119. Therefore, the difference between them is 111.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
MAX(assignment1 + assignment2 + assignment3) - MIN(
assignment1 + assignment2 + assignment3
) AS difference_in_score
FROM Scores;
|
2,990
|
Loan Types
|
Easy
|
<p>Table: <code>Loans</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| loan_id | int |
| user_id | int |
| loan_type | varchar |
+-------------+---------+
loan_id is column of unique values for this table.
This table contains loan_id, user_id, and loan_type.
</pre>
<p>Write a solution to find all <strong>distinct</strong> <code>user_id</code>'s that have <strong>at least one</strong> <strong>Refinance</strong> loan type and at least one <strong>Mortgage</strong> loan type.</p>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Loans table:
+---------+---------+-----------+
| loan_id | user_id | loan_type |
+---------+---------+-----------+
| 683 | 101 | Mortgage |
| 218 | 101 | AutoLoan |
| 802 | 101 | Inschool |
| 593 | 102 | Mortgage |
| 138 | 102 | Refinance |
| 294 | 102 | Inschool |
| 308 | 103 | Refinance |
| 389 | 104 | Mortgage |
+---------+---------+-----------+
<strong>Output</strong>
+---------+
| user_id |
+---------+
| 102 |
+---------+
<strong>Explanation</strong>
- User_id 101 has three loan types, one of which is a Mortgage. However, this user does not have any loan type categorized as Refinance, so user_id 101 won't be considered.
- User_id 102 possesses three loan types: one for Mortgage and one for Refinance. Hence, user_id 102 will be included in the result.
- User_id 103 has a loan type of Refinance but lacks a Mortgage loan type, so user_id 103 won't be considered.
- User_id 104 has a Mortgage loan type but doesn't have a Refinance loan type, thus, user_id 104 won't be considered.
Output table is ordered by user_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT user_id
FROM Loans
GROUP BY 1
HAVING SUM(loan_type = 'Refinance') > 0 AND SUM(loan_type = 'Mortgage') > 0
ORDER BY 1;
|
2,991
|
Top Three Wineries
|
Hard
|
<p>Table: <code>Wineries</code></p>
<pre>
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| id | int |
| country | varchar |
| points | int |
| winery | varchar |
+-------------+----------+
id is column of unique values for this table.
This table contains id, country, points, and winery.
</pre>
<p>Write a solution to find the <strong>top three wineries</strong> in <strong>each</strong> <strong>country</strong> based on their <strong>total points</strong>. If <strong>multiple wineries</strong> have the <strong>same</strong> total points, order them by <code>winery</code> name in <strong>ascending</strong> order. If there's <strong>no second winery</strong>, output 'No second winery,' and if there's <strong>no third winery</strong>, output 'No third winery.'</p>
<p>Return <em>the result table ordered by </em><code>country</code><em> in <strong>ascending</strong> order</em><em>.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Wineries table:
+-----+-----------+--------+-----------------+
| id | country | points | winery |
+-----+-----------+--------+-----------------+
| 103 | Australia | 84 | WhisperingPines |
| 737 | Australia | 85 | GrapesGalore |
| 848 | Australia | 100 | HarmonyHill |
| 222 | Hungary | 60 | MoonlitCellars |
| 116 | USA | 47 | RoyalVines |
| 124 | USA | 45 | Eagle'sNest |
| 648 | India | 69 | SunsetVines |
| 894 | USA | 39 | RoyalVines |
| 677 | USA | 9 | PacificCrest |
+-----+-----------+--------+-----------------+
<strong>Output:</strong>
+-----------+---------------------+-------------------+----------------------+
| country | top_winery | second_winery | third_winery |
+-----------+---------------------+-------------------+----------------------+
| Australia | HarmonyHill (100) | GrapesGalore (85) | WhisperingPines (84) |
| Hungary | MoonlitCellars (60) | No second winery | No third winery |
| India | SunsetVines (69) | No second winery | No third winery |
| USA | RoyalVines (86) | Eagle'sNest (45) | PacificCrest (9) |
+-----------+---------------------+-------------------+----------------------+
<strong>Explanation</strong>
For Australia
- HarmonyHill Winery accumulates the highest score of 100 points in Australia.
- GrapesGalore Winery has a total of 85 points, securing the second-highest position in Australia.
- WhisperingPines Winery has a total of 80 points, ranking as the third-highest.
For Hungary
- MoonlitCellars is the sole winery, accruing 60 points, automatically making it the highest. There is no second or third winery.
For India
- SunsetVines is the sole winery, earning 69 points, making it the top winery. There is no second or third winery.
For the USA
- RoyalVines Wines accumulates a total of 47 + 39 = 86 points, claiming the highest position in the USA.
- Eagle'sNest has a total of 45 points, securing the second-highest position in the USA.
- PacificCrest accumulates 9 points, ranking as the third-highest winery in the USA
Output table is ordered by country in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
country,
CONCAT(winery, ' (', points, ')') AS winery,
RANK() OVER (
PARTITION BY country
ORDER BY points DESC, winery
) AS rk
FROM (SELECT country, SUM(points) AS points, winery FROM Wineries GROUP BY 1, 3) AS t
)
SELECT
t1.country,
t1.winery AS top_winery,
IFNULL(t2.winery, 'No second winery') AS second_winery,
IFNULL(t3.winery, 'No third winery') AS third_winery
FROM
T AS t1
LEFT JOIN T AS t2 ON t1.country = t2.country AND t1.rk = t2.rk - 1
LEFT JOIN T AS t3 ON t2.country = t3.country AND t2.rk = t3.rk - 1
WHERE t1.rk = 1
ORDER BY 1;
|
2,992
|
Number of Self-Divisible Permutations
|
Medium
|
<p>Given an integer <code>n</code>, return <em>the number of <strong>permutations</strong> of the <strong>1-indexed</strong> array</em> <code>nums = [1, 2, ..., n]</code><em>, such that it's <strong>self-divisible</strong></em>.</p>
<p>A <strong>1-indexed</strong> array <code>a</code> of length <code>n</code> is <strong>self-divisible</strong> if for every <code>1 <= i <= n</code>, <code><span data-keyword="gcd-function">gcd</span>(a[i], i) == 1</code>.</p>
<p>A <strong>permutation</strong> of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array <code>[1, 2, 3]</code>:</p>
<ul>
<li><code>[1, 2, 3]</code></li>
<li><code>[1, 3, 2]</code></li>
<li><code>[2, 1, 3]</code></li>
<li><code>[2, 3, 1]</code></li>
<li><code>[3, 1, 2]</code></li>
<li><code>[3, 2, 1]</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1] has only 1 permutation which is self-divisible.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 12</code></li>
</ul>
|
Bit Manipulation; Array; Math; Dynamic Programming; Backtracking; Bitmask; Number Theory
|
C++
|
class Solution {
public:
int selfDivisiblePermutationCount(int n) {
int f[1 << (n + 1)];
memset(f, -1, sizeof(f));
function<int(int)> dfs = [&](int mask) {
if (f[mask] != -1) {
return f[mask];
}
int i = __builtin_popcount(mask) + 1;
if (i > n) {
return 1;
}
f[mask] = 0;
for (int j = 1; j <= n; ++j) {
if ((mask >> j & 1) == 0 && (i % j == 0 || j % i == 0)) {
f[mask] += dfs(mask | 1 << j);
}
}
return f[mask];
};
return dfs(0);
}
};
|
2,992
|
Number of Self-Divisible Permutations
|
Medium
|
<p>Given an integer <code>n</code>, return <em>the number of <strong>permutations</strong> of the <strong>1-indexed</strong> array</em> <code>nums = [1, 2, ..., n]</code><em>, such that it's <strong>self-divisible</strong></em>.</p>
<p>A <strong>1-indexed</strong> array <code>a</code> of length <code>n</code> is <strong>self-divisible</strong> if for every <code>1 <= i <= n</code>, <code><span data-keyword="gcd-function">gcd</span>(a[i], i) == 1</code>.</p>
<p>A <strong>permutation</strong> of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array <code>[1, 2, 3]</code>:</p>
<ul>
<li><code>[1, 2, 3]</code></li>
<li><code>[1, 3, 2]</code></li>
<li><code>[2, 1, 3]</code></li>
<li><code>[2, 3, 1]</code></li>
<li><code>[3, 1, 2]</code></li>
<li><code>[3, 2, 1]</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1] has only 1 permutation which is self-divisible.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 12</code></li>
</ul>
|
Bit Manipulation; Array; Math; Dynamic Programming; Backtracking; Bitmask; Number Theory
|
Go
|
func selfDivisiblePermutationCount(n int) int {
f := make([]int, 1<<(n+1))
for i := range f {
f[i] = -1
}
var dfs func(int) int
dfs = func(mask int) int {
if f[mask] != -1 {
return f[mask]
}
i := bits.OnesCount(uint(mask)) + 1
if i > n {
return 1
}
f[mask] = 0
for j := 1; j <= n; j++ {
if mask>>j&1 == 0 && (i%j == 0 || j%i == 0) {
f[mask] += dfs(mask | 1<<j)
}
}
return f[mask]
}
return dfs(0)
}
|
2,992
|
Number of Self-Divisible Permutations
|
Medium
|
<p>Given an integer <code>n</code>, return <em>the number of <strong>permutations</strong> of the <strong>1-indexed</strong> array</em> <code>nums = [1, 2, ..., n]</code><em>, such that it's <strong>self-divisible</strong></em>.</p>
<p>A <strong>1-indexed</strong> array <code>a</code> of length <code>n</code> is <strong>self-divisible</strong> if for every <code>1 <= i <= n</code>, <code><span data-keyword="gcd-function">gcd</span>(a[i], i) == 1</code>.</p>
<p>A <strong>permutation</strong> of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array <code>[1, 2, 3]</code>:</p>
<ul>
<li><code>[1, 2, 3]</code></li>
<li><code>[1, 3, 2]</code></li>
<li><code>[2, 1, 3]</code></li>
<li><code>[2, 3, 1]</code></li>
<li><code>[3, 1, 2]</code></li>
<li><code>[3, 2, 1]</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1] has only 1 permutation which is self-divisible.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 12</code></li>
</ul>
|
Bit Manipulation; Array; Math; Dynamic Programming; Backtracking; Bitmask; Number Theory
|
Java
|
class Solution {
private int n;
private Integer[] f;
public int selfDivisiblePermutationCount(int n) {
this.n = n;
f = new Integer[1 << (n + 1)];
return dfs(0);
}
private int dfs(int mask) {
if (f[mask] != null) {
return f[mask];
}
int i = Integer.bitCount(mask) + 1;
if (i > n) {
return 1;
}
f[mask] = 0;
for (int j = 1; j <= n; ++j) {
if ((mask >> j & 1) == 0 && (i % j == 0 || j % i == 0)) {
f[mask] += dfs(mask | 1 << j);
}
}
return f[mask];
}
}
|
2,992
|
Number of Self-Divisible Permutations
|
Medium
|
<p>Given an integer <code>n</code>, return <em>the number of <strong>permutations</strong> of the <strong>1-indexed</strong> array</em> <code>nums = [1, 2, ..., n]</code><em>, such that it's <strong>self-divisible</strong></em>.</p>
<p>A <strong>1-indexed</strong> array <code>a</code> of length <code>n</code> is <strong>self-divisible</strong> if for every <code>1 <= i <= n</code>, <code><span data-keyword="gcd-function">gcd</span>(a[i], i) == 1</code>.</p>
<p>A <strong>permutation</strong> of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array <code>[1, 2, 3]</code>:</p>
<ul>
<li><code>[1, 2, 3]</code></li>
<li><code>[1, 3, 2]</code></li>
<li><code>[2, 1, 3]</code></li>
<li><code>[2, 3, 1]</code></li>
<li><code>[3, 1, 2]</code></li>
<li><code>[3, 2, 1]</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1] has only 1 permutation which is self-divisible.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 12</code></li>
</ul>
|
Bit Manipulation; Array; Math; Dynamic Programming; Backtracking; Bitmask; Number Theory
|
Python
|
class Solution:
def selfDivisiblePermutationCount(self, n: int) -> int:
@cache
def dfs(mask: int) -> int:
i = mask.bit_count() + 1
if i > n:
return 1
ans = 0
for j in range(1, n + 1):
if (mask >> j & 1) == 0 and gcd(i, j) == 1:
ans += dfs(mask | 1 << j)
return ans
return dfs(0)
|
2,992
|
Number of Self-Divisible Permutations
|
Medium
|
<p>Given an integer <code>n</code>, return <em>the number of <strong>permutations</strong> of the <strong>1-indexed</strong> array</em> <code>nums = [1, 2, ..., n]</code><em>, such that it's <strong>self-divisible</strong></em>.</p>
<p>A <strong>1-indexed</strong> array <code>a</code> of length <code>n</code> is <strong>self-divisible</strong> if for every <code>1 <= i <= n</code>, <code><span data-keyword="gcd-function">gcd</span>(a[i], i) == 1</code>.</p>
<p>A <strong>permutation</strong> of an array is a rearrangement of the elements of that array, for example here are all of the permutations of the array <code>[1, 2, 3]</code>:</p>
<ul>
<li><code>[1, 2, 3]</code></li>
<li><code>[1, 3, 2]</code></li>
<li><code>[2, 1, 3]</code></li>
<li><code>[2, 3, 1]</code></li>
<li><code>[3, 1, 2]</code></li>
<li><code>[3, 2, 1]</code></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1] has only 1 permutation which is self-divisible.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> The array [1,2] has 2 permutations and only one of them is self-divisible:
nums = [1,2]: This is not self-divisible since gcd(nums[2], 2) != 1.
nums = [2,1]: This is self-divisible since gcd(nums[1], 1) == 1 and gcd(nums[2], 2) == 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The array [1,2,3] has 3 self-divisble permutations: [1,3,2], [3,1,2], [2,3,1].
It can be shown that the other 3 permutations are not self-divisible. Hence the answer is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 12</code></li>
</ul>
|
Bit Manipulation; Array; Math; Dynamic Programming; Backtracking; Bitmask; Number Theory
|
TypeScript
|
function selfDivisiblePermutationCount(n: number): number {
const f: number[] = Array(1 << (n + 1)).fill(-1);
const dfs = (mask: number): number => {
if (f[mask] !== -1) {
return f[mask];
}
const i = bitCount(mask) + 1;
if (i > n) {
return 1;
}
f[mask] = 0;
for (let j = 1; j <= n; ++j) {
if (((mask >> j) & 1) === 0 && (i % j === 0 || j % i === 0)) {
f[mask] += dfs(mask | (1 << j));
}
}
return f[mask];
};
return dfs(0);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
2,993
|
Friday Purchases I
|
Medium
|
<p>Table: <code>Purchases</code></p>
<pre>
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user id, purchase date, and amount spend.
</pre>
<p>Write a solution to calculate the <strong>total spending</strong> by users on <strong>each Friday</strong> of <strong>every week</strong> in <strong>November 2023</strong>. Output only weeks that include <strong>at least one</strong> purchase on a <strong>Friday</strong>.</p>
<p>Return <em>the result table ordered by week of month</em><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Purchases table:
+---------+---------------+--------------+
| user_id | purchase_date | amount_spend |
+---------+---------------+--------------+
| 11 | 2023-11-07 | 1126 |
| 15 | 2023-11-30 | 7473 |
| 17 | 2023-11-14 | 2414 |
| 12 | 2023-11-24 | 9692 |
| 8 | 2023-11-03 | 5117 |
| 1 | 2023-11-16 | 5241 |
| 10 | 2023-11-12 | 8266 |
| 13 | 2023-11-24 | 12000 |
+---------+---------------+--------------+
<strong>Output:</strong>
+---------------+---------------+--------------+
| week_of_month | purchase_date | total_amount |
+---------------+---------------+--------------+
| 1 | 2023-11-03 | 5117 |
| 4 | 2023-11-24 | 21692 |
+---------------+---------------+--------------+
<strong>Explanation:</strong>
- During the first week of November 2023, transactions amounting to $5,117 occurred on Friday, 2023-11-03.
- For the second week of November 2023, there were no transactions on Friday, 2023-11-10.
- Similarly, during the third week of November 2023, there were no transactions on Friday, 2023-11-17.
- In the fourth week of November 2023, two transactions took place on Friday, 2023-11-24, amounting to $12,000 and $9,692 respectively, summing up to a total of $21,692.
Output table is ordered by week_of_month in ascending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month,
purchase_date,
SUM(amount_spend) AS total_amount
FROM Purchases
WHERE DATE_FORMAT(purchase_date, '%Y%m') = '202311' AND DAYOFWEEK(purchase_date) = 6
GROUP BY 2
ORDER BY 1;
|
2,994
|
Friday Purchases II
|
Hard
|
<p>Table: <code>Purchases</code></p>
<pre>
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user id, purchase date, and amount spend.
</pre>
<p>Write a solution to calculate the <strong>total spending</strong> by users on <strong>each Friday</strong> of <strong>every week</strong> in <strong>November 2023</strong>. If there are <strong>no</strong> purchases on a particular <strong>Friday of a week</strong>, it will be considered as <code>0</code>.</p>
<p>Return <em>the result table ordered by week of month</em><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Purchases table:
+---------+---------------+--------------+
| user_id | purchase_date | amount_spend |
+---------+---------------+--------------+
| 11 | 2023-11-07 | 1126 |
| 15 | 2023-11-30 | 7473 |
| 17 | 2023-11-14 | 2414 |
| 12 | 2023-11-24 | 9692 |
| 8 | 2023-11-03 | 5117 |
| 1 | 2023-11-16 | 5241 |
| 10 | 2023-11-12 | 8266 |
| 13 | 2023-11-24 | 12000 |
+---------+---------------+--------------+
<strong>Output:</strong>
+---------------+---------------+--------------+
| week_of_month | purchase_date | total_amount |
+---------------+---------------+--------------+
| 1 | 2023-11-03 | 5117 |
| 2 | 2023-11-10 | 0 |
| 3 | 2023-11-17 | 0 |
| 4 | 2023-11-24 | 21692 |
+---------------+---------------+--------------+
<strong>Explanation:</strong>
- During the first week of November 2023, transactions amounting to $5,117 occurred on Friday, 2023-11-03.
- For the second week of November 2023, there were no transactions on Friday, 2023-11-10, resulting in a value of 0 in the output table for that day.
- Similarly, during the third week of November 2023, there were no transactions on Friday, 2023-11-17, reflected as 0 in the output table for that specific day.
- In the fourth week of November 2023, two transactions took place on Friday, 2023-11-24, amounting to $12,000 and $9,692 respectively, summing up to a total of $21,692.
Output table is ordered by week_of_month in ascending order.</pre>
|
Database
|
SQL
|
WITH RECURSIVE
T AS (
SELECT '2023-11-01' AS purchase_date
UNION
SELECT purchase_date + INTERVAL 1 DAY
FROM T
WHERE purchase_date < '2023-11-30'
)
SELECT
CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month,
purchase_date,
IFNULL(SUM(amount_spend), 0) AS total_amount
FROM
T
LEFT JOIN Purchases USING (purchase_date)
WHERE DAYOFWEEK(purchase_date) = 6
GROUP BY 2
ORDER BY 1;
|
2,995
|
Viewers Turned Streamers
|
Hard
|
<p>Table: <code>Sessions</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| user_id | int |
| session_start | datetime |
| session_end | datetime |
| session_id | int |
| session_type | enum |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.
</pre>
<p>Write a solution to find the number of <strong>streaming</strong> sessions for users whose <strong>first session </strong>was as a <strong>viewer</strong>.</p>
<p>Return <em>the result table ordered by count of streaming sessions, </em> <code>user_id</code><em> in <strong>descending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Sessions table:
+---------+---------------------+---------------------+------------+--------------+
| user_id | session_start | session_end | session_id | session_type |
+---------+---------------------+---------------------+------------+--------------+
| 101 | 2023-11-06 13:53:42 | 2023-11-06 14:05:42 | 375 | Viewer |
| 101 | 2023-11-22 16:45:21 | 2023-11-22 20:39:21 | 594 | Streamer |
| 102 | 2023-11-16 13:23:09 | 2023-11-16 16:10:09 | 777 | Streamer |
| 102 | 2023-11-17 13:23:09 | 2023-11-17 16:10:09 | 778 | Streamer |
| 101 | 2023-11-20 07:16:06 | 2023-11-20 08:33:06 | 315 | Streamer |
| 104 | 2023-11-27 03:10:49 | 2023-11-27 03:30:49 | 797 | Viewer |
| 103 | 2023-11-27 03:10:49 | 2023-11-27 03:30:49 | 798 | Streamer |
+---------+---------------------+---------------------+------------+--------------+
<strong>Output:</strong>
+---------+----------------+
| user_id | sessions_count |
+---------+----------------+
| 101 | 2 |
+---------+----------------+
<strong>Explanation</strong>
- user_id 101, initiated their initial session as a viewer on 2023-11-06 at 13:53:42, followed by two subsequent sessions as a Streamer, the count will be 2.
- user_id 102, although there are two sessions, the initial session was as a Streamer, so this user will be excluded.
- user_id 103 participated in only one session, which was as a Streamer, hence, it won't be considered.
- User_id 104 commenced their first session as a viewer but didn't have any subsequent sessions, therefore, they won't be included in the final count.
Output table is ordered by sessions count and user_id in descending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
user_id,
session_type,
RANK() OVER (
PARTITION BY user_id
ORDER BY session_start
) AS rk
FROM Sessions
)
SELECT user_id, COUNT(1) AS sessions_count
FROM
T AS t
JOIN Sessions AS s USING (user_id)
WHERE rk = 1 AND t.session_type = 'Viewer' AND s.session_type = 'Streamer'
GROUP BY 1
ORDER BY 2 DESC, 1 DESC;
|
2,996
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>.</p>
<p>A prefix <code>nums[0..i]</code> is <strong>sequential</strong> if, for all <code>1 <= j <= i</code>, <code>nums[j] = nums[j - 1] + 1</code>. In particular, the prefix consisting only of <code>nums[0]</code> is <strong>sequential</strong>.</p>
<p>Return <em>the <strong>smallest</strong> integer</em> <code>x</code> <em>missing from</em> <code>nums</code> <em>such that</em> <code>x</code> <em>is greater than or equal to the sum of the <strong>longest</strong> sequential prefix.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5,1,12,14,13]
<strong>Output:</strong> 15
<strong>Explanation:</strong> The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Hash Table; Sorting
|
C++
|
class Solution {
public:
int missingInteger(vector<int>& nums) {
int s = nums[0];
for (int j = 1; j < nums.size() && nums[j] == nums[j - 1] + 1; ++j) {
s += nums[j];
}
bitset<51> vis;
for (int x : nums) {
vis[x] = 1;
}
for (int x = s;; ++x) {
if (x >= 51 || !vis[x]) {
return x;
}
}
}
};
|
2,996
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>.</p>
<p>A prefix <code>nums[0..i]</code> is <strong>sequential</strong> if, for all <code>1 <= j <= i</code>, <code>nums[j] = nums[j - 1] + 1</code>. In particular, the prefix consisting only of <code>nums[0]</code> is <strong>sequential</strong>.</p>
<p>Return <em>the <strong>smallest</strong> integer</em> <code>x</code> <em>missing from</em> <code>nums</code> <em>such that</em> <code>x</code> <em>is greater than or equal to the sum of the <strong>longest</strong> sequential prefix.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5,1,12,14,13]
<strong>Output:</strong> 15
<strong>Explanation:</strong> The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Go
|
func missingInteger(nums []int) int {
s := nums[0]
for j := 1; j < len(nums) && nums[j] == nums[j-1]+1; j++ {
s += nums[j]
}
vis := [51]bool{}
for _, x := range nums {
vis[x] = true
}
for x := s; ; x++ {
if x >= len(vis) || !vis[x] {
return x
}
}
}
|
2,996
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>.</p>
<p>A prefix <code>nums[0..i]</code> is <strong>sequential</strong> if, for all <code>1 <= j <= i</code>, <code>nums[j] = nums[j - 1] + 1</code>. In particular, the prefix consisting only of <code>nums[0]</code> is <strong>sequential</strong>.</p>
<p>Return <em>the <strong>smallest</strong> integer</em> <code>x</code> <em>missing from</em> <code>nums</code> <em>such that</em> <code>x</code> <em>is greater than or equal to the sum of the <strong>longest</strong> sequential prefix.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5,1,12,14,13]
<strong>Output:</strong> 15
<strong>Explanation:</strong> The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Java
|
class Solution {
public int missingInteger(int[] nums) {
int s = nums[0];
for (int j = 1; j < nums.length && nums[j] == nums[j - 1] + 1; ++j) {
s += nums[j];
}
boolean[] vis = new boolean[51];
for (int x : nums) {
vis[x] = true;
}
for (int x = s;; ++x) {
if (x >= vis.length || !vis[x]) {
return x;
}
}
}
}
|
2,996
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>.</p>
<p>A prefix <code>nums[0..i]</code> is <strong>sequential</strong> if, for all <code>1 <= j <= i</code>, <code>nums[j] = nums[j - 1] + 1</code>. In particular, the prefix consisting only of <code>nums[0]</code> is <strong>sequential</strong>.</p>
<p>Return <em>the <strong>smallest</strong> integer</em> <code>x</code> <em>missing from</em> <code>nums</code> <em>such that</em> <code>x</code> <em>is greater than or equal to the sum of the <strong>longest</strong> sequential prefix.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5,1,12,14,13]
<strong>Output:</strong> 15
<strong>Explanation:</strong> The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Hash Table; Sorting
|
Python
|
class Solution:
def missingInteger(self, nums: List[int]) -> int:
s, j = nums[0], 1
while j < len(nums) and nums[j] == nums[j - 1] + 1:
s += nums[j]
j += 1
vis = set(nums)
for x in count(s):
if x not in vis:
return x
|
2,996
|
Smallest Missing Integer Greater Than Sequential Prefix Sum
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>.</p>
<p>A prefix <code>nums[0..i]</code> is <strong>sequential</strong> if, for all <code>1 <= j <= i</code>, <code>nums[j] = nums[j - 1] + 1</code>. In particular, the prefix consisting only of <code>nums[0]</code> is <strong>sequential</strong>.</p>
<p>Return <em>the <strong>smallest</strong> integer</em> <code>x</code> <em>missing from</em> <code>nums</code> <em>such that</em> <code>x</code> <em>is greater than or equal to the sum of the <strong>longest</strong> sequential prefix.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,2,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5,1,12,14,13]
<strong>Output:</strong> 15
<strong>Explanation:</strong> The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Hash Table; Sorting
|
TypeScript
|
function missingInteger(nums: number[]): number {
let s = nums[0];
for (let j = 1; j < nums.length && nums[j] === nums[j - 1] + 1; ++j) {
s += nums[j];
}
const vis: Set<number> = new Set(nums);
for (let x = s; ; ++x) {
if (!vis.has(x)) {
return x;
}
}
}
|
2,997
|
Minimum Number of Operations to Make Array XOR Equal to K
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p>
<p>You can apply the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> element of the array and <strong>flip</strong> a bit in its <strong>binary</strong> representation. Flipping a bit means changing a <code>0</code> to <code>1</code> or vice versa.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the bitwise </em><code>XOR</code><em> of <strong>all</strong> elements of the final array equal to </em><code>k</code>.</p>
<p><strong>Note</strong> that you can flip leading zero bits in the binary representation of elements. For example, for the number <code>(101)<sub>2</sub></code> you can flip the fourth bit and obtain <code>(1101)<sub>2</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4], k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can do the following operations:
- Choose element 2 which is 3 == (011)<sub>2</sub>, we flip the first bit and we obtain (010)<sub>2</sub> == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)<sub>2</sub>, we flip the third bit and we obtain (110)<sub>2</sub> = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,0,2,0], k = 0
<strong>Output:</strong> 0
<strong>Explanation:</strong> The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>0 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
for (int x : nums) {
k ^= x;
}
return __builtin_popcount(k);
}
};
|
2,997
|
Minimum Number of Operations to Make Array XOR Equal to K
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p>
<p>You can apply the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> element of the array and <strong>flip</strong> a bit in its <strong>binary</strong> representation. Flipping a bit means changing a <code>0</code> to <code>1</code> or vice versa.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the bitwise </em><code>XOR</code><em> of <strong>all</strong> elements of the final array equal to </em><code>k</code>.</p>
<p><strong>Note</strong> that you can flip leading zero bits in the binary representation of elements. For example, for the number <code>(101)<sub>2</sub></code> you can flip the fourth bit and obtain <code>(1101)<sub>2</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4], k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can do the following operations:
- Choose element 2 which is 3 == (011)<sub>2</sub>, we flip the first bit and we obtain (010)<sub>2</sub> == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)<sub>2</sub>, we flip the third bit and we obtain (110)<sub>2</sub> = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,0,2,0], k = 0
<strong>Output:</strong> 0
<strong>Explanation:</strong> The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>0 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func minOperations(nums []int, k int) (ans int) {
for _, x := range nums {
k ^= x
}
return bits.OnesCount(uint(k))
}
|
2,997
|
Minimum Number of Operations to Make Array XOR Equal to K
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p>
<p>You can apply the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> element of the array and <strong>flip</strong> a bit in its <strong>binary</strong> representation. Flipping a bit means changing a <code>0</code> to <code>1</code> or vice versa.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the bitwise </em><code>XOR</code><em> of <strong>all</strong> elements of the final array equal to </em><code>k</code>.</p>
<p><strong>Note</strong> that you can flip leading zero bits in the binary representation of elements. For example, for the number <code>(101)<sub>2</sub></code> you can flip the fourth bit and obtain <code>(1101)<sub>2</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4], k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can do the following operations:
- Choose element 2 which is 3 == (011)<sub>2</sub>, we flip the first bit and we obtain (010)<sub>2</sub> == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)<sub>2</sub>, we flip the third bit and we obtain (110)<sub>2</sub> = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,0,2,0], k = 0
<strong>Output:</strong> 0
<strong>Explanation:</strong> The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>0 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
for (int x : nums) {
k ^= x;
}
return Integer.bitCount(k);
}
}
|
2,997
|
Minimum Number of Operations to Make Array XOR Equal to K
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p>
<p>You can apply the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> element of the array and <strong>flip</strong> a bit in its <strong>binary</strong> representation. Flipping a bit means changing a <code>0</code> to <code>1</code> or vice versa.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the bitwise </em><code>XOR</code><em> of <strong>all</strong> elements of the final array equal to </em><code>k</code>.</p>
<p><strong>Note</strong> that you can flip leading zero bits in the binary representation of elements. For example, for the number <code>(101)<sub>2</sub></code> you can flip the fourth bit and obtain <code>(1101)<sub>2</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4], k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can do the following operations:
- Choose element 2 which is 3 == (011)<sub>2</sub>, we flip the first bit and we obtain (010)<sub>2</sub> == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)<sub>2</sub>, we flip the third bit and we obtain (110)<sub>2</sub> = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,0,2,0], k = 0
<strong>Output:</strong> 0
<strong>Explanation:</strong> The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>0 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return reduce(xor, nums, k).bit_count()
|
2,997
|
Minimum Number of Operations to Make Array XOR Equal to K
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p>
<p>You can apply the following operation on the array <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> element of the array and <strong>flip</strong> a bit in its <strong>binary</strong> representation. Flipping a bit means changing a <code>0</code> to <code>1</code> or vice versa.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the bitwise </em><code>XOR</code><em> of <strong>all</strong> elements of the final array equal to </em><code>k</code>.</p>
<p><strong>Note</strong> that you can flip leading zero bits in the binary representation of elements. For example, for the number <code>(101)<sub>2</sub></code> you can flip the fourth bit and obtain <code>(1101)<sub>2</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4], k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can do the following operations:
- Choose element 2 which is 3 == (011)<sub>2</sub>, we flip the first bit and we obtain (010)<sub>2</sub> == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)<sub>2</sub>, we flip the third bit and we obtain (110)<sub>2</sub> = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,0,2,0], k = 0
<strong>Output:</strong> 0
<strong>Explanation:</strong> The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>0 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
for (const x of nums) {
k ^= x;
}
return bitCount(k);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
2,998
|
Minimum Number of Operations to Make X and Y Equal
|
Medium
|
<p>You are given two positive integers <code>x</code> and <code>y</code>.</p>
<p>In one operation, you can do one of the four following operations:</p>
<ol>
<li>Divide <code>x</code> by <code>11</code> if <code>x</code> is a multiple of <code>11</code>.</li>
<li>Divide <code>x</code> by <code>5</code> if <code>x</code> is a multiple of <code>5</code>.</li>
<li>Decrement <code>x</code> by <code>1</code>.</li>
<li>Increment <code>x</code> by <code>1</code>.</li>
</ol>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em> <code>x</code> <i>and</i> <code>y</code> equal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 26, y = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 54, y = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> x = 25, y = 30
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Memoization; Dynamic Programming
|
C++
|
class Solution {
public:
int minimumOperationsToMakeEqual(int x, int y) {
unordered_map<int, int> f;
function<int(int)> dfs = [&](int x) {
if (y >= x) {
return y - x;
}
if (f.count(x)) {
return f[x];
}
int a = x % 5 + 1 + dfs(x / 5);
int b = 5 - x % 5 + 1 + dfs(x / 5 + 1);
int c = x % 11 + 1 + dfs(x / 11);
int d = 11 - x % 11 + 1 + dfs(x / 11 + 1);
return f[x] = min({x - y, a, b, c, d});
};
return dfs(x);
}
};
|
2,998
|
Minimum Number of Operations to Make X and Y Equal
|
Medium
|
<p>You are given two positive integers <code>x</code> and <code>y</code>.</p>
<p>In one operation, you can do one of the four following operations:</p>
<ol>
<li>Divide <code>x</code> by <code>11</code> if <code>x</code> is a multiple of <code>11</code>.</li>
<li>Divide <code>x</code> by <code>5</code> if <code>x</code> is a multiple of <code>5</code>.</li>
<li>Decrement <code>x</code> by <code>1</code>.</li>
<li>Increment <code>x</code> by <code>1</code>.</li>
</ol>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em> <code>x</code> <i>and</i> <code>y</code> equal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 26, y = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 54, y = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> x = 25, y = 30
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Memoization; Dynamic Programming
|
Go
|
func minimumOperationsToMakeEqual(x int, y int) int {
f := map[int]int{}
var dfs func(int) int
dfs = func(x int) int {
if y >= x {
return y - x
}
if v, ok := f[x]; ok {
return v
}
a := x%5 + 1 + dfs(x/5)
b := 5 - x%5 + 1 + dfs(x/5+1)
c := x%11 + 1 + dfs(x/11)
d := 11 - x%11 + 1 + dfs(x/11+1)
f[x] = min(x-y, a, b, c, d)
return f[x]
}
return dfs(x)
}
|
2,998
|
Minimum Number of Operations to Make X and Y Equal
|
Medium
|
<p>You are given two positive integers <code>x</code> and <code>y</code>.</p>
<p>In one operation, you can do one of the four following operations:</p>
<ol>
<li>Divide <code>x</code> by <code>11</code> if <code>x</code> is a multiple of <code>11</code>.</li>
<li>Divide <code>x</code> by <code>5</code> if <code>x</code> is a multiple of <code>5</code>.</li>
<li>Decrement <code>x</code> by <code>1</code>.</li>
<li>Increment <code>x</code> by <code>1</code>.</li>
</ol>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em> <code>x</code> <i>and</i> <code>y</code> equal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 26, y = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 54, y = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> x = 25, y = 30
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Memoization; Dynamic Programming
|
Java
|
class Solution {
private Map<Integer, Integer> f = new HashMap<>();
private int y;
public int minimumOperationsToMakeEqual(int x, int y) {
this.y = y;
return dfs(x);
}
private int dfs(int x) {
if (y >= x) {
return y - x;
}
if (f.containsKey(x)) {
return f.get(x);
}
int ans = x - y;
int a = x % 5 + 1 + dfs(x / 5);
int b = 5 - x % 5 + 1 + dfs(x / 5 + 1);
int c = x % 11 + 1 + dfs(x / 11);
int d = 11 - x % 11 + 1 + dfs(x / 11 + 1);
ans = Math.min(ans, Math.min(a, Math.min(b, Math.min(c, d))));
f.put(x, ans);
return ans;
}
}
|
2,998
|
Minimum Number of Operations to Make X and Y Equal
|
Medium
|
<p>You are given two positive integers <code>x</code> and <code>y</code>.</p>
<p>In one operation, you can do one of the four following operations:</p>
<ol>
<li>Divide <code>x</code> by <code>11</code> if <code>x</code> is a multiple of <code>11</code>.</li>
<li>Divide <code>x</code> by <code>5</code> if <code>x</code> is a multiple of <code>5</code>.</li>
<li>Decrement <code>x</code> by <code>1</code>.</li>
<li>Increment <code>x</code> by <code>1</code>.</li>
</ol>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em> <code>x</code> <i>and</i> <code>y</code> equal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 26, y = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 54, y = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> x = 25, y = 30
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Memoization; Dynamic Programming
|
Python
|
class Solution:
def minimumOperationsToMakeEqual(self, x: int, y: int) -> int:
@cache
def dfs(x: int) -> int:
if y >= x:
return y - x
ans = x - y
ans = min(ans, x % 5 + 1 + dfs(x // 5))
ans = min(ans, 5 - x % 5 + 1 + dfs(x // 5 + 1))
ans = min(ans, x % 11 + 1 + dfs(x // 11))
ans = min(ans, 11 - x % 11 + 1 + dfs(x // 11 + 1))
return ans
return dfs(x)
|
2,998
|
Minimum Number of Operations to Make X and Y Equal
|
Medium
|
<p>You are given two positive integers <code>x</code> and <code>y</code>.</p>
<p>In one operation, you can do one of the four following operations:</p>
<ol>
<li>Divide <code>x</code> by <code>11</code> if <code>x</code> is a multiple of <code>11</code>.</li>
<li>Divide <code>x</code> by <code>5</code> if <code>x</code> is a multiple of <code>5</code>.</li>
<li>Decrement <code>x</code> by <code>1</code>.</li>
<li>Increment <code>x</code> by <code>1</code>.</li>
</ol>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em> <code>x</code> <i>and</i> <code>y</code> equal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 26, y = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 26 equal to 1 by applying the following operations:
1. Decrement x by 1
2. Divide x by 5
3. Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 54, y = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make 54 equal to 2 by applying the following operations:
1. Increment x by 1
2. Divide x by 11
3. Divide x by 5
4. Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> x = 25, y = 30
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make 25 equal to 30 by applying the following operations:
1. Increment x by 1
2. Increment x by 1
3. Increment x by 1
4. Increment x by 1
5. Increment x by 1
It can be shown that 5 is the minimum number of operations required to make 25 equal to 30.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 10<sup>4</sup></code></li>
</ul>
|
Breadth-First Search; Memoization; Dynamic Programming
|
TypeScript
|
function minimumOperationsToMakeEqual(x: number, y: number): number {
const f: Map<number, number> = new Map();
const dfs = (x: number): number => {
if (y >= x) {
return y - x;
}
if (f.has(x)) {
return f.get(x)!;
}
const a = (x % 5) + 1 + dfs((x / 5) | 0);
const b = 5 - (x % 5) + 1 + dfs(((x / 5) | 0) + 1);
const c = (x % 11) + 1 + dfs((x / 11) | 0);
const d = 11 - (x % 11) + 1 + dfs(((x / 11) | 0) + 1);
const ans = Math.min(x - y, a, b, c, d);
f.set(x, ans);
return ans;
};
return dfs(x);
}
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
C++
|
class Solution {
public:
long long numberOfPowerfulInt(long long start, long long finish, int limit, string s) {
string t = to_string(start - 1);
long long f[20];
memset(f, -1, sizeof(f));
auto dfs = [&](this auto&& dfs, int pos, int lim) -> long long {
if (t.size() < s.size()) {
return 0;
}
if (!lim && f[pos] != -1) {
return f[pos];
}
if (t.size() - pos == s.size()) {
return lim ? s <= t.substr(pos) : 1;
}
long long ans = 0;
int up = min(lim ? t[pos] - '0' : 9, limit);
for (int i = 0; i <= up; ++i) {
ans += dfs(pos + 1, lim && i == (t[pos] - '0'));
}
if (!lim) {
f[pos] = ans;
}
return ans;
};
long long a = dfs(0, true);
t = to_string(finish);
memset(f, -1, sizeof(f));
long long b = dfs(0, true);
return b - a;
}
};
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
C#
|
public class Solution {
private string s;
private string t;
private long?[] f;
private int limit;
public long NumberOfPowerfulInt(long start, long finish, int limit, string s) {
this.s = s;
this.limit = limit;
t = (start - 1).ToString();
f = new long?[20];
long a = Dfs(0, true);
t = finish.ToString();
f = new long?[20];
long b = Dfs(0, true);
return b - a;
}
private long Dfs(int pos, bool lim) {
if (t.Length < s.Length) {
return 0;
}
if (!lim && f[pos].HasValue) {
return f[pos].Value;
}
if (t.Length - pos == s.Length) {
return lim ? (string.Compare(s, t.Substring(pos)) <= 0 ? 1 : 0) : 1;
}
int up = lim ? t[pos] - '0' : 9;
up = Math.Min(up, limit);
long ans = 0;
for (int i = 0; i <= up; ++i) {
ans += Dfs(pos + 1, lim && i == (t[pos] - '0'));
}
if (!lim) {
f[pos] = ans;
}
return ans;
}
}
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
Go
|
func numberOfPowerfulInt(start, finish int64, limit int, s string) int64 {
t := strconv.FormatInt(start-1, 10)
f := make([]int64, 20)
for i := range f {
f[i] = -1
}
var dfs func(int, bool) int64
dfs = func(pos int, lim bool) int64 {
if len(t) < len(s) {
return 0
}
if !lim && f[pos] != -1 {
return f[pos]
}
if len(t)-pos == len(s) {
if lim {
if s <= t[pos:] {
return 1
}
return 0
}
return 1
}
ans := int64(0)
up := 9
if lim {
up = int(t[pos] - '0')
}
up = min(up, limit)
for i := 0; i <= up; i++ {
ans += dfs(pos+1, lim && i == int(t[pos]-'0'))
}
if !lim {
f[pos] = ans
}
return ans
}
a := dfs(0, true)
t = strconv.FormatInt(finish, 10)
for i := range f {
f[i] = -1
}
b := dfs(0, true)
return b - a
}
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
Java
|
class Solution {
private String s;
private String t;
private Long[] f;
private int limit;
public long numberOfPowerfulInt(long start, long finish, int limit, String s) {
this.s = s;
this.limit = limit;
t = String.valueOf(start - 1);
f = new Long[20];
long a = dfs(0, true);
t = String.valueOf(finish);
f = new Long[20];
long b = dfs(0, true);
return b - a;
}
private long dfs(int pos, boolean lim) {
if (t.length() < s.length()) {
return 0;
}
if (!lim && f[pos] != null) {
return f[pos];
}
if (t.length() - pos == s.length()) {
return lim ? (s.compareTo(t.substring(pos)) <= 0 ? 1 : 0) : 1;
}
int up = lim ? t.charAt(pos) - '0' : 9;
up = Math.min(up, limit);
long ans = 0;
for (int i = 0; i <= up; ++i) {
ans += dfs(pos + 1, lim && i == (t.charAt(pos) - '0'));
}
if (!lim) {
f[pos] = ans;
}
return ans;
}
}
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
Python
|
class Solution:
def numberOfPowerfulInt(self, start: int, finish: int, limit: int, s: str) -> int:
@cache
def dfs(pos: int, lim: int) -> int:
if len(t) < n:
return 0
if len(t) - pos == n:
return int(s <= t[pos:]) if lim else 1
up = min(int(t[pos]) if lim else 9, limit)
ans = 0
for i in range(up + 1):
ans += dfs(pos + 1, lim and i == int(t[pos]))
return ans
n = len(s)
t = str(start - 1)
a = dfs(0, True)
dfs.cache_clear()
t = str(finish)
b = dfs(0, True)
return b - a
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
Rust
|
impl Solution {
pub fn number_of_powerful_int(start: i64, finish: i64, limit: i32, s: String) -> i64 {
fn count(x: i64, limit: i32, s: &str) -> i64 {
let t = x.to_string();
if t.len() < s.len() {
return 0;
}
let t_bytes: Vec<u8> = t.bytes().collect();
let mut f = [-1_i64; 20];
fn dfs(pos: usize, lim: bool, t: &[u8], s: &str, limit: i32, f: &mut [i64; 20]) -> i64 {
if t.len() < s.len() {
return 0;
}
if !lim && f[pos] != -1 {
return f[pos];
}
if t.len() - pos == s.len() {
if lim {
let suffix = &t[pos..];
let suffix_str = String::from_utf8_lossy(suffix);
return if suffix_str.as_ref() >= s { 1 } else { 0 };
} else {
return 1;
}
}
let mut ans = 0;
let up = if lim {
(t[pos] - b'0').min(limit as u8)
} else {
limit as u8
};
for i in 0..=up {
let next_lim = lim && i == t[pos] - b'0';
ans += dfs(pos + 1, next_lim, t, s, limit, f);
}
if !lim {
f[pos] = ans;
}
ans
}
dfs(0, true, &t_bytes, s, limit, &mut f)
}
let a = count(start - 1, limit, &s);
let b = count(finish, limit, &s);
b - a
}
}
|
2,999
|
Count the Number of Powerful Integers
|
Hard
|
<p>You are given three integers <code>start</code>, <code>finish</code>, and <code>limit</code>. You are also given a <strong>0-indexed</strong> string <code>s</code> representing a <strong>positive</strong> integer.</p>
<p>A <strong>positive</strong> integer <code>x</code> is called <strong>powerful</strong> if it ends with <code>s</code> (in other words, <code>s</code> is a <strong>suffix</strong> of <code>x</code>) and each digit in <code>x</code> is at most <code>limit</code>.</p>
<p>Return <em>the <strong>total</strong> number of powerful integers in the range</em> <code>[start..finish]</code>.</p>
<p>A string <code>x</code> is a suffix of a string <code>y</code> if and only if <code>x</code> is a substring of <code>y</code> that starts from some index (<strong>including </strong><code>0</code>) in <code>y</code> and extends to the index <code>y.length - 1</code>. For example, <code>25</code> is a suffix of <code>5125</code> whereas <code>512</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> start = 1, finish = 6000, limit = 4, s = "124"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.
It can be shown that there are only 5 powerful integers in this range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> start = 15, finish = 215, limit = 6, s = "10"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.
It can be shown that there are only 2 powerful integers in this range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> start = 1000, finish = 2000, limit = 4, s = "3000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= start <= finish <= 10<sup>15</sup></code></li>
<li><code>1 <= limit <= 9</code></li>
<li><code>1 <= s.length <= floor(log<sub>10</sub>(finish)) + 1</code></li>
<li><code>s</code> only consists of numeric digits which are at most <code>limit</code>.</li>
<li><code>s</code> does not have leading zeros.</li>
</ul>
|
Math; String; Dynamic Programming
|
TypeScript
|
function numberOfPowerfulInt(start: number, finish: number, limit: number, s: string): number {
let t: string = (start - 1).toString();
let f: number[] = Array(20).fill(-1);
const dfs = (pos: number, lim: boolean): number => {
if (t.length < s.length) {
return 0;
}
if (!lim && f[pos] !== -1) {
return f[pos];
}
if (t.length - pos === s.length) {
if (lim) {
return s <= t.substring(pos) ? 1 : 0;
}
return 1;
}
let ans: number = 0;
const up: number = Math.min(lim ? +t[pos] : 9, limit);
for (let i = 0; i <= up; i++) {
ans += dfs(pos + 1, lim && i === +t[pos]);
}
if (!lim) {
f[pos] = ans;
}
return ans;
};
const a: number = dfs(0, true);
t = finish.toString();
f = Array(20).fill(-1);
const b: number = dfs(0, true);
return b - a;
}
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int areaOfMaxDiagonal(vector<vector<int>>& dimensions) {
int ans = 0, mx = 0;
for (auto& d : dimensions) {
int l = d[0], w = d[1];
int t = l * l + w * w;
if (mx < t) {
mx = t;
ans = l * w;
} else if (mx == t) {
ans = max(ans, l * w);
}
}
return ans;
}
};
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
C#
|
public class Solution {
public int AreaOfMaxDiagonal(int[][] dimensions) {
int ans = 0, mx = 0;
foreach (var d in dimensions) {
int l = d[0], w = d[1];
int t = l * l + w * w;
if (mx < t) {
mx = t;
ans = l * w;
} else if (mx == t) {
ans = Math.Max(ans, l * w);
}
}
return ans;
}
}
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
Go
|
func areaOfMaxDiagonal(dimensions [][]int) (ans int) {
mx := 0
for _, d := range dimensions {
l, w := d[0], d[1]
t := l*l + w*w
if mx < t {
mx = t
ans = l * w
} else if mx == t {
ans = max(ans, l*w)
}
}
return
}
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int areaOfMaxDiagonal(int[][] dimensions) {
int ans = 0, mx = 0;
for (var d : dimensions) {
int l = d[0], w = d[1];
int t = l * l + w * w;
if (mx < t) {
mx = t;
ans = l * w;
} else if (mx == t) {
ans = Math.max(ans, l * w);
}
}
return ans;
}
}
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
ans = mx = 0
for l, w in dimensions:
t = l**2 + w**2
if mx < t:
mx = t
ans = l * w
elif mx == t:
ans = max(ans, l * w)
return ans
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn area_of_max_diagonal(dimensions: Vec<Vec<i32>>) -> i32 {
let mut ans = 0;
let mut mx = 0;
for d in dimensions {
let l = d[0];
let w = d[1];
let t = l * l + w * w;
if mx < t {
mx = t;
ans = l * w;
} else if mx == t {
ans = ans.max(l * w);
}
}
ans
}
}
|
3,000
|
Maximum Area of Longest Diagonal Rectangle
|
Easy
|
<p>You are given a 2D <strong>0-indexed </strong>integer array <code>dimensions</code>.</p>
<p>For all indices <code>i</code>, <code>0 <= i < dimensions.length</code>, <code>dimensions[i][0]</code> represents the length and <code>dimensions[i][1]</code> represents the width of the rectangle<span style="font-size: 13.3333px;"> <code>i</code></span>.</p>
<p>Return <em>the <strong>area</strong> of the rectangle having the <strong>longest</strong> diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the <strong>maximum</strong> area.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[9,3],[8,6]]
<strong>Output:</strong> 48
<strong>Explanation:</strong>
For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈<!-- notionvc: 882cf44c-3b17-428e-9c65-9940810216f1 --> 9.487.
For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.
So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> dimensions = [[3,4],[4,3]]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Length of diagonal is the same for both which is 5, so maximum area = 12.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= dimensions.length <= 100</code></li>
<li><code><font face="monospace">dimensions[i].length == 2</font></code></li>
<li><code><font face="monospace">1 <= dimensions[i][0], dimensions[i][1] <= 100</font></code></li>
</ul>
|
Array
|
TypeScript
|
function areaOfMaxDiagonal(dimensions: number[][]): number {
let [ans, mx] = [0, 0];
for (const [l, w] of dimensions) {
const t = l * l + w * w;
if (mx < t) {
mx = t;
ans = l * w;
} else if (mx === t) {
ans = Math.max(ans, l * w);
}
}
return ans;
}
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
Cangjie
|
class Solution {
func minMovesToCaptureTheQueen(a: Int64, b: Int64, c: Int64, d: Int64, e: Int64, f: Int64): Int64 {
if (a == e && (c != a || (d - b) * (d - f) > 0)) {
return 1
}
if (b == f && (d != b || (c - a) * (c - e) > 0)) {
return 1
}
if (c - e == d - f && (a - e != b - f || (a - c) * (a - e) > 0)) {
return 1
}
if (c - e == f - d && (a - e != f - b || (a - c) * (a - e) > 0)) {
return 1
}
2
}
}
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
C++
|
class Solution {
public:
int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) {
if (a == e && (c != a || (d - b) * (d - f) > 0)) {
return 1;
}
if (b == f && (d != b || (c - a) * (c - e) > 0)) {
return 1;
}
if (c - e == d - f && (a - e != b - f || (a - c) * (a - e) > 0)) {
return 1;
}
if (c - e == f - d && (a - e != f - b || (a - c) * (a - e) > 0)) {
return 1;
}
return 2;
}
};
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
Go
|
func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int {
if a == e && (c != a || (d-b)*(d-f) > 0) {
return 1
}
if b == f && (d != b || (c-a)*(c-e) > 0) {
return 1
}
if c-e == d-f && (a-e != b-f || (a-c)*(a-e) > 0) {
return 1
}
if c-e == f-d && (a-e != f-b || (a-c)*(a-e) > 0) {
return 1
}
return 2
}
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
Java
|
class Solution {
public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) {
if (a == e && (c != a || (d - b) * (d - f) > 0)) {
return 1;
}
if (b == f && (d != b || (c - a) * (c - e) > 0)) {
return 1;
}
if (c - e == d - f && (a - e != b - f || (a - c) * (a - e) > 0)) {
return 1;
}
if (c - e == f - d && (a - e != f - b || (a - c) * (a - e) > 0)) {
return 1;
}
return 2;
}
}
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
Python
|
class Solution:
def minMovesToCaptureTheQueen(
self, a: int, b: int, c: int, d: int, e: int, f: int
) -> int:
if a == e and (c != a or (d - b) * (d - f) > 0):
return 1
if b == f and (d != b or (c - a) * (c - e) > 0):
return 1
if c - e == d - f and (a - e != b - f or (a - c) * (a - e) > 0):
return 1
if c - e == f - d and (a - e != f - b or (a - c) * (a - e) > 0):
return 1
return 2
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
Rust
|
impl Solution {
pub fn min_moves_to_capture_the_queen(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32) -> i32 {
if a == e && (c != a || (d - b) * (d - f) > 0) {
return 1;
}
if b == f && (d != b || (c - a) * (c - e) > 0) {
return 1;
}
if c - e == d - f && (a - e != b - f || (a - c) * (a - e) > 0) {
return 1;
}
if c - e == f - d && (a - e != f - b || (a - c) * (a - e) > 0) {
return 1;
}
return 2;
}
}
|
3,001
|
Minimum Moves to Capture The Queen
|
Medium
|
<p>There is a <strong>1-indexed</strong> <code>8 x 8</code> chessboard containing <code>3</code> pieces.</p>
<p>You are given <code>6</code> integers <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, and <code>f</code> where:</p>
<ul>
<li><code>(a, b)</code> denotes the position of the white rook.</li>
<li><code>(c, d)</code> denotes the position of the white bishop.</li>
<li><code>(e, f)</code> denotes the position of the black queen.</li>
</ul>
<p>Given that you can only move the white pieces, return <em>the <strong>minimum</strong> number of moves required to capture the black queen</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.</li>
<li>Bishops can move any number of squares diagonally, but cannot jump over other pieces.</li>
<li>A rook or a bishop can capture the queen if it is located in a square that they can move to.</li>
<li>The queen does not move.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex1.png" style="width: 600px; height: 600px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3001.Minimum%20Moves%20to%20Capture%20The%20Queen/images/ex2.png" style="width: 600px; height: 600px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can capture the black queen in a single move by doing one of the following:
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a, b, c, d, e, f <= 8</code></li>
<li>No two pieces are on the same square.</li>
</ul>
|
Math; Enumeration
|
TypeScript
|
function minMovesToCaptureTheQueen(
a: number,
b: number,
c: number,
d: number,
e: number,
f: number,
): number {
if (a === e && (c !== a || (d - b) * (d - f) > 0)) {
return 1;
}
if (b === f && (d !== b || (c - a) * (c - e) > 0)) {
return 1;
}
if (c - e === d - f && (a - e !== b - f || (a - c) * (a - e) > 0)) {
return 1;
}
if (c - e === f - d && (a - e !== f - b || (a - c) * (a - e) > 0)) {
return 1;
}
return 2;
}
|
3,002
|
Maximum Size of a Set After Removals
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of even length <code>n</code>.</p>
<p>You must remove <code>n / 2</code> elements from <code>nums1</code> and <code>n / 2</code> elements from <code>nums2</code>. After the removals, you insert the remaining elements of <code>nums1</code> and <code>nums2</code> into a set <code>s</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible size of the set</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,1,2], nums2 = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.
It can be shown that 2 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.
It can be shown that 5 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.
It can be shown that 6 is the maximum possible size of the set s after the removals.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
C++
|
class Solution {
public:
int maximumSetSize(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> s1(nums1.begin(), nums1.end());
unordered_set<int> s2(nums2.begin(), nums2.end());
int n = nums1.size();
int a = 0, b = 0, c = 0;
for (int x : s1) {
if (!s2.count(x)) {
++a;
}
}
for (int x : s2) {
if (!s1.count(x)) {
++b;
} else {
++c;
}
}
a = min(a, n / 2);
b = min(b, n / 2);
return min(a + b + c, n);
}
};
|
3,002
|
Maximum Size of a Set After Removals
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of even length <code>n</code>.</p>
<p>You must remove <code>n / 2</code> elements from <code>nums1</code> and <code>n / 2</code> elements from <code>nums2</code>. After the removals, you insert the remaining elements of <code>nums1</code> and <code>nums2</code> into a set <code>s</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible size of the set</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,1,2], nums2 = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.
It can be shown that 2 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.
It can be shown that 5 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.
It can be shown that 6 is the maximum possible size of the set s after the removals.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Go
|
func maximumSetSize(nums1 []int, nums2 []int) int {
s1 := map[int]bool{}
s2 := map[int]bool{}
for _, x := range nums1 {
s1[x] = true
}
for _, x := range nums2 {
s2[x] = true
}
a, b, c := 0, 0, 0
for x := range s1 {
if !s2[x] {
a++
}
}
for x := range s2 {
if !s1[x] {
b++
} else {
c++
}
}
n := len(nums1)
a = min(a, n/2)
b = min(b, n/2)
return min(a+b+c, n)
}
|
3,002
|
Maximum Size of a Set After Removals
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of even length <code>n</code>.</p>
<p>You must remove <code>n / 2</code> elements from <code>nums1</code> and <code>n / 2</code> elements from <code>nums2</code>. After the removals, you insert the remaining elements of <code>nums1</code> and <code>nums2</code> into a set <code>s</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible size of the set</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,1,2], nums2 = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.
It can be shown that 2 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.
It can be shown that 5 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.
It can be shown that 6 is the maximum possible size of the set s after the removals.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Java
|
class Solution {
public int maximumSetSize(int[] nums1, int[] nums2) {
Set<Integer> s1 = new HashSet<>();
Set<Integer> s2 = new HashSet<>();
for (int x : nums1) {
s1.add(x);
}
for (int x : nums2) {
s2.add(x);
}
int n = nums1.length;
int a = 0, b = 0, c = 0;
for (int x : s1) {
if (!s2.contains(x)) {
++a;
}
}
for (int x : s2) {
if (!s1.contains(x)) {
++b;
} else {
++c;
}
}
a = Math.min(a, n / 2);
b = Math.min(b, n / 2);
return Math.min(a + b + c, n);
}
}
|
3,002
|
Maximum Size of a Set After Removals
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of even length <code>n</code>.</p>
<p>You must remove <code>n / 2</code> elements from <code>nums1</code> and <code>n / 2</code> elements from <code>nums2</code>. After the removals, you insert the remaining elements of <code>nums1</code> and <code>nums2</code> into a set <code>s</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible size of the set</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,1,2], nums2 = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.
It can be shown that 2 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.
It can be shown that 5 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.
It can be shown that 6 is the maximum possible size of the set s after the removals.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Python
|
class Solution:
def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int:
s1 = set(nums1)
s2 = set(nums2)
n = len(nums1)
a = min(len(s1 - s2), n // 2)
b = min(len(s2 - s1), n // 2)
return min(a + b + len(s1 & s2), n)
|
3,002
|
Maximum Size of a Set After Removals
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of even length <code>n</code>.</p>
<p>You must remove <code>n / 2</code> elements from <code>nums1</code> and <code>n / 2</code> elements from <code>nums2</code>. After the removals, you insert the remaining elements of <code>nums1</code> and <code>nums2</code> into a set <code>s</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible size of the set</em> <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,1,2], nums2 = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.
It can be shown that 2 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.
It can be shown that 5 is the maximum possible size of the set s after the removals.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.
It can be shown that 6 is the maximum possible size of the set s after the removals.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
TypeScript
|
function maximumSetSize(nums1: number[], nums2: number[]): number {
const s1: Set<number> = new Set(nums1);
const s2: Set<number> = new Set(nums2);
const n = nums1.length;
let [a, b, c] = [0, 0, 0];
for (const x of s1) {
if (!s2.has(x)) {
++a;
}
}
for (const x of s2) {
if (!s1.has(x)) {
++b;
} else {
++c;
}
}
a = Math.min(a, n >> 1);
b = Math.min(b, n >> 1);
return Math.min(a + b + c, n);
}
|
3,003
|
Maximize the Number of Partitions After Operations
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>First, you are allowed to change <strong>at most</strong> <strong>one</strong> index in <code>s</code> to another lowercase English letter.</p>
<p>After that, do the following partitioning operation until <code>s</code> is <strong>empty</strong>:</p>
<ul>
<li>Choose the <strong>longest</strong> <strong>prefix</strong> of <code>s</code> containing at most <code>k</code> <strong>distinct</strong> characters.</li>
<li><strong>Delete</strong> the prefix from <code>s</code> and increase the number of partitions by one. The remaining characters (if any) in <code>s</code> maintain their initial order.</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> number of resulting partitions after the operations by optimally choosing at most one index to change.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "accca", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[2]</code> to something other than a and c, for example, b. then it becomes <code>"acbca"</code>.</p>
<p>Then we perform the operations:</p>
<ol>
<li>The longest prefix containing at most 2 distinct characters is <code>"ac"</code>, we remove it and <code>s</code> becomes <code>"bca"</code>.</li>
<li>Now The longest prefix containing at most 2 distinct characters is <code>"bc"</code>, so we remove it and <code>s</code> becomes <code>"a"</code>.</li>
<li>Finally, we remove <code>"a"</code> and <code>s</code> becomes empty, so the procedure ends.</li>
</ol>
<p>Doing the operations, the string is divided into 3 partitions, so the answer is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabaab", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially <code>s</code> contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xxyz", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[0]</code> or <code>s[1]</code> to something other than characters in <code>s</code>, for example, to change <code>s[0]</code> to <code>w</code>.</p>
<p>Then <code>s</code> becomes <code>"wxyz"</code>, which consists of 4 distinct characters, so as <code>k</code> is 1, it will divide into 4 partitions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>1 <= k <= 26</code></li>
</ul>
|
Bit Manipulation; String; Dynamic Programming; Bitmask
|
C++
|
class Solution {
public:
int maxPartitionsAfterOperations(string s, int k) {
int n = s.size();
unordered_map<long long, int> f;
function<int(int, int, int)> dfs = [&](int i, int cur, int t) {
if (i >= n) {
return 1;
}
long long key = (long long) i << 32 | cur << 1 | t;
if (f.count(key)) {
return f[key];
}
int v = 1 << (s[i] - 'a');
int nxt = cur | v;
int ans = __builtin_popcount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t);
if (t) {
for (int j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (__builtin_popcount(nxt) > k) {
ans = max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = max(ans, dfs(i + 1, nxt, 0));
}
}
}
return f[key] = ans;
};
return dfs(0, 0, 1);
}
};
|
3,003
|
Maximize the Number of Partitions After Operations
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>First, you are allowed to change <strong>at most</strong> <strong>one</strong> index in <code>s</code> to another lowercase English letter.</p>
<p>After that, do the following partitioning operation until <code>s</code> is <strong>empty</strong>:</p>
<ul>
<li>Choose the <strong>longest</strong> <strong>prefix</strong> of <code>s</code> containing at most <code>k</code> <strong>distinct</strong> characters.</li>
<li><strong>Delete</strong> the prefix from <code>s</code> and increase the number of partitions by one. The remaining characters (if any) in <code>s</code> maintain their initial order.</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> number of resulting partitions after the operations by optimally choosing at most one index to change.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "accca", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[2]</code> to something other than a and c, for example, b. then it becomes <code>"acbca"</code>.</p>
<p>Then we perform the operations:</p>
<ol>
<li>The longest prefix containing at most 2 distinct characters is <code>"ac"</code>, we remove it and <code>s</code> becomes <code>"bca"</code>.</li>
<li>Now The longest prefix containing at most 2 distinct characters is <code>"bc"</code>, so we remove it and <code>s</code> becomes <code>"a"</code>.</li>
<li>Finally, we remove <code>"a"</code> and <code>s</code> becomes empty, so the procedure ends.</li>
</ol>
<p>Doing the operations, the string is divided into 3 partitions, so the answer is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabaab", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially <code>s</code> contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xxyz", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[0]</code> or <code>s[1]</code> to something other than characters in <code>s</code>, for example, to change <code>s[0]</code> to <code>w</code>.</p>
<p>Then <code>s</code> becomes <code>"wxyz"</code>, which consists of 4 distinct characters, so as <code>k</code> is 1, it will divide into 4 partitions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>1 <= k <= 26</code></li>
</ul>
|
Bit Manipulation; String; Dynamic Programming; Bitmask
|
Go
|
func maxPartitionsAfterOperations(s string, k int) int {
n := len(s)
type tuple struct{ i, cur, t int }
f := map[tuple]int{}
var dfs func(i, cur, t int) int
dfs = func(i, cur, t int) int {
if i >= n {
return 1
}
key := tuple{i, cur, t}
if v, ok := f[key]; ok {
return v
}
v := 1 << (s[i] - 'a')
nxt := cur | v
var ans int
if bits.OnesCount(uint(nxt)) > k {
ans = dfs(i+1, v, t) + 1
} else {
ans = dfs(i+1, nxt, t)
}
if t > 0 {
for j := 0; j < 26; j++ {
nxt = cur | (1 << j)
if bits.OnesCount(uint(nxt)) > k {
ans = max(ans, dfs(i+1, 1<<j, 0)+1)
} else {
ans = max(ans, dfs(i+1, nxt, 0))
}
}
}
f[key] = ans
return ans
}
return dfs(0, 0, 1)
}
|
3,003
|
Maximize the Number of Partitions After Operations
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>First, you are allowed to change <strong>at most</strong> <strong>one</strong> index in <code>s</code> to another lowercase English letter.</p>
<p>After that, do the following partitioning operation until <code>s</code> is <strong>empty</strong>:</p>
<ul>
<li>Choose the <strong>longest</strong> <strong>prefix</strong> of <code>s</code> containing at most <code>k</code> <strong>distinct</strong> characters.</li>
<li><strong>Delete</strong> the prefix from <code>s</code> and increase the number of partitions by one. The remaining characters (if any) in <code>s</code> maintain their initial order.</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> number of resulting partitions after the operations by optimally choosing at most one index to change.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "accca", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[2]</code> to something other than a and c, for example, b. then it becomes <code>"acbca"</code>.</p>
<p>Then we perform the operations:</p>
<ol>
<li>The longest prefix containing at most 2 distinct characters is <code>"ac"</code>, we remove it and <code>s</code> becomes <code>"bca"</code>.</li>
<li>Now The longest prefix containing at most 2 distinct characters is <code>"bc"</code>, so we remove it and <code>s</code> becomes <code>"a"</code>.</li>
<li>Finally, we remove <code>"a"</code> and <code>s</code> becomes empty, so the procedure ends.</li>
</ol>
<p>Doing the operations, the string is divided into 3 partitions, so the answer is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabaab", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially <code>s</code> contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xxyz", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[0]</code> or <code>s[1]</code> to something other than characters in <code>s</code>, for example, to change <code>s[0]</code> to <code>w</code>.</p>
<p>Then <code>s</code> becomes <code>"wxyz"</code>, which consists of 4 distinct characters, so as <code>k</code> is 1, it will divide into 4 partitions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>1 <= k <= 26</code></li>
</ul>
|
Bit Manipulation; String; Dynamic Programming; Bitmask
|
Java
|
class Solution {
private Map<List<Integer>, Integer> f = new HashMap<>();
private String s;
private int k;
public int maxPartitionsAfterOperations(String s, int k) {
this.s = s;
this.k = k;
return dfs(0, 0, 1);
}
private int dfs(int i, int cur, int t) {
if (i >= s.length()) {
return 1;
}
var key = List.of(i, cur, t);
if (f.containsKey(key)) {
return f.get(key);
}
int v = 1 << (s.charAt(i) - 'a');
int nxt = cur | v;
int ans = Integer.bitCount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t);
if (t > 0) {
for (int j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (Integer.bitCount(nxt) > k) {
ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = Math.max(ans, dfs(i + 1, nxt, 0));
}
}
}
f.put(key, ans);
return ans;
}
}
|
3,003
|
Maximize the Number of Partitions After Operations
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>First, you are allowed to change <strong>at most</strong> <strong>one</strong> index in <code>s</code> to another lowercase English letter.</p>
<p>After that, do the following partitioning operation until <code>s</code> is <strong>empty</strong>:</p>
<ul>
<li>Choose the <strong>longest</strong> <strong>prefix</strong> of <code>s</code> containing at most <code>k</code> <strong>distinct</strong> characters.</li>
<li><strong>Delete</strong> the prefix from <code>s</code> and increase the number of partitions by one. The remaining characters (if any) in <code>s</code> maintain their initial order.</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> number of resulting partitions after the operations by optimally choosing at most one index to change.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "accca", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[2]</code> to something other than a and c, for example, b. then it becomes <code>"acbca"</code>.</p>
<p>Then we perform the operations:</p>
<ol>
<li>The longest prefix containing at most 2 distinct characters is <code>"ac"</code>, we remove it and <code>s</code> becomes <code>"bca"</code>.</li>
<li>Now The longest prefix containing at most 2 distinct characters is <code>"bc"</code>, so we remove it and <code>s</code> becomes <code>"a"</code>.</li>
<li>Finally, we remove <code>"a"</code> and <code>s</code> becomes empty, so the procedure ends.</li>
</ol>
<p>Doing the operations, the string is divided into 3 partitions, so the answer is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabaab", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially <code>s</code> contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xxyz", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[0]</code> or <code>s[1]</code> to something other than characters in <code>s</code>, for example, to change <code>s[0]</code> to <code>w</code>.</p>
<p>Then <code>s</code> becomes <code>"wxyz"</code>, which consists of 4 distinct characters, so as <code>k</code> is 1, it will divide into 4 partitions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>1 <= k <= 26</code></li>
</ul>
|
Bit Manipulation; String; Dynamic Programming; Bitmask
|
Python
|
class Solution:
def maxPartitionsAfterOperations(self, s: str, k: int) -> int:
@cache
def dfs(i: int, cur: int, t: int) -> int:
if i >= n:
return 1
v = 1 << (ord(s[i]) - ord("a"))
nxt = cur | v
if nxt.bit_count() > k:
ans = dfs(i + 1, v, t) + 1
else:
ans = dfs(i + 1, nxt, t)
if t:
for j in range(26):
nxt = cur | (1 << j)
if nxt.bit_count() > k:
ans = max(ans, dfs(i + 1, 1 << j, 0) + 1)
else:
ans = max(ans, dfs(i + 1, nxt, 0))
return ans
n = len(s)
return dfs(0, 0, 1)
|
3,003
|
Maximize the Number of Partitions After Operations
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>First, you are allowed to change <strong>at most</strong> <strong>one</strong> index in <code>s</code> to another lowercase English letter.</p>
<p>After that, do the following partitioning operation until <code>s</code> is <strong>empty</strong>:</p>
<ul>
<li>Choose the <strong>longest</strong> <strong>prefix</strong> of <code>s</code> containing at most <code>k</code> <strong>distinct</strong> characters.</li>
<li><strong>Delete</strong> the prefix from <code>s</code> and increase the number of partitions by one. The remaining characters (if any) in <code>s</code> maintain their initial order.</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> number of resulting partitions after the operations by optimally choosing at most one index to change.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "accca", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[2]</code> to something other than a and c, for example, b. then it becomes <code>"acbca"</code>.</p>
<p>Then we perform the operations:</p>
<ol>
<li>The longest prefix containing at most 2 distinct characters is <code>"ac"</code>, we remove it and <code>s</code> becomes <code>"bca"</code>.</li>
<li>Now The longest prefix containing at most 2 distinct characters is <code>"bc"</code>, so we remove it and <code>s</code> becomes <code>"a"</code>.</li>
<li>Finally, we remove <code>"a"</code> and <code>s</code> becomes empty, so the procedure ends.</li>
</ol>
<p>Doing the operations, the string is divided into 3 partitions, so the answer is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabaab", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially <code>s</code> contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xxyz", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The optimal way is to change <code>s[0]</code> or <code>s[1]</code> to something other than characters in <code>s</code>, for example, to change <code>s[0]</code> to <code>w</code>.</p>
<p>Then <code>s</code> becomes <code>"wxyz"</code>, which consists of 4 distinct characters, so as <code>k</code> is 1, it will divide into 4 partitions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
<li><code>1 <= k <= 26</code></li>
</ul>
|
Bit Manipulation; String; Dynamic Programming; Bitmask
|
TypeScript
|
function maxPartitionsAfterOperations(s: string, k: number): number {
const n = s.length;
const f: Map<bigint, number> = new Map();
const dfs = (i: number, cur: number, t: number): number => {
if (i >= n) {
return 1;
}
const key = (BigInt(i) << 27n) | (BigInt(cur) << 1n) | BigInt(t);
if (f.has(key)) {
return f.get(key)!;
}
const v = 1 << (s.charCodeAt(i) - 97);
let nxt = cur | v;
let ans = 0;
if (bitCount(nxt) > k) {
ans = dfs(i + 1, v, t) + 1;
} else {
ans = dfs(i + 1, nxt, t);
}
if (t) {
for (let j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (bitCount(nxt) > k) {
ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = Math.max(ans, dfs(i + 1, nxt, 0));
}
}
}
f.set(key, ans);
return ans;
};
return dfs(0, 0, 1);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
3,004
|
Maximum Subtree of the Same Color
|
Medium
|
<p>You are given a 2D integer array <code>edges</code> representing a tree with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>, rooted at node <code>0</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> means there is an edge between the nodes <code>v<sub>i</sub></code> and <code>u<sub>i</sub></code>.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>colors</code> of size <code>n</code>, where <code>colors[i]</code> is the color assigned to node <code>i</code>.</p>
<p>We want to find a node <code>v</code> such that every node in the <span data-keyword="subtree-of-node">subtree</span> of <code>v</code> has the <strong>same</strong> color.</p>
<p>Return <em>the size of such subtree with the <strong>maximum</strong> number of nodes possible.</em></p>
<p> </p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134026.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 132px;" /></strong></p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.
</pre>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 221px;" /></strong></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == edges.length + 1</code></li>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>colors.length == n</code></li>
<li><code>1 <= colors[i] <= 10<sup>5</sup></code></li>
<li>The input is generated such that the graph represented by <code>edges</code> is a tree.</li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
C++
|
class Solution {
public:
int maximumSubtreeSize(vector<vector<int>>& edges, vector<int>& colors) {
int n = edges.size() + 1;
vector<int> g[n];
vector<int> size(n, 1);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
int ans = 0;
function<bool(int, int)> dfs = [&](int a, int fa) {
bool ok = true;
for (int b : g[a]) {
if (b != fa) {
bool t = dfs(b, a);
ok = ok && colors[a] == colors[b] && t;
size[a] += size[b];
}
}
if (ok) {
ans = max(ans, size[a]);
}
return ok;
};
dfs(0, -1);
return ans;
}
};
|
3,004
|
Maximum Subtree of the Same Color
|
Medium
|
<p>You are given a 2D integer array <code>edges</code> representing a tree with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>, rooted at node <code>0</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> means there is an edge between the nodes <code>v<sub>i</sub></code> and <code>u<sub>i</sub></code>.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>colors</code> of size <code>n</code>, where <code>colors[i]</code> is the color assigned to node <code>i</code>.</p>
<p>We want to find a node <code>v</code> such that every node in the <span data-keyword="subtree-of-node">subtree</span> of <code>v</code> has the <strong>same</strong> color.</p>
<p>Return <em>the size of such subtree with the <strong>maximum</strong> number of nodes possible.</em></p>
<p> </p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134026.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 132px;" /></strong></p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.
</pre>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 221px;" /></strong></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == edges.length + 1</code></li>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>colors.length == n</code></li>
<li><code>1 <= colors[i] <= 10<sup>5</sup></code></li>
<li>The input is generated such that the graph represented by <code>edges</code> is a tree.</li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Go
|
func maximumSubtreeSize(edges [][]int, colors []int) (ans int) {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
size := make([]int, n)
var dfs func(int, int) bool
dfs = func(a, fa int) bool {
size[a] = 1
ok := true
for _, b := range g[a] {
if b != fa {
t := dfs(b, a)
ok = ok && t && colors[a] == colors[b]
size[a] += size[b]
}
}
if ok {
ans = max(ans, size[a])
}
return ok
}
dfs(0, -1)
return
}
|
3,004
|
Maximum Subtree of the Same Color
|
Medium
|
<p>You are given a 2D integer array <code>edges</code> representing a tree with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>, rooted at node <code>0</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> means there is an edge between the nodes <code>v<sub>i</sub></code> and <code>u<sub>i</sub></code>.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>colors</code> of size <code>n</code>, where <code>colors[i]</code> is the color assigned to node <code>i</code>.</p>
<p>We want to find a node <code>v</code> such that every node in the <span data-keyword="subtree-of-node">subtree</span> of <code>v</code> has the <strong>same</strong> color.</p>
<p>Return <em>the size of such subtree with the <strong>maximum</strong> number of nodes possible.</em></p>
<p> </p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134026.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 132px;" /></strong></p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.
</pre>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 221px;" /></strong></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == edges.length + 1</code></li>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>colors.length == n</code></li>
<li><code>1 <= colors[i] <= 10<sup>5</sup></code></li>
<li>The input is generated such that the graph represented by <code>edges</code> is a tree.</li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Java
|
class Solution {
private List<Integer>[] g;
private int[] colors;
private int[] size;
private int ans;
public int maximumSubtreeSize(int[][] edges, int[] colors) {
int n = edges.length + 1;
g = new List[n];
size = new int[n];
this.colors = colors;
Arrays.fill(size, 1);
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
dfs(0, -1);
return ans;
}
private boolean dfs(int a, int fa) {
boolean ok = true;
for (int b : g[a]) {
if (b != fa) {
boolean t = dfs(b, a);
ok = ok && colors[a] == colors[b] && t;
size[a] += size[b];
}
}
if (ok) {
ans = Math.max(ans, size[a]);
}
return ok;
}
}
|
3,004
|
Maximum Subtree of the Same Color
|
Medium
|
<p>You are given a 2D integer array <code>edges</code> representing a tree with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>, rooted at node <code>0</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> means there is an edge between the nodes <code>v<sub>i</sub></code> and <code>u<sub>i</sub></code>.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>colors</code> of size <code>n</code>, where <code>colors[i]</code> is the color assigned to node <code>i</code>.</p>
<p>We want to find a node <code>v</code> such that every node in the <span data-keyword="subtree-of-node">subtree</span> of <code>v</code> has the <strong>same</strong> color.</p>
<p>Return <em>the size of such subtree with the <strong>maximum</strong> number of nodes possible.</em></p>
<p> </p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134026.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 132px;" /></strong></p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.
</pre>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 221px;" /></strong></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == edges.length + 1</code></li>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>colors.length == n</code></li>
<li><code>1 <= colors[i] <= 10<sup>5</sup></code></li>
<li>The input is generated such that the graph represented by <code>edges</code> is a tree.</li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Python
|
class Solution:
def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int:
def dfs(a: int, fa: int) -> bool:
ok = True
for b in g[a]:
if b != fa:
t = dfs(b, a)
ok = ok and colors[a] == colors[b] and t
size[a] += size[b]
if ok:
nonlocal ans
ans = max(ans, size[a])
return ok
n = len(edges) + 1
g = [[] for _ in range(n)]
size = [1] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
|
3,004
|
Maximum Subtree of the Same Color
|
Medium
|
<p>You are given a 2D integer array <code>edges</code> representing a tree with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>, rooted at node <code>0</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> means there is an edge between the nodes <code>v<sub>i</sub></code> and <code>u<sub>i</sub></code>.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>colors</code> of size <code>n</code>, where <code>colors[i]</code> is the color assigned to node <code>i</code>.</p>
<p>We want to find a node <code>v</code> such that every node in the <span data-keyword="subtree-of-node">subtree</span> of <code>v</code> has the <strong>same</strong> color.</p>
<p>Return <em>the size of such subtree with the <strong>maximum</strong> number of nodes possible.</em></p>
<p> </p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134026.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 132px;" /></strong></p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,2,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color and has a size of 1. Hence, we return 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3]], colors = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The whole tree has the same color, and the subtree rooted at node 0 has the most number of nodes which is 4. Hence, we return 4.
</pre>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3004.Maximum%20Subtree%20of%20the%20Same%20Color/images/20231216-134017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 221px; height: 221px;" /></strong></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,3,3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each color is represented as: 1 -> Red, 2 -> Green, 3 -> Blue. We can see that the subtree rooted at node 0 has children with different colors. Any other subtree is of the same color, but the subtree rooted at node 2 has a size of 3 which is the maximum. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == edges.length + 1</code></li>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>colors.length == n</code></li>
<li><code>1 <= colors[i] <= 10<sup>5</sup></code></li>
<li>The input is generated such that the graph represented by <code>edges</code> is a tree.</li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
TypeScript
|
function maximumSubtreeSize(edges: number[][], colors: number[]): number {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const size: number[] = Array(n).fill(1);
let ans = 0;
const dfs = (a: number, fa: number): boolean => {
let ok = true;
for (const b of g[a]) {
if (b !== fa) {
const t = dfs(b, a);
ok = ok && t && colors[a] === colors[b];
size[a] += size[b];
}
}
if (ok) {
ans = Math.max(ans, size[a]);
}
return ok;
};
dfs(0, -1);
return ans;
}
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
C++
|
class Solution {
public:
int maxFrequencyElements(vector<int>& nums) {
int cnt[101]{};
for (int x : nums) {
++cnt[x];
}
int ans = 0, mx = -1;
for (int x : cnt) {
if (mx < x) {
mx = x;
ans = x;
} else if (mx == x) {
ans += x;
}
}
return ans;
}
};
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
C#
|
public class Solution {
public int MaxFrequencyElements(int[] nums) {
int[] cnt = new int[101];
foreach (int x in nums) {
++cnt[x];
}
int ans = 0, mx = -1;
foreach (int x in cnt) {
if (mx < x) {
mx = x;
ans = x;
} else if (mx == x) {
ans += x;
}
}
return ans;
}
}
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Go
|
func maxFrequencyElements(nums []int) (ans int) {
cnt := [101]int{}
for _, x := range nums {
cnt[x]++
}
mx := -1
for _, x := range cnt {
if mx < x {
mx, ans = x, x
} else if mx == x {
ans += x
}
}
return
}
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Java
|
class Solution {
public int maxFrequencyElements(int[] nums) {
int[] cnt = new int[101];
for (int x : nums) {
++cnt[x];
}
int ans = 0, mx = -1;
for (int x : cnt) {
if (mx < x) {
mx = x;
ans = x;
} else if (mx == x) {
ans += x;
}
}
return ans;
}
}
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
JavaScript
|
/**
* @param {number[]} nums
* @return {number}
*/
var maxFrequencyElements = function (nums) {
const cnt = new Array(101).fill(0);
for (const x of nums) {
++cnt[x];
}
let [ans, mx] = [0, -1];
for (const x of cnt) {
if (mx < x) {
mx = x;
ans = x;
} else if (mx === x) {
ans += x;
}
}
return ans;
};
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Python
|
class Solution:
def maxFrequencyElements(self, nums: List[int]) -> int:
cnt = Counter(nums)
mx = max(cnt.values())
return sum(x for x in cnt.values() if x == mx)
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Rust
|
impl Solution {
pub fn max_frequency_elements(nums: Vec<i32>) -> i32 {
let mut cnt = [0; 101];
for &x in &nums {
cnt[x as usize] += 1;
}
let mut ans = 0;
let mut mx = -1;
for &x in &cnt {
if mx < x {
mx = x;
ans = x;
} else if mx == x {
ans += x;
}
}
ans
}
}
|
3,005
|
Count Elements With Maximum Frequency
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code> <em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
TypeScript
|
function maxFrequencyElements(nums: number[]): number {
const cnt: number[] = Array(101).fill(0);
for (const x of nums) {
++cnt[x];
}
let [ans, mx] = [0, -1];
for (const x of cnt) {
if (mx < x) {
mx = x;
ans = x;
} else if (mx === x) {
ans += x;
}
}
return ans;
}
|
3,006
|
Find Beautiful Indices in the Given Array I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 10</code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
C++
|
class Solution {
public:
vector<int> beautifulIndices(string s, string patternA, string patternB, int k) {
vector<int> beautifulIndicesA = kmpSearch(s, patternA);
vector<int> beautifulIndicesB = kmpSearch(s, patternB);
sort(beautifulIndicesB.begin(), beautifulIndicesB.end());
vector<int> result;
for (int indexA : beautifulIndicesA) {
int left = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA - k) - beautifulIndicesB.begin();
int right = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA + k + patternB.length()) - beautifulIndicesB.begin();
left = (left >= 0) ? left : -(left + 1);
right = (right >= 0) ? right : -(right + 1);
for (int indexB = left; indexB < right; indexB++) {
if (abs(beautifulIndicesB[indexB] - indexA) <= k) {
result.push_back(indexA);
break;
}
}
}
return result;
}
private:
vector<int> kmpSearch(string text, string pattern) {
vector<int> indices;
vector<int> pi = computePrefixFunction(pattern);
int q = 0;
for (int i = 0; i < text.length(); i++) {
while (q > 0 && pattern[q] != text[i]) {
q = pi[q - 1];
}
if (pattern[q] == text[i]) {
q++;
}
if (q == pattern.length()) {
indices.push_back(i - q + 1);
q = pi[q - 1];
}
}
return indices;
}
vector<int> computePrefixFunction(string pattern) {
int m = pattern.length();
vector<int> pi(m, 0);
int k = 0;
for (int q = 1; q < m; q++) {
while (k > 0 && pattern[k] != pattern[q]) {
k = pi[k - 1];
}
if (pattern[k] == pattern[q]) {
k++;
}
pi[q] = k;
}
return pi;
}
};
|
3,006
|
Find Beautiful Indices in the Given Array I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 10</code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Go
|
func beautifulIndices(s string, a string, b string, k int) []int {
s_len := len(s)
a_len := len(a)
b_len := len(b)
final := make([]int, 0)
lps_a := make([]int, a_len)
lps_b := make([]int, b_len)
a_index := make([]int, 0)
b_index := make([]int, 0)
var pat func(lps []int, s_l int, pattern string)
pat = func(lps []int, s_l int, pattern string) {
l := 0
lps[0] = 0
i := 1
for i < s_l {
if pattern[i] == pattern[l] {
l++
lps[i] = l
i++
} else {
if l != 0 {
l = lps[l-1]
} else {
lps[i] = l
i++
}
}
}
}
pat(lps_a, a_len, a)
pat(lps_b, b_len, b)
var kmp func(pat string, pat_l int, lps []int, index *[]int)
kmp = func(pat string, pat_l int, lps []int, index *[]int) {
i := 0
j := 0
for s_len-i >= pat_l-j {
if s[i] == pat[j] {
i++
j++
}
if j == pat_l {
*index = append(*index, i-pat_l)
j = lps[j-1]
} else if s[i] != pat[j] {
if j != 0 {
j = lps[j-1]
} else {
i++
}
}
}
}
kmp(a, a_len, lps_a, &a_index)
kmp(b, b_len, lps_b, &b_index)
// fmt.Println(a_index, b_index)
i := 0
j := 0
for i < len(a_index) && j < len(b_index) {
if a_index[i]+k >= b_index[j] && a_index[i]-k <= b_index[j] {
final = append(final, a_index[i])
i++
} else if a_index[i]-k > b_index[j] {
j++
} else {
i++
}
}
return final
}
|
3,006
|
Find Beautiful Indices in the Given Array I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 10</code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Java
|
public class Solution {
public void computeLPS(String pattern, int[] lps) {
int M = pattern.length();
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
public List<Integer> KMP_codestorywithMIK(String pat, String txt) {
int N = txt.length();
int M = pat.length();
List<Integer> result = new ArrayList<>();
int[] lps = new int[M];
computeLPS(pat, lps);
int i = 0; // Index for text
int j = 0; // Index for pattern
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
i++;
j++;
}
if (j == M) {
result.add(i - j); // Pattern found at index i-j+1 (If you have to return 1 Based
// indexing, that's why added + 1)
j = lps[j - 1];
} else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return result;
}
private int lowerBound(List<Integer> list, int target) {
int left = 0, right = list.size() - 1, result = list.size();
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) >= target) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
public List<Integer> beautifulIndices(String s, String a, String b, int k) {
int n = s.length();
List<Integer> i_indices = KMP_codestorywithMIK(a, s);
List<Integer> j_indices = KMP_codestorywithMIK(b, s);
List<Integer> result = new ArrayList<>();
for (int i : i_indices) {
int left_limit = Math.max(0, i - k); // To avoid out of bound -> I used max(0, i-k)
int right_limit
= Math.min(n - 1, i + k); // To avoid out of bound -> I used min(n-1, i+k)
int lowerBoundIndex = lowerBound(j_indices, left_limit);
if (lowerBoundIndex < j_indices.size()
&& j_indices.get(lowerBoundIndex) <= right_limit) {
result.add(i);
}
}
return result;
}
}
|
3,006
|
Find Beautiful Indices in the Given Array I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 10</code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Python
|
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
def build_prefix_function(pattern):
prefix_function = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[i] != pattern[j]:
j = prefix_function[j - 1]
if pattern[i] == pattern[j]:
j += 1
prefix_function[i] = j
return prefix_function
def kmp_search(pattern, text, prefix_function):
occurrences = []
j = 0
for i in range(len(text)):
while j > 0 and text[i] != pattern[j]:
j = prefix_function[j - 1]
if text[i] == pattern[j]:
j += 1
if j == len(pattern):
occurrences.append(i - j + 1)
j = prefix_function[j - 1]
return occurrences
prefix_a = build_prefix_function(a)
prefix_b = build_prefix_function(b)
resa = kmp_search(a, s, prefix_a)
resb = kmp_search(b, s, prefix_b)
res = []
print(resa, resb)
i = 0
j = 0
while i < len(resa):
while j < len(resb):
if abs(resb[j] - resa[i]) <= k:
res.append(resa[i])
break
elif j + 1 < len(resb) and abs(resb[j + 1] - resa[i]) < abs(
resb[j] - resa[i]
):
j += 1
else:
break
i += 1
return res
|
3,007
|
Maximum Number That Sum of the Prices Is Less Than or Equal to K
|
Medium
|
<p>You are given an integer <code>k</code> and an integer <code>x</code>. The price of a number <code>num</code> is calculated by the count of <span data-keyword="set-bit">set bits</span> at positions <code>x</code>, <code>2x</code>, <code>3x</code>, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td><u>0</u><u>0</u><u>0</u><u>0</u><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>0<u>0</u>0<u>0</u>0<strong><u>1</u></strong>1<u>0</u>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>233</td>
<td>0<strong><u>1</u></strong>1<strong><u>1</u></strong>0<strong><u>1</u></strong>0<u>0</u>1</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>13</td>
<td><u>0</u>00<u>0</u>01<strong><u>1</u></strong>01</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>362</td>
<td><strong><u>1</u></strong>01<strong><u>1</u></strong>01<u>0</u>10</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>The <strong>accumulated price</strong> of <code>num</code> is the <b>total</b> price of numbers from <code>1</code> to <code>num</code>. <code>num</code> is considered <strong>cheap</strong> if its accumulated price is less than or equal to <code>k</code>.</p>
<p>Return the <b>greatest</b> cheap number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 9, x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>6</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td><u>0</u><u>0</u><strong><u>1</u></strong></td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><u>0</u><strong><u>1</u></strong><u>0</u></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td><strong><u>1</u></strong><u>0</u><u>0</u></td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u></td>
<td>2</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>7</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>3</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 7, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>9</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><u>0</u>0<u>0</u>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><u>0</u>0<strong><u>1</u></strong>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td><u>0</u>0<strong><u>1</u></strong>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td><u>0</u>1<u>0</u>0</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td><u>0</u>1<u>0</u>1</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td><u>0</u>1<strong><u>1</u></strong>0</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
<td><u>0</u>1<strong><u>1</u></strong>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td><strong><u>1</u></strong>0<u>0</u>0</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>9</td>
<td><strong><u>1</u></strong>0<u>0</u>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td><strong><u>1</u></strong>0<strong><u>1</u></strong>0</td>
<td>2</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>15</sup></code></li>
<li><code>1 <= x <= 8</code></li>
</ul>
|
Bit Manipulation; Binary Search; Dynamic Programming
|
C++
|
class Solution {
public:
long long findMaximumNumber(long long k, int x) {
using ll = long long;
ll l = 1, r = 1e17;
ll num = 0;
ll f[65][65];
auto dfs = [&](this auto&& dfs, int pos, int cnt, bool limit) -> ll {
if (pos == 0) {
return cnt;
}
if (!limit && f[pos][cnt] != -1) {
return f[pos][cnt];
}
int up = limit ? num >> (pos - 1) & 1 : 1;
ll ans = 0;
for (int i = 0; i <= up; ++i) {
ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0), limit && i == up);
}
if (!limit) {
f[pos][cnt] = ans;
}
return ans;
};
while (l < r) {
ll mid = (l + r + 1) >> 1;
num = mid;
memset(f, -1, sizeof(f));
int pos = 64 - __builtin_clzll(mid);
if (dfs(pos, 0, true) <= k) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
};
|
3,007
|
Maximum Number That Sum of the Prices Is Less Than or Equal to K
|
Medium
|
<p>You are given an integer <code>k</code> and an integer <code>x</code>. The price of a number <code>num</code> is calculated by the count of <span data-keyword="set-bit">set bits</span> at positions <code>x</code>, <code>2x</code>, <code>3x</code>, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td><u>0</u><u>0</u><u>0</u><u>0</u><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>0<u>0</u>0<u>0</u>0<strong><u>1</u></strong>1<u>0</u>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>233</td>
<td>0<strong><u>1</u></strong>1<strong><u>1</u></strong>0<strong><u>1</u></strong>0<u>0</u>1</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>13</td>
<td><u>0</u>00<u>0</u>01<strong><u>1</u></strong>01</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>362</td>
<td><strong><u>1</u></strong>01<strong><u>1</u></strong>01<u>0</u>10</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>The <strong>accumulated price</strong> of <code>num</code> is the <b>total</b> price of numbers from <code>1</code> to <code>num</code>. <code>num</code> is considered <strong>cheap</strong> if its accumulated price is less than or equal to <code>k</code>.</p>
<p>Return the <b>greatest</b> cheap number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 9, x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>6</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td><u>0</u><u>0</u><strong><u>1</u></strong></td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><u>0</u><strong><u>1</u></strong><u>0</u></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td><strong><u>1</u></strong><u>0</u><u>0</u></td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u></td>
<td>2</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>7</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>3</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 7, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>9</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><u>0</u>0<u>0</u>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><u>0</u>0<strong><u>1</u></strong>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td><u>0</u>0<strong><u>1</u></strong>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td><u>0</u>1<u>0</u>0</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td><u>0</u>1<u>0</u>1</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td><u>0</u>1<strong><u>1</u></strong>0</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
<td><u>0</u>1<strong><u>1</u></strong>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td><strong><u>1</u></strong>0<u>0</u>0</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>9</td>
<td><strong><u>1</u></strong>0<u>0</u>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td><strong><u>1</u></strong>0<strong><u>1</u></strong>0</td>
<td>2</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>15</sup></code></li>
<li><code>1 <= x <= 8</code></li>
</ul>
|
Bit Manipulation; Binary Search; Dynamic Programming
|
Go
|
func findMaximumNumber(k int64, x int) int64 {
var l, r int64 = 1, 1e17
var num int64
var f [65][65]int64
var dfs func(pos, cnt int, limit bool) int64
dfs = func(pos, cnt int, limit bool) int64 {
if pos == 0 {
return int64(cnt)
}
if !limit && f[pos][cnt] != -1 {
return f[pos][cnt]
}
var ans int64
up := 1
if limit {
up = int(num >> (pos - 1) & 1)
}
for i := 0; i <= up; i++ {
v := cnt
if i == 1 && pos%x == 0 {
v++
}
ans += dfs(pos-1, v, limit && i == up)
}
if !limit {
f[pos][cnt] = ans
}
return ans
}
for l < r {
mid := (l + r + 1) >> 1
num = mid
m := bits.Len(uint(num))
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
if dfs(m, 0, true) <= k {
l = mid
} else {
r = mid - 1
}
}
return l
}
|
3,007
|
Maximum Number That Sum of the Prices Is Less Than or Equal to K
|
Medium
|
<p>You are given an integer <code>k</code> and an integer <code>x</code>. The price of a number <code>num</code> is calculated by the count of <span data-keyword="set-bit">set bits</span> at positions <code>x</code>, <code>2x</code>, <code>3x</code>, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td><u>0</u><u>0</u><u>0</u><u>0</u><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>0<u>0</u>0<u>0</u>0<strong><u>1</u></strong>1<u>0</u>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>233</td>
<td>0<strong><u>1</u></strong>1<strong><u>1</u></strong>0<strong><u>1</u></strong>0<u>0</u>1</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>13</td>
<td><u>0</u>00<u>0</u>01<strong><u>1</u></strong>01</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>362</td>
<td><strong><u>1</u></strong>01<strong><u>1</u></strong>01<u>0</u>10</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>The <strong>accumulated price</strong> of <code>num</code> is the <b>total</b> price of numbers from <code>1</code> to <code>num</code>. <code>num</code> is considered <strong>cheap</strong> if its accumulated price is less than or equal to <code>k</code>.</p>
<p>Return the <b>greatest</b> cheap number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 9, x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>6</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td><u>0</u><u>0</u><strong><u>1</u></strong></td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><u>0</u><strong><u>1</u></strong><u>0</u></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td><strong><u>1</u></strong><u>0</u><u>0</u></td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u></td>
<td>2</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>7</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>3</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 7, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>9</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><u>0</u>0<u>0</u>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><u>0</u>0<strong><u>1</u></strong>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td><u>0</u>0<strong><u>1</u></strong>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td><u>0</u>1<u>0</u>0</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td><u>0</u>1<u>0</u>1</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td><u>0</u>1<strong><u>1</u></strong>0</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
<td><u>0</u>1<strong><u>1</u></strong>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td><strong><u>1</u></strong>0<u>0</u>0</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>9</td>
<td><strong><u>1</u></strong>0<u>0</u>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td><strong><u>1</u></strong>0<strong><u>1</u></strong>0</td>
<td>2</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>15</sup></code></li>
<li><code>1 <= x <= 8</code></li>
</ul>
|
Bit Manipulation; Binary Search; Dynamic Programming
|
Java
|
class Solution {
private int x;
private long num;
private Long[][] f;
public long findMaximumNumber(long k, int x) {
this.x = x;
long l = 1, r = (long) 1e17;
while (l < r) {
long mid = (l + r + 1) >>> 1;
num = mid;
f = new Long[65][65];
int pos = 64 - Long.numberOfLeadingZeros(mid);
if (dfs(pos, 0, true) <= k) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
private long dfs(int pos, int cnt, boolean limit) {
if (pos == 0) {
return cnt;
}
if (!limit && f[pos][cnt] != null) {
return f[pos][cnt];
}
long ans = 0;
int up = limit ? (int) (num >> (pos - 1) & 1) : 1;
for (int i = 0; i <= up; ++i) {
ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0 ? 1 : 0), limit && i == up);
}
if (!limit) {
f[pos][cnt] = ans;
}
return ans;
}
}
|
3,007
|
Maximum Number That Sum of the Prices Is Less Than or Equal to K
|
Medium
|
<p>You are given an integer <code>k</code> and an integer <code>x</code>. The price of a number <code>num</code> is calculated by the count of <span data-keyword="set-bit">set bits</span> at positions <code>x</code>, <code>2x</code>, <code>3x</code>, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td><u>0</u><u>0</u><u>0</u><u>0</u><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>0<u>0</u>0<u>0</u>0<strong><u>1</u></strong>1<u>0</u>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>233</td>
<td>0<strong><u>1</u></strong>1<strong><u>1</u></strong>0<strong><u>1</u></strong>0<u>0</u>1</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>13</td>
<td><u>0</u>00<u>0</u>01<strong><u>1</u></strong>01</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>362</td>
<td><strong><u>1</u></strong>01<strong><u>1</u></strong>01<u>0</u>10</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>The <strong>accumulated price</strong> of <code>num</code> is the <b>total</b> price of numbers from <code>1</code> to <code>num</code>. <code>num</code> is considered <strong>cheap</strong> if its accumulated price is less than or equal to <code>k</code>.</p>
<p>Return the <b>greatest</b> cheap number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 9, x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>6</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td><u>0</u><u>0</u><strong><u>1</u></strong></td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><u>0</u><strong><u>1</u></strong><u>0</u></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td><strong><u>1</u></strong><u>0</u><u>0</u></td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u></td>
<td>2</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>7</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>3</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 7, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>9</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><u>0</u>0<u>0</u>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><u>0</u>0<strong><u>1</u></strong>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td><u>0</u>0<strong><u>1</u></strong>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td><u>0</u>1<u>0</u>0</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td><u>0</u>1<u>0</u>1</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td><u>0</u>1<strong><u>1</u></strong>0</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
<td><u>0</u>1<strong><u>1</u></strong>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td><strong><u>1</u></strong>0<u>0</u>0</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>9</td>
<td><strong><u>1</u></strong>0<u>0</u>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td><strong><u>1</u></strong>0<strong><u>1</u></strong>0</td>
<td>2</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>15</sup></code></li>
<li><code>1 <= x <= 8</code></li>
</ul>
|
Bit Manipulation; Binary Search; Dynamic Programming
|
Python
|
class Solution:
def findMaximumNumber(self, k: int, x: int) -> int:
@cache
def dfs(pos, limit, cnt):
if pos == 0:
return cnt
ans = 0
up = (self.num >> (pos - 1) & 1) if limit else 1
for i in range(up + 1):
ans += dfs(pos - 1, limit and i == up, cnt + (i == 1 and pos % x == 0))
return ans
l, r = 1, 10**18
while l < r:
mid = (l + r + 1) >> 1
self.num = mid
v = dfs(mid.bit_length(), True, 0)
dfs.cache_clear()
if v <= k:
l = mid
else:
r = mid - 1
return l
|
3,007
|
Maximum Number That Sum of the Prices Is Less Than or Equal to K
|
Medium
|
<p>You are given an integer <code>k</code> and an integer <code>x</code>. The price of a number <code>num</code> is calculated by the count of <span data-keyword="set-bit">set bits</span> at positions <code>x</code>, <code>2x</code>, <code>3x</code>, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>13</td>
<td><u>0</u><u>0</u><u>0</u><u>0</u><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>13</td>
<td>0<u>0</u>0<u>0</u>0<strong><u>1</u></strong>1<u>0</u>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>233</td>
<td>0<strong><u>1</u></strong>1<strong><u>1</u></strong>0<strong><u>1</u></strong>0<u>0</u>1</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>13</td>
<td><u>0</u>00<u>0</u>01<strong><u>1</u></strong>01</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>362</td>
<td><strong><u>1</u></strong>01<strong><u>1</u></strong>01<u>0</u>10</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>The <strong>accumulated price</strong> of <code>num</code> is the <b>total</b> price of numbers from <code>1</code> to <code>num</code>. <code>num</code> is considered <strong>cheap</strong> if its accumulated price is less than or equal to <code>k</code>.</p>
<p>Return the <b>greatest</b> cheap number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 9, x = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>6</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td><u>0</u><u>0</u><strong><u>1</u></strong></td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><u>0</u><strong><u>1</u></strong><u>0</u></td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td><u>0</u><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td><strong><u>1</u></strong><u>0</u><u>0</u></td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>5</td>
<td><strong><u>1</u></strong><u>0</u><strong><u>1</u></strong></td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><u>0</u></td>
<td>2</td>
<td>9</td>
</tr>
<tr>
<td>1</td>
<td>7</td>
<td><strong><u>1</u></strong><strong><u>1</u></strong><strong><u>1</u></strong></td>
<td>3</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 7, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>As shown in the table below, <code>9</code> is the greatest cheap number.</p>
<table border="1">
<tbody>
<tr>
<th>x</th>
<th>num</th>
<th>Binary Representation</th>
<th>Price</th>
<th>Accumulated Price</th>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><u>0</u>0<u>0</u>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><u>0</u>0<strong><u>1</u></strong>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td><u>0</u>0<strong><u>1</u></strong>1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td><u>0</u>1<u>0</u>0</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td><u>0</u>1<u>0</u>1</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
<td><u>0</u>1<strong><u>1</u></strong>0</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
<td><u>0</u>1<strong><u>1</u></strong>1</td>
<td>1</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td><strong><u>1</u></strong>0<u>0</u>0</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>9</td>
<td><strong><u>1</u></strong>0<u>0</u>1</td>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>10</td>
<td><strong><u>1</u></strong>0<strong><u>1</u></strong>0</td>
<td>2</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>15</sup></code></li>
<li><code>1 <= x <= 8</code></li>
</ul>
|
Bit Manipulation; Binary Search; Dynamic Programming
|
TypeScript
|
function findMaximumNumber(k: number, x: number): number {
let [l, r] = [1n, 10n ** 17n];
let num: bigint;
const f: bigint[][] = Array.from({ length: 65 }, () => Array(65).fill(-1n));
const dfs = (pos: number, cnt: number, limit: boolean): bigint => {
if (pos === 0) {
return BigInt(cnt);
}
if (!limit && f[pos][cnt] !== -1n) {
return f[pos][cnt];
}
let ans: bigint = 0n;
let up: number = 1;
if (limit) {
up = Number((num >> BigInt(pos - 1)) & 1n);
}
for (let i = 0; i <= up; i++) {
let v: number = cnt;
if (i === 1 && pos % x === 0) {
v++;
}
ans += dfs(pos - 1, v, limit && i === up);
}
if (!limit) {
f[pos][cnt] = ans;
}
return ans;
};
while (l < r) {
let mid: bigint = (l + r + 1n) >> 1n;
num = mid;
let m: number = num.toString(2).length;
for (let i = 0; i < f.length; i++) {
f[i].fill(-1n);
}
if (dfs(m, 0, true) <= BigInt(k)) {
l = mid;
} else {
r = mid - 1n;
}
}
return Number(l);
}
|
3,008
|
Find Beautiful Indices in the Given Array II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
C++
|
class Solution {
public:
vector<int> beautifulIndices(string s, string patternA, string patternB, int k) {
vector<int> beautifulIndicesA = kmpSearch(s, patternA);
vector<int> beautifulIndicesB = kmpSearch(s, patternB);
sort(beautifulIndicesB.begin(), beautifulIndicesB.end());
vector<int> result;
for (int indexA : beautifulIndicesA) {
int left = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA - k) - beautifulIndicesB.begin();
int right = lower_bound(beautifulIndicesB.begin(), beautifulIndicesB.end(), indexA + k + patternB.length()) - beautifulIndicesB.begin();
left = (left >= 0) ? left : -(left + 1);
right = (right >= 0) ? right : -(right + 1);
for (int indexB = left; indexB < right; indexB++) {
if (abs(beautifulIndicesB[indexB] - indexA) <= k) {
result.push_back(indexA);
break;
}
}
}
return result;
}
private:
vector<int> kmpSearch(string text, string pattern) {
vector<int> indices;
vector<int> pi = computePrefixFunction(pattern);
int q = 0;
for (int i = 0; i < text.length(); i++) {
while (q > 0 && pattern[q] != text[i]) {
q = pi[q - 1];
}
if (pattern[q] == text[i]) {
q++;
}
if (q == pattern.length()) {
indices.push_back(i - q + 1);
q = pi[q - 1];
}
}
return indices;
}
vector<int> computePrefixFunction(string pattern) {
int m = pattern.length();
vector<int> pi(m, 0);
int k = 0;
for (int q = 1; q < m; q++) {
while (k > 0 && pattern[k] != pattern[q]) {
k = pi[k - 1];
}
if (pattern[k] == pattern[q]) {
k++;
}
pi[q] = k;
}
return pi;
}
};
|
3,008
|
Find Beautiful Indices in the Given Array II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Go
|
func beautifulIndices(s string, a string, b string, k int) []int {
s_len := len(s)
a_len := len(a)
b_len := len(b)
final := make([]int, 0)
lps_a := make([]int, a_len)
lps_b := make([]int, b_len)
a_index := make([]int, 0)
b_index := make([]int, 0)
var pat func(lps []int, s_l int, pattern string)
pat = func(lps []int, s_l int, pattern string) {
l := 0
lps[0] = 0
i := 1
for i < s_l {
if pattern[i] == pattern[l] {
l++
lps[i] = l
i++
} else {
if l != 0 {
l = lps[l-1]
} else {
lps[i] = l
i++
}
}
}
}
pat(lps_a, a_len, a)
pat(lps_b, b_len, b)
var kmp func(pat string, pat_l int, lps []int, index *[]int)
kmp = func(pat string, pat_l int, lps []int, index *[]int) {
i := 0
j := 0
for s_len-i >= pat_l-j {
if s[i] == pat[j] {
i++
j++
}
if j == pat_l {
*index = append(*index, i-pat_l)
j = lps[j-1]
} else if s[i] != pat[j] {
if j != 0 {
j = lps[j-1]
} else {
i++
}
}
}
}
kmp(a, a_len, lps_a, &a_index)
kmp(b, b_len, lps_b, &b_index)
// fmt.Println(a_index, b_index)
i := 0
j := 0
for i < len(a_index) && j < len(b_index) {
if a_index[i]+k >= b_index[j] && a_index[i]-k <= b_index[j] {
final = append(final, a_index[i])
i++
} else if a_index[i]-k > b_index[j] {
j++
} else {
i++
}
}
return final
}
|
3,008
|
Find Beautiful Indices in the Given Array II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Java
|
public class Solution {
public void computeLPS(String pattern, int[] lps) {
int M = pattern.length();
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
public List<Integer> KMP_codestorywithMIK(String pat, String txt) {
int N = txt.length();
int M = pat.length();
List<Integer> result = new ArrayList<>();
int[] lps = new int[M];
computeLPS(pat, lps);
int i = 0; // Index for text
int j = 0; // Index for pattern
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
i++;
j++;
}
if (j == M) {
result.add(i - j); // Pattern found at index i-j+1 (If you have to return 1 Based
// indexing, that's why added + 1)
j = lps[j - 1];
} else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return result;
}
private int lowerBound(List<Integer> list, int target) {
int left = 0, right = list.size() - 1, result = list.size();
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) >= target) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
public List<Integer> beautifulIndices(String s, String a, String b, int k) {
int n = s.length();
List<Integer> i_indices = KMP_codestorywithMIK(a, s);
List<Integer> j_indices = KMP_codestorywithMIK(b, s);
List<Integer> result = new ArrayList<>();
for (int i : i_indices) {
int left_limit = Math.max(0, i - k); // To avoid out of bound -> I used max(0, i-k)
int right_limit
= Math.min(n - 1, i + k); // To avoid out of bound -> I used min(n-1, i+k)
int lowerBoundIndex = lowerBound(j_indices, left_limit);
if (lowerBoundIndex < j_indices.size()
&& j_indices.get(lowerBoundIndex) <= right_limit) {
result.add(i);
}
}
return result;
}
}
|
3,008
|
Find Beautiful Indices in the Given Array II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, a string <code>a</code>, a string <code>b</code>, and an integer <code>k</code>.</p>
<p>An index <code>i</code> is <strong>beautiful</strong> if:</p>
<ul>
<li><code>0 <= i <= s.length - a.length</code></li>
<li><code>s[i..(i + a.length - 1)] == a</code></li>
<li>There exists an index <code>j</code> such that:
<ul>
<li><code>0 <= j <= s.length - b.length</code></li>
<li><code>s[j..(j + b.length - 1)] == b</code></li>
<li><code>|j - i| <= k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the array that contains beautiful indices in <strong>sorted order from smallest to largest</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
<strong>Output:</strong> [16,33]
<strong>Explanation:</strong> There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd", a = "a", b = "a", k = 4
<strong>Output:</strong> [0]
<strong>Explanation:</strong> There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>1 <= a.length, b.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code>, <code>a</code>, and <code>b</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Binary Search; String Matching; Hash Function; Rolling Hash
|
Python
|
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
def build_prefix_function(pattern):
prefix_function = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[i] != pattern[j]:
j = prefix_function[j - 1]
if pattern[i] == pattern[j]:
j += 1
prefix_function[i] = j
return prefix_function
def kmp_search(pattern, text, prefix_function):
occurrences = []
j = 0
for i in range(len(text)):
while j > 0 and text[i] != pattern[j]:
j = prefix_function[j - 1]
if text[i] == pattern[j]:
j += 1
if j == len(pattern):
occurrences.append(i - j + 1)
j = prefix_function[j - 1]
return occurrences
prefix_a = build_prefix_function(a)
prefix_b = build_prefix_function(b)
resa = kmp_search(a, s, prefix_a)
resb = kmp_search(b, s, prefix_b)
res = []
print(resa, resb)
i = 0
j = 0
while i < len(resa):
while j < len(resb):
if abs(resb[j] - resa[i]) <= k:
res.append(resa[i])
break
elif j + 1 < len(resb) and abs(resb[j + 1] - resa[i]) < abs(
resb[j] - resa[i]
):
j += 1
else:
break
i += 1
return res
|
3,009
|
Maximum Number of Intersections on the Chart
|
Hard
|
<p>There is a line chart consisting of <code>n</code> points connected by line segments. You are given a <strong>1-indexed</strong> integer array <code>y</code>. The <code>k<sup>th</sup></code> point has coordinates <code>(k, y[k])</code>. There are no horizontal lines; that is, no two consecutive points have the same y-coordinate.</p>
<p>We can draw an infinitely long horizontal line. Return <em>the <strong>maximum</strong> number of points of intersection of the line with the chart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3009.Maximum%20Number%20of%20Intersections%20on%20the%20Chart/images/20231208-020549.jpeg" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; height: 217px; width: 600px;" /></strong>
<pre>
<strong>Input:</strong> y = [1,2,1,2,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> As you can see in the image above, the line y = 1.5 has 5 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 4 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 5 points. So the answer would be 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3009.Maximum%20Number%20of%20Intersections%20on%20the%20Chart/images/20231208-020557.jpeg" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 404px;" /></strong>
<pre>
<strong>Input:</strong> y = [2,1,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> As you can see in the image above, the line y = 1.5 has 2 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 2 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 2 points. So the answer would be 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= y.length <= 10<sup>5</sup></code></li>
<li><code>1 <= y[i] <= 10<sup>9</sup></code></li>
<li><code>y[i] != y[i + 1]</code> for <code>i</code> in range <code>[1, n - 1]</code></li>
</ul>
|
Binary Indexed Tree; Geometry; Array; Math
|
Java
|
class Solution {
public int maxIntersectionCount(int[] y) {
final int n = y.length;
int ans = 0;
int intersectionCount = 0;
TreeMap<Integer, Integer> line = new TreeMap<>();
for (int i = 1; i < n; ++i) {
final int start = 2 * y[i - 1];
final int end = 2 * y[i] + (i == n - 1 ? 0 : y[i] > y[i - 1] ? -1 : 1);
line.merge(Math.min(start, end), 1, Integer::sum);
line.merge(Math.max(start, end) + 1, -1, Integer::sum);
}
for (final int count : line.values()) {
intersectionCount += count;
ans = Math.max(ans, intersectionCount);
}
return ans;
}
}
|
3,010
|
Divide an Array Into Subarrays With Minimum Cost I
|
Easy
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code>.</p>
<p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p>
<p>You need to divide <code>nums</code> into <code>3</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible <strong>sum</strong> of the cost of these subarrays</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,12]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6.
The other possible ways to form 3 subarrays are:
- [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15.
- [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12.
It can be shown that 12 is the minimum cost achievable.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,3,1,1]
<strong>Output:</strong> 12
<strong>Explanation:</strong> The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12.
It can be shown that 12 is the minimum cost achievable.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Enumeration; Sorting
|
C++
|
class Solution {
public:
int minimumCost(vector<int>& nums) {
int a = nums[0], b = 100, c = 100;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] < b) {
c = b;
b = nums[i];
} else if (nums[i] < c) {
c = nums[i];
}
}
return a + b + c;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.