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
|
|---|---|---|---|---|---|---|
3,300
|
Minimum Element After Replacement With Digit Sum
|
Easy
|
<p>You are given an integer array <code>nums</code>.</p>
<p>You replace each element in <code>nums</code> with the <strong>sum</strong> of its digits.</p>
<p>Return the <strong>minimum</strong> element in <code>nums</code> after all replacements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,12,13,14]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 3, 4, 5]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 2, 3, 4]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [999,19,199]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[27, 10, 19]</code> after all replacements, with minimum element 10.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
int minElement(vector<int>& nums) {
int ans = 100;
for (int x : nums) {
int y = 0;
for (; x > 0; x /= 10) {
y += x % 10;
}
ans = min(ans, y);
}
return ans;
}
};
|
3,300
|
Minimum Element After Replacement With Digit Sum
|
Easy
|
<p>You are given an integer array <code>nums</code>.</p>
<p>You replace each element in <code>nums</code> with the <strong>sum</strong> of its digits.</p>
<p>Return the <strong>minimum</strong> element in <code>nums</code> after all replacements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,12,13,14]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 3, 4, 5]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 2, 3, 4]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [999,19,199]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[27, 10, 19]</code> after all replacements, with minimum element 10.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Go
|
func minElement(nums []int) int {
ans := 100
for _, x := range nums {
y := 0
for ; x > 0; x /= 10 {
y += x % 10
}
ans = min(ans, y)
}
return ans
}
|
3,300
|
Minimum Element After Replacement With Digit Sum
|
Easy
|
<p>You are given an integer array <code>nums</code>.</p>
<p>You replace each element in <code>nums</code> with the <strong>sum</strong> of its digits.</p>
<p>Return the <strong>minimum</strong> element in <code>nums</code> after all replacements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,12,13,14]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 3, 4, 5]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 2, 3, 4]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [999,19,199]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[27, 10, 19]</code> after all replacements, with minimum element 10.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int minElement(int[] nums) {
int ans = 100;
for (int x : nums) {
int y = 0;
for (; x > 0; x /= 10) {
y += x % 10;
}
ans = Math.min(ans, y);
}
return ans;
}
}
|
3,300
|
Minimum Element After Replacement With Digit Sum
|
Easy
|
<p>You are given an integer array <code>nums</code>.</p>
<p>You replace each element in <code>nums</code> with the <strong>sum</strong> of its digits.</p>
<p>Return the <strong>minimum</strong> element in <code>nums</code> after all replacements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,12,13,14]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 3, 4, 5]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 2, 3, 4]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [999,19,199]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[27, 10, 19]</code> after all replacements, with minimum element 10.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def minElement(self, nums: List[int]) -> int:
return min(sum(int(b) for b in str(x)) for x in nums)
|
3,300
|
Minimum Element After Replacement With Digit Sum
|
Easy
|
<p>You are given an integer array <code>nums</code>.</p>
<p>You replace each element in <code>nums</code> with the <strong>sum</strong> of its digits.</p>
<p>Return the <strong>minimum</strong> element in <code>nums</code> after all replacements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,12,13,14]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 3, 4, 5]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[1, 2, 3, 4]</code> after all replacements, with minimum element 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [999,19,199]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> becomes <code>[27, 10, 19]</code> after all replacements, with minimum element 10.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Math
|
TypeScript
|
function minElement(nums: number[]): number {
let ans: number = 100;
for (let x of nums) {
let y = 0;
for (; x; x = Math.floor(x / 10)) {
y += x % 10;
}
ans = Math.min(ans, y);
}
return ans;
}
|
3,301
|
Maximize the Total Height of Unique Towers
|
Medium
|
<p>You are given an array <code>maximumHeight</code>, where <code>maximumHeight[i]</code> denotes the <strong>maximum</strong> height the <code>i<sup>th</sup></code> tower can be assigned.</p>
<p>Your task is to assign a height to each tower so that:</p>
<ol>
<li>The height of the <code>i<sup>th</sup></code> tower is a positive integer and does not exceed <code>maximumHeight[i]</code>.</li>
<li>No two towers have the same height.</li>
</ol>
<p>Return the <strong>maximum</strong> possible total sum of the tower heights. If it's not possible to assign heights, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,3,4,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[1, 2, 4, 3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [15,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[15, 10]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to assign positive heights to each index so that no two towers have the same height.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maximumHeight.length <= 10<sup>5</sup></code></li>
<li><code>1 <= maximumHeight[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
long long maximumTotalSum(vector<int>& maximumHeight) {
ranges::sort(maximumHeight, greater<int>());
long long ans = 0;
int mx = 1 << 30;
for (int x : maximumHeight) {
x = min(x, mx - 1);
if (x <= 0) {
return -1;
}
ans += x;
mx = x;
}
return ans;
}
};
|
3,301
|
Maximize the Total Height of Unique Towers
|
Medium
|
<p>You are given an array <code>maximumHeight</code>, where <code>maximumHeight[i]</code> denotes the <strong>maximum</strong> height the <code>i<sup>th</sup></code> tower can be assigned.</p>
<p>Your task is to assign a height to each tower so that:</p>
<ol>
<li>The height of the <code>i<sup>th</sup></code> tower is a positive integer and does not exceed <code>maximumHeight[i]</code>.</li>
<li>No two towers have the same height.</li>
</ol>
<p>Return the <strong>maximum</strong> possible total sum of the tower heights. If it's not possible to assign heights, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,3,4,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[1, 2, 4, 3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [15,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[15, 10]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to assign positive heights to each index so that no two towers have the same height.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maximumHeight.length <= 10<sup>5</sup></code></li>
<li><code>1 <= maximumHeight[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func maximumTotalSum(maximumHeight []int) int64 {
slices.SortFunc(maximumHeight, func(a, b int) int { return b - a })
ans := int64(0)
mx := 1 << 30
for _, x := range maximumHeight {
x = min(x, mx-1)
if x <= 0 {
return -1
}
ans += int64(x)
mx = x
}
return ans
}
|
3,301
|
Maximize the Total Height of Unique Towers
|
Medium
|
<p>You are given an array <code>maximumHeight</code>, where <code>maximumHeight[i]</code> denotes the <strong>maximum</strong> height the <code>i<sup>th</sup></code> tower can be assigned.</p>
<p>Your task is to assign a height to each tower so that:</p>
<ol>
<li>The height of the <code>i<sup>th</sup></code> tower is a positive integer and does not exceed <code>maximumHeight[i]</code>.</li>
<li>No two towers have the same height.</li>
</ol>
<p>Return the <strong>maximum</strong> possible total sum of the tower heights. If it's not possible to assign heights, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,3,4,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[1, 2, 4, 3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [15,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[15, 10]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to assign positive heights to each index so that no two towers have the same height.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maximumHeight.length <= 10<sup>5</sup></code></li>
<li><code>1 <= maximumHeight[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public long maximumTotalSum(int[] maximumHeight) {
long ans = 0;
int mx = 1 << 30;
Arrays.sort(maximumHeight);
for (int i = maximumHeight.length - 1; i >= 0; --i) {
int x = Math.min(maximumHeight[i], mx - 1);
if (x <= 0) {
return -1;
}
ans += x;
mx = x;
}
return ans;
}
}
|
3,301
|
Maximize the Total Height of Unique Towers
|
Medium
|
<p>You are given an array <code>maximumHeight</code>, where <code>maximumHeight[i]</code> denotes the <strong>maximum</strong> height the <code>i<sup>th</sup></code> tower can be assigned.</p>
<p>Your task is to assign a height to each tower so that:</p>
<ol>
<li>The height of the <code>i<sup>th</sup></code> tower is a positive integer and does not exceed <code>maximumHeight[i]</code>.</li>
<li>No two towers have the same height.</li>
</ol>
<p>Return the <strong>maximum</strong> possible total sum of the tower heights. If it's not possible to assign heights, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,3,4,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[1, 2, 4, 3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [15,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[15, 10]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to assign positive heights to each index so that no two towers have the same height.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maximumHeight.length <= 10<sup>5</sup></code></li>
<li><code>1 <= maximumHeight[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def maximumTotalSum(self, maximumHeight: List[int]) -> int:
maximumHeight.sort()
ans, mx = 0, inf
for x in maximumHeight[::-1]:
x = min(x, mx - 1)
if x <= 0:
return -1
ans += x
mx = x
return ans
|
3,301
|
Maximize the Total Height of Unique Towers
|
Medium
|
<p>You are given an array <code>maximumHeight</code>, where <code>maximumHeight[i]</code> denotes the <strong>maximum</strong> height the <code>i<sup>th</sup></code> tower can be assigned.</p>
<p>Your task is to assign a height to each tower so that:</p>
<ol>
<li>The height of the <code>i<sup>th</sup></code> tower is a positive integer and does not exceed <code>maximumHeight[i]</code>.</li>
<li>No two towers have the same height.</li>
</ol>
<p>Return the <strong>maximum</strong> possible total sum of the tower heights. If it's not possible to assign heights, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,3,4,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[1, 2, 4, 3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [15,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>We can assign heights in the following way: <code>[15, 10]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> maximumHeight<span class="example-io"> = [2,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to assign positive heights to each index so that no two towers have the same height.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maximumHeight.length <= 10<sup>5</sup></code></li>
<li><code>1 <= maximumHeight[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function maximumTotalSum(maximumHeight: number[]): number {
maximumHeight.sort((a, b) => a - b).reverse();
let ans: number = 0;
let mx: number = Infinity;
for (let x of maximumHeight) {
x = Math.min(x, mx - 1);
if (x <= 0) {
return -1;
}
ans += x;
mx = x;
}
return ans;
}
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
C++
|
class Solution {
public:
char kthCharacter(int k) {
vector<int> word;
word.push_back(0);
while (word.size() < k) {
int m = word.size();
for (int i = 0; i < m; ++i) {
word.push_back((word[i] + 1) % 26);
}
}
return 'a' + word[k - 1];
}
};
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
Go
|
func kthCharacter(k int) byte {
word := []int{0}
for len(word) < k {
m := len(word)
for i := 0; i < m; i++ {
word = append(word, (word[i]+1)%26)
}
}
return 'a' + byte(word[k-1])
}
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
Java
|
class Solution {
public char kthCharacter(int k) {
List<Integer> word = new ArrayList<>();
word.add(0);
while (word.size() < k) {
for (int i = 0, m = word.size(); i < m; ++i) {
word.add((word.get(i) + 1) % 26);
}
}
return (char) ('a' + word.get(k - 1));
}
}
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
Python
|
class Solution:
def kthCharacter(self, k: int) -> str:
word = [0]
while len(word) < k:
word.extend([(x + 1) % 26 for x in word])
return chr(ord("a") + word[k - 1])
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
Rust
|
impl Solution {
pub fn kth_character(k: i32) -> char {
let mut word = vec![0];
while word.len() < k as usize {
let m = word.len();
for i in 0..m {
word.push((word[i] + 1) % 26);
}
}
(b'a' + word[(k - 1) as usize] as u8) as char
}
}
|
3,304
|
Find the K-th Character in String Game I
|
Easy
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>.</p>
<p>Now Bob will ask Alice to perform the following operation <strong>forever</strong>:</p>
<ul>
<li>Generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>.</li>
</ul>
<p>For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</p>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code>, after enough operations have been done for <code>word</code> to have <strong>at least</strong> <code>k</code> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word = "a"</code>. We need to do the operation three times:</p>
<ul>
<li>Generated string is <code>"b"</code>, <code>word</code> becomes <code>"ab"</code>.</li>
<li>Generated string is <code>"bc"</code>, <code>word</code> becomes <code>"abbc"</code>.</li>
<li>Generated string is <code>"bccd"</code>, <code>word</code> becomes <code>"abbcbccd"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">"c"</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 500</code></li>
</ul>
|
Bit Manipulation; Recursion; Math; Simulation
|
TypeScript
|
function kthCharacter(k: number): string {
const word: number[] = [0];
while (word.length < k) {
word.push(...word.map(x => (x + 1) % 26));
}
return String.fromCharCode(97 + word[k - 1]);
}
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
C++
|
class Solution {
public:
int countOfSubstrings(string word, int k) {
auto f = [&](int k) -> int {
int ans = 0;
int l = 0, x = 0;
unordered_map<char, int> cnt;
auto vowel = [&](char c) -> bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
for (char c : word) {
if (vowel(c)) {
cnt[c]++;
} else {
++x;
}
while (x >= k && cnt.size() == 5) {
char d = word[l++];
if (vowel(d)) {
if (--cnt[d] == 0) {
cnt.erase(d);
}
} else {
--x;
}
}
ans += l;
}
return ans;
};
return f(k) - f(k + 1);
}
};
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Go
|
func countOfSubstrings(word string, k int) int {
f := func(k int) int {
var ans int = 0
l, x := 0, 0
cnt := make(map[rune]int)
vowel := func(c rune) bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
}
for _, c := range word {
if vowel(c) {
cnt[c]++
} else {
x++
}
for x >= k && len(cnt) == 5 {
d := rune(word[l])
l++
if vowel(d) {
cnt[d]--
if cnt[d] == 0 {
delete(cnt, d)
}
} else {
x--
}
}
ans += l
}
return ans
}
return f(k) - f(k+1)
}
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Java
|
class Solution {
public int countOfSubstrings(String word, int k) {
return f(word, k) - f(word, k + 1);
}
private int f(String word, int k) {
int ans = 0;
int l = 0, x = 0;
Map<Character, Integer> cnt = new HashMap<>(5);
for (char c : word.toCharArray()) {
if (vowel(c)) {
cnt.merge(c, 1, Integer::sum);
} else {
++x;
}
while (x >= k && cnt.size() == 5) {
char d = word.charAt(l++);
if (vowel(d)) {
if (cnt.merge(d, -1, Integer::sum) == 0) {
cnt.remove(d);
}
} else {
--x;
}
}
ans += l;
}
return ans;
}
private boolean vowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Python
|
class Solution:
def countOfSubstrings(self, word: str, k: int) -> int:
def f(k: int) -> int:
cnt = Counter()
ans = l = x = 0
for c in word:
if c in "aeiou":
cnt[c] += 1
else:
x += 1
while x >= k and len(cnt) == 5:
d = word[l]
if d in "aeiou":
cnt[d] -= 1
if cnt[d] == 0:
cnt.pop(d)
else:
x -= 1
l += 1
ans += l
return ans
return f(k) - f(k + 1)
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Rust
|
impl Solution {
pub fn count_of_substrings(word: String, k: i32) -> i32 {
fn f(word: &Vec<char>, k: i32) -> i32 {
let mut ans = 0;
let mut l = 0;
let mut x = 0;
let mut cnt = std::collections::HashMap::new();
let is_vowel = |c: char| matches!(c, 'a' | 'e' | 'i' | 'o' | 'u');
for (r, &c) in word.iter().enumerate() {
if is_vowel(c) {
*cnt.entry(c).or_insert(0) += 1;
} else {
x += 1;
}
while x >= k && cnt.len() == 5 {
let d = word[l];
l += 1;
if is_vowel(d) {
let count = cnt.entry(d).or_insert(0);
*count -= 1;
if *count == 0 {
cnt.remove(&d);
}
} else {
x -= 1;
}
}
ans += l as i32;
}
ans
}
let chars: Vec<char> = word.chars().collect();
f(&chars, k) - f(&chars, k + 1)
}
}
|
3,305
|
Count of Substrings Containing Every Vowel and K Consonants I
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 250</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
TypeScript
|
function countOfSubstrings(word: string, k: number): number {
const f = (k: number): number => {
let ans = 0;
let l = 0,
x = 0;
const cnt = new Map<string, number>();
const vowel = (c: string): boolean => {
return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u';
};
for (const c of word) {
if (vowel(c)) {
cnt.set(c, (cnt.get(c) || 0) + 1);
} else {
x++;
}
while (x >= k && cnt.size === 5) {
const d = word[l++];
if (vowel(d)) {
cnt.set(d, cnt.get(d)! - 1);
if (cnt.get(d) === 0) {
cnt.delete(d);
}
} else {
x--;
}
}
ans += l;
}
return ans;
};
return f(k) - f(k + 1);
}
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
C++
|
class Solution {
public:
long long countOfSubstrings(string word, int k) {
auto f = [&](int k) -> long long {
long long ans = 0;
int l = 0, x = 0;
unordered_map<char, int> cnt;
auto vowel = [&](char c) -> bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
for (char c : word) {
if (vowel(c)) {
cnt[c]++;
} else {
++x;
}
while (x >= k && cnt.size() == 5) {
char d = word[l++];
if (vowel(d)) {
if (--cnt[d] == 0) {
cnt.erase(d);
}
} else {
--x;
}
}
ans += l;
}
return ans;
};
return f(k) - f(k + 1);
}
};
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Go
|
func countOfSubstrings(word string, k int) int64 {
f := func(k int) int64 {
var ans int64 = 0
l, x := 0, 0
cnt := make(map[rune]int)
vowel := func(c rune) bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
}
for _, c := range word {
if vowel(c) {
cnt[c]++
} else {
x++
}
for x >= k && len(cnt) == 5 {
d := rune(word[l])
l++
if vowel(d) {
cnt[d]--
if cnt[d] == 0 {
delete(cnt, d)
}
} else {
x--
}
}
ans += int64(l)
}
return ans
}
return f(k) - f(k+1)
}
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Java
|
class Solution {
public long countOfSubstrings(String word, int k) {
return f(word, k) - f(word, k + 1);
}
private long f(String word, int k) {
long ans = 0;
int l = 0, x = 0;
Map<Character, Integer> cnt = new HashMap<>(5);
for (char c : word.toCharArray()) {
if (vowel(c)) {
cnt.merge(c, 1, Integer::sum);
} else {
++x;
}
while (x >= k && cnt.size() == 5) {
char d = word.charAt(l++);
if (vowel(d)) {
if (cnt.merge(d, -1, Integer::sum) == 0) {
cnt.remove(d);
}
} else {
--x;
}
}
ans += l;
}
return ans;
}
private boolean vowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Python
|
class Solution:
def countOfSubstrings(self, word: str, k: int) -> int:
def f(k: int) -> int:
cnt = Counter()
ans = l = x = 0
for c in word:
if c in "aeiou":
cnt[c] += 1
else:
x += 1
while x >= k and len(cnt) == 5:
d = word[l]
if d in "aeiou":
cnt[d] -= 1
if cnt[d] == 0:
cnt.pop(d)
else:
x -= 1
l += 1
ans += l
return ans
return f(k) - f(k + 1)
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
Rust
|
impl Solution {
pub fn count_of_substrings(word: String, k: i32) -> i64 {
fn f(word: &Vec<char>, k: i32) -> i64 {
let mut ans = 0_i64;
let mut l = 0;
let mut x = 0;
let mut cnt = std::collections::HashMap::new();
let is_vowel = |c: char| matches!(c, 'a' | 'e' | 'i' | 'o' | 'u');
for (r, &c) in word.iter().enumerate() {
if is_vowel(c) {
*cnt.entry(c).or_insert(0) += 1;
} else {
x += 1;
}
while x >= k && cnt.len() == 5 {
let d = word[l];
l += 1;
if is_vowel(d) {
let count = cnt.entry(d).or_insert(0);
*count -= 1;
if *count == 0 {
cnt.remove(&d);
}
} else {
x -= 1;
}
}
ans += l as i64;
}
ans
}
let chars: Vec<char> = word.chars().collect();
f(&chars, k) - f(&chars, k + 1)
}
}
|
3,306
|
Count of Substrings Containing Every Vowel and K Consonants II
|
Medium
|
<p>You are given a string <code>word</code> and a <strong>non-negative</strong> integer <code>k</code>.</p>
<p>Return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>word</code> that contain every vowel (<code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>) <strong>at least</strong> once and <strong>exactly</strong> <code>k</code> consonants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeioqq", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring with every vowel.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "aeiou", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring with every vowel and zero consonants is <code>word[0..4]</code>, which is <code>"aeiou"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "</span>ieaouqqieaouqq<span class="example-io">", k = 1</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>The substrings with every vowel and one consonant are:</p>
<ul>
<li><code>word[0..5]</code>, which is <code>"ieaouq"</code>.</li>
<li><code>word[6..11]</code>, which is <code>"qieaou"</code>.</li>
<li><code>word[7..12]</code>, which is <code>"ieaouq"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>5 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>0 <= k <= word.length - 5</code></li>
</ul>
|
Hash Table; String; Sliding Window
|
TypeScript
|
function countOfSubstrings(word: string, k: number): number {
const f = (k: number): number => {
let ans = 0;
let l = 0,
x = 0;
const cnt = new Map<string, number>();
const vowel = (c: string): boolean => {
return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u';
};
for (const c of word) {
if (vowel(c)) {
cnt.set(c, (cnt.get(c) || 0) + 1);
} else {
x++;
}
while (x >= k && cnt.size === 5) {
const d = word[l++];
if (vowel(d)) {
cnt.set(d, cnt.get(d)! - 1);
if (cnt.get(d) === 0) {
cnt.delete(d);
}
} else {
x--;
}
}
ans += l;
}
return ans;
};
return f(k) - f(k + 1);
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
C++
|
class Solution {
public:
char kthCharacter(long long k, vector<int>& operations) {
long long n = 1;
int i = 0;
while (n < k) {
n *= 2;
++i;
}
int d = 0;
while (n > 1) {
if (k > n / 2) {
k -= n / 2;
d += operations[i - 1];
}
n /= 2;
--i;
}
return 'a' + (d % 26);
}
};
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
C#
|
public class Solution {
public char KthCharacter(long k, int[] operations) {
long n = 1;
int i = 0;
while (n < k) {
n *= 2;
++i;
}
int d = 0;
while (n > 1) {
if (k > n / 2) {
k -= n / 2;
d += operations[i - 1];
}
n /= 2;
--i;
}
return (char)('a' + (d % 26));
}
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
Go
|
func kthCharacter(k int64, operations []int) byte {
n := int64(1)
i := 0
for n < k {
n *= 2
i++
}
d := 0
for n > 1 {
if k > n/2 {
k -= n / 2
d += operations[i-1]
}
n /= 2
i--
}
return byte('a' + (d % 26))
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
Java
|
class Solution {
public char kthCharacter(long k, int[] operations) {
long n = 1;
int i = 0;
while (n < k) {
n *= 2;
++i;
}
int d = 0;
while (n > 1) {
if (k > n / 2) {
k -= n / 2;
d += operations[i - 1];
}
n /= 2;
--i;
}
return (char) ('a' + (d % 26));
}
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
PHP
|
class Solution {
/**
* @param Integer $k
* @param Integer[] $operations
* @return String
*/
function kthCharacter($k, $operations) {
$n = 1;
$i = 0;
while ($n < $k) {
$n *= 2;
++$i;
}
$d = 0;
while ($n > 1) {
if ($k > $n / 2) {
$k -= $n / 2;
$d += $operations[$i - 1];
}
$n /= 2;
--$i;
}
return chr(ord('a') + ($d % 26));
}
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
Python
|
class Solution:
def kthCharacter(self, k: int, operations: List[int]) -> str:
n, i = 1, 0
while n < k:
n *= 2
i += 1
d = 0
while n > 1:
if k > n // 2:
k -= n // 2
d += operations[i - 1]
n //= 2
i -= 1
return chr(d % 26 + ord("a"))
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
Rust
|
impl Solution {
pub fn kth_character(mut k: i64, operations: Vec<i32>) -> char {
let mut n = 1i64;
let mut i = 0;
while n < k {
n *= 2;
i += 1;
}
let mut d = 0;
while n > 1 {
if k > n / 2 {
k -= n / 2;
d += operations[i - 1] as i64;
}
n /= 2;
i -= 1;
}
((b'a' + (d % 26) as u8) as char)
}
}
|
3,307
|
Find the K-th Character in String Game II
|
Hard
|
<p>Alice and Bob are playing a game. Initially, Alice has a string <code>word = "a"</code>.</p>
<p>You are given a <strong>positive</strong> integer <code>k</code>. You are also given an integer array <code>operations</code>, where <code>operations[i]</code> represents the <strong>type</strong> of the <code>i<sup>th</sup></code> operation.</p>
<p>Now Bob will ask Alice to perform <strong>all</strong> operations in sequence:</p>
<ul>
<li>If <code>operations[i] == 0</code>, <strong>append</strong> a copy of <code>word</code> to itself.</li>
<li>If <code>operations[i] == 1</code>, generate a new string by <strong>changing</strong> each character in <code>word</code> to its <strong>next</strong> character in the English alphabet, and <strong>append</strong> it to the <em>original</em> <code>word</code>. For example, performing the operation on <code>"c"</code> generates <code>"cd"</code> and performing the operation on <code>"zb"</code> generates <code>"zbac"</code>.</li>
</ul>
<p>Return the value of the <code>k<sup>th</sup></code> character in <code>word</code> after performing all the operations.</p>
<p><strong>Note</strong> that the character <code>'z'</code> can be changed to <code>'a'</code> in the second type of operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 5, operations = [0,0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">"a"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the three operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"aa"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aaaa"</code>.</li>
<li>Appends <code>"aaaa"</code> to <code>"aaaa"</code>, <code>word</code> becomes <code>"aaaaaaaa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 10, operations = [0,1,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">"b"</span></p>
<p><strong>Explanation:</strong></p>
<p>Initially, <code>word == "a"</code>. Alice performs the four operations as follows:</p>
<ul>
<li>Appends <code>"a"</code> to <code>"a"</code>, <code>word</code> becomes <code>"aa"</code>.</li>
<li>Appends <code>"bb"</code> to <code>"aa"</code>, <code>word</code> becomes <code>"aabb"</code>.</li>
<li>Appends <code>"aabb"</code> to <code>"aabb"</code>, <code>word</code> becomes <code>"aabbaabb"</code>.</li>
<li>Appends <code>"bbccbbcc"</code> to <code>"aabbaabb"</code>, <code>word</code> becomes <code>"aabbaabbbbccbbcc"</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>14</sup></code></li>
<li><code>1 <= operations.length <= 100</code></li>
<li><code>operations[i]</code> is either 0 or 1.</li>
<li>The input is generated such that <code>word</code> has <strong>at least</strong> <code>k</code> characters after all operations.</li>
</ul>
|
Bit Manipulation; Recursion; Math
|
TypeScript
|
function kthCharacter(k: number, operations: number[]): string {
let n = 1;
let i = 0;
while (n < k) {
n *= 2;
i++;
}
let d = 0;
while (n > 1) {
if (k > n / 2) {
k -= n / 2;
d += operations[i - 1];
}
n /= 2;
i--;
}
return String.fromCharCode('a'.charCodeAt(0) + (d % 26));
}
|
3,308
|
Find Top Performing Driver
|
Medium
|
<p>Table: <font face="monospace"><code>Drivers</code></font></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| driver_id | int |
| name | varchar |
| age | int |
| experience | int |
| accidents | int |
+--------------+---------+
(driver_id) is the unique key for this table.
Each row includes a driver's ID, their name, age, years of driving experience, and the number of accidents they’ve had.
</pre>
<p>Table: <font face="monospace"><code>Vehicles</code></font></p>
<pre>
+--------------+---------+
| vehicle_id | int |
| driver_id | int |
| model | varchar |
| fuel_type | varchar |
| mileage | int |
+--------------+---------+
(vehicle_id, driver_id, fuel_type) is the unique key for this table.
Each row includes the vehicle's ID, the driver who operates it, the model, fuel type, and mileage.
</pre>
<p>Table: <font face="monospace"><code>Trips</code></font></p>
<pre>
+--------------+---------+
| trip_id | int |
| vehicle_id | int |
| distance | int |
| duration | int |
| rating | int |
+--------------+---------+
(trip_id) is the unique key for this table.
Each row includes a trip's ID, the vehicle used, the distance covered (in miles), the trip duration (in minutes), and the passenger's rating (1-5).
</pre>
<p>Uber is analyzing drivers based on their trips. Write a solution to find the <strong>top-performing driver</strong> for <strong>each fuel type</strong> based on the following criteria:</p>
<ol>
<li>A driver's performance is calculated as the <strong>average rating</strong> across all their trips. Average rating should be rounded to <code>2</code> decimal places.</li>
<li>If two drivers have the same average rating, the driver with the <strong>longer total distance</strong> traveled should be ranked higher.</li>
<li>If there is <strong>still a tie</strong>, choose the driver with the <strong>fewest accidents</strong>.</li>
</ol>
<p>Return <em>the result table ordered by</em> <code>fuel_type</code> <em>in </em><strong>ascending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>Drivers</code> table:</p>
<pre class="example-io">
+-----------+----------+-----+------------+-----------+
| driver_id | name | age | experience | accidents |
+-----------+----------+-----+------------+-----------+
| 1 | Alice | 34 | 10 | 1 |
| 2 | Bob | 45 | 20 | 3 |
| 3 | Charlie | 28 | 5 | 0 |
+-----------+----------+-----+------------+-----------+
</pre>
<p><code>Vehicles</code> table:</p>
<pre class="example-io">
+------------+-----------+---------+-----------+---------+
| vehicle_id | driver_id | model | fuel_type | mileage |
+------------+-----------+---------+-----------+---------+
| 100 | 1 | Sedan | Gasoline | 20000 |
| 101 | 2 | SUV | Electric | 30000 |
| 102 | 3 | Coupe | Gasoline | 15000 |
+------------+-----------+---------+-----------+---------+
</pre>
<p><code>Trips</code> table:</p>
<pre class="example-io">
+---------+------------+----------+----------+--------+
| trip_id | vehicle_id | distance | duration | rating |
+---------+------------+----------+----------+--------+
| 201 | 100 | 50 | 30 | 5 |
| 202 | 100 | 30 | 20 | 4 |
| 203 | 101 | 100 | 60 | 4 |
| 204 | 101 | 80 | 50 | 5 |
| 205 | 102 | 40 | 30 | 5 |
| 206 | 102 | 60 | 40 | 5 |
+---------+------------+----------+----------+--------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-----------+--------+----------+
| fuel_type | driver_id | rating | distance |
+-----------+-----------+--------+----------+
| Electric | 2 | 4.50 | 180 |
| Gasoline | 3 | 5.00 | 100 |
+-----------+-----------+--------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For fuel type <code>Gasoline</code>, both Alice (Driver 1) and Charlie (Driver 3) have trips. Charlie has an average rating of 5.0, while Alice has 4.5. Therefore, Charlie is selected.</li>
<li>For fuel type <code>Electric</code>, Bob (Driver 2) is the only driver with an average rating of 4.5, so he is selected.</li>
</ul>
<p>The output table is ordered by <code>fuel_type</code> in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
fuel_type,
driver_id,
ROUND(AVG(rating), 2) rating,
SUM(distance) distance,
SUM(accidents) accidents
FROM
Drivers
JOIN Vehicles USING (driver_id)
JOIN Trips USING (vehicle_id)
GROUP BY fuel_type, driver_id
),
P AS (
SELECT
*,
RANK() OVER (
PARTITION BY fuel_type
ORDER BY rating DESC, distance DESC, accidents
) rk
FROM T
)
SELECT fuel_type, driver_id, rating, distance
FROM P
WHERE rk = 1
ORDER BY 1;
|
3,309
|
Maximum Possible Number by Binary Concatenation
|
Medium
|
<p>You are given an array of integers <code>nums</code> of size 3.</p>
<p>Return the <strong>maximum</strong> possible number whose <em>binary representation</em> can be formed by <strong>concatenating</strong> the <em>binary representation</em> of <strong>all</strong> elements in <code>nums</code> in some order.</p>
<p><strong>Note</strong> that the binary representation of any number <em>does not</em> contain leading zeros.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> 30</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[3, 1, 2]</code> to get the result <code>"11110"</code>, which is the binary representation of 30.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,16]</span></p>
<p><strong>Output:</strong> 1296</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[2, 8, 16]</code> to get the result <code>"10100010000"</code>, which is the binary representation of 1296.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 127</code></li>
</ul>
|
Bit Manipulation; Array; Enumeration
|
C++
|
class Solution {
public:
int maxGoodNumber(vector<int>& nums) {
int ans = 0;
auto f = [&](vector<int>& nums) {
int res = 0;
vector<int> t;
for (int x : nums) {
for (; x; x >>= 1) {
t.push_back(x & 1);
}
}
while (t.size()) {
res = res * 2 + t.back();
t.pop_back();
}
return res;
};
for (int i = 0; i < 6; ++i) {
ans = max(ans, f(nums));
next_permutation(nums.begin(), nums.end());
}
return ans;
}
};
|
3,309
|
Maximum Possible Number by Binary Concatenation
|
Medium
|
<p>You are given an array of integers <code>nums</code> of size 3.</p>
<p>Return the <strong>maximum</strong> possible number whose <em>binary representation</em> can be formed by <strong>concatenating</strong> the <em>binary representation</em> of <strong>all</strong> elements in <code>nums</code> in some order.</p>
<p><strong>Note</strong> that the binary representation of any number <em>does not</em> contain leading zeros.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> 30</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[3, 1, 2]</code> to get the result <code>"11110"</code>, which is the binary representation of 30.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,16]</span></p>
<p><strong>Output:</strong> 1296</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[2, 8, 16]</code> to get the result <code>"10100010000"</code>, which is the binary representation of 1296.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 127</code></li>
</ul>
|
Bit Manipulation; Array; Enumeration
|
Go
|
func maxGoodNumber(nums []int) int {
f := func(i, j, k int) int {
a := strconv.FormatInt(int64(nums[i]), 2)
b := strconv.FormatInt(int64(nums[j]), 2)
c := strconv.FormatInt(int64(nums[k]), 2)
res, _ := strconv.ParseInt(a+b+c, 2, 64)
return int(res)
}
ans := f(0, 1, 2)
ans = max(ans, f(0, 2, 1))
ans = max(ans, f(1, 0, 2))
ans = max(ans, f(1, 2, 0))
ans = max(ans, f(2, 0, 1))
ans = max(ans, f(2, 1, 0))
return ans
}
|
3,309
|
Maximum Possible Number by Binary Concatenation
|
Medium
|
<p>You are given an array of integers <code>nums</code> of size 3.</p>
<p>Return the <strong>maximum</strong> possible number whose <em>binary representation</em> can be formed by <strong>concatenating</strong> the <em>binary representation</em> of <strong>all</strong> elements in <code>nums</code> in some order.</p>
<p><strong>Note</strong> that the binary representation of any number <em>does not</em> contain leading zeros.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> 30</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[3, 1, 2]</code> to get the result <code>"11110"</code>, which is the binary representation of 30.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,16]</span></p>
<p><strong>Output:</strong> 1296</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[2, 8, 16]</code> to get the result <code>"10100010000"</code>, which is the binary representation of 1296.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 127</code></li>
</ul>
|
Bit Manipulation; Array; Enumeration
|
Java
|
class Solution {
private int[] nums;
public int maxGoodNumber(int[] nums) {
this.nums = nums;
int ans = f(0, 1, 2);
ans = Math.max(ans, f(0, 2, 1));
ans = Math.max(ans, f(1, 0, 2));
ans = Math.max(ans, f(1, 2, 0));
ans = Math.max(ans, f(2, 0, 1));
ans = Math.max(ans, f(2, 1, 0));
return ans;
}
private int f(int i, int j, int k) {
String a = Integer.toBinaryString(nums[i]);
String b = Integer.toBinaryString(nums[j]);
String c = Integer.toBinaryString(nums[k]);
return Integer.parseInt(a + b + c, 2);
}
}
|
3,309
|
Maximum Possible Number by Binary Concatenation
|
Medium
|
<p>You are given an array of integers <code>nums</code> of size 3.</p>
<p>Return the <strong>maximum</strong> possible number whose <em>binary representation</em> can be formed by <strong>concatenating</strong> the <em>binary representation</em> of <strong>all</strong> elements in <code>nums</code> in some order.</p>
<p><strong>Note</strong> that the binary representation of any number <em>does not</em> contain leading zeros.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> 30</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[3, 1, 2]</code> to get the result <code>"11110"</code>, which is the binary representation of 30.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,16]</span></p>
<p><strong>Output:</strong> 1296</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[2, 8, 16]</code> to get the result <code>"10100010000"</code>, which is the binary representation of 1296.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 127</code></li>
</ul>
|
Bit Manipulation; Array; Enumeration
|
Python
|
class Solution:
def maxGoodNumber(self, nums: List[int]) -> int:
ans = 0
for arr in permutations(nums):
num = int("".join(bin(i)[2:] for i in arr), 2)
ans = max(ans, num)
return ans
|
3,309
|
Maximum Possible Number by Binary Concatenation
|
Medium
|
<p>You are given an array of integers <code>nums</code> of size 3.</p>
<p>Return the <strong>maximum</strong> possible number whose <em>binary representation</em> can be formed by <strong>concatenating</strong> the <em>binary representation</em> of <strong>all</strong> elements in <code>nums</code> in some order.</p>
<p><strong>Note</strong> that the binary representation of any number <em>does not</em> contain leading zeros.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> 30</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[3, 1, 2]</code> to get the result <code>"11110"</code>, which is the binary representation of 30.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,16]</span></p>
<p><strong>Output:</strong> 1296</p>
<p><strong>Explanation:</strong></p>
<p>Concatenate the numbers in the order <code>[2, 8, 16]</code> to get the result <code>"10100010000"</code>, which is the binary representation of 1296.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 127</code></li>
</ul>
|
Bit Manipulation; Array; Enumeration
|
TypeScript
|
function maxGoodNumber(nums: number[]): number {
const f = (i: number, j: number, k: number): number => {
const a = nums[i].toString(2);
const b = nums[j].toString(2);
const c = nums[k].toString(2);
const res = parseInt(a + b + c, 2);
return res;
};
let ans = f(0, 1, 2);
ans = Math.max(ans, f(0, 2, 1));
ans = Math.max(ans, f(1, 0, 2));
ans = Math.max(ans, f(1, 2, 0));
ans = Math.max(ans, f(2, 0, 1));
ans = Math.max(ans, f(2, 1, 0));
return ans;
}
|
3,310
|
Remove Methods From Project
|
Medium
|
<p>You are maintaining a project that has <code>n</code> methods numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>invocations</code>, where <code>invocations[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that method <code>a<sub>i</sub></code> invokes method <code>b<sub>i</sub></code>.</p>
<p>There is a known bug in method <code>k</code>. Method <code>k</code>, along with any method invoked by it, either <strong>directly</strong> or <strong>indirectly</strong>, are considered <strong>suspicious</strong> and we aim to remove them.</p>
<p>A group of methods can only be removed if no method <strong>outside</strong> the group invokes any methods <strong>within</strong> it.</p>
<p>Return an array containing all the remaining methods after removing all the <strong>suspicious</strong> methods. You may return the answer in <em>any order</em>. If it is not possible to remove <strong>all</strong> the suspicious methods, <strong>none</strong> should be removed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-2.png" style="width: 200px; height: 200px;" /></p>
<p>Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-3.png" style="width: 200px; height: 200px;" /></p>
<p>Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph.png" style="width: 200px; height: 200px;" /></p>
<p>All methods are suspicious. We can remove them.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
<li><code>0 <= invocations.length <= 2 * 10<sup>5</sup></code></li>
<li><code>invocations[i] == [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>invocations[i] != invocations[j]</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
C++
|
class Solution {
public:
vector<int> remainingMethods(int n, int k, vector<vector<int>>& invocations) {
vector<bool> suspicious(n);
vector<bool> vis(n);
vector<int> f[n];
vector<int> g[n];
for (const auto& e : invocations) {
int a = e[0], b = e[1];
f[a].push_back(b);
f[b].push_back(a);
g[a].push_back(b);
}
auto dfs = [&](this auto&& dfs, int i) -> void {
suspicious[i] = true;
for (int j : g[i]) {
if (!suspicious[j]) {
dfs(j);
}
}
};
dfs(k);
auto dfs2 = [&](this auto&& dfs2, int i) -> void {
vis[i] = true;
for (int j : f[i]) {
if (!vis[j]) {
suspicious[j] = false;
dfs2(j);
}
}
};
for (int i = 0; i < n; ++i) {
if (!suspicious[i] && !vis[i]) {
dfs2(i);
}
}
vector<int> ans;
for (int i = 0; i < n; ++i) {
if (!suspicious[i]) {
ans.push_back(i);
}
}
return ans;
}
};
|
3,310
|
Remove Methods From Project
|
Medium
|
<p>You are maintaining a project that has <code>n</code> methods numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>invocations</code>, where <code>invocations[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that method <code>a<sub>i</sub></code> invokes method <code>b<sub>i</sub></code>.</p>
<p>There is a known bug in method <code>k</code>. Method <code>k</code>, along with any method invoked by it, either <strong>directly</strong> or <strong>indirectly</strong>, are considered <strong>suspicious</strong> and we aim to remove them.</p>
<p>A group of methods can only be removed if no method <strong>outside</strong> the group invokes any methods <strong>within</strong> it.</p>
<p>Return an array containing all the remaining methods after removing all the <strong>suspicious</strong> methods. You may return the answer in <em>any order</em>. If it is not possible to remove <strong>all</strong> the suspicious methods, <strong>none</strong> should be removed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-2.png" style="width: 200px; height: 200px;" /></p>
<p>Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-3.png" style="width: 200px; height: 200px;" /></p>
<p>Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph.png" style="width: 200px; height: 200px;" /></p>
<p>All methods are suspicious. We can remove them.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
<li><code>0 <= invocations.length <= 2 * 10<sup>5</sup></code></li>
<li><code>invocations[i] == [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>invocations[i] != invocations[j]</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Go
|
func remainingMethods(n int, k int, invocations [][]int) []int {
suspicious := make([]bool, n)
vis := make([]bool, n)
f := make([][]int, n)
g := make([][]int, n)
for _, e := range invocations {
a, b := e[0], e[1]
f[a] = append(f[a], b)
f[b] = append(f[b], a)
g[a] = append(g[a], b)
}
var dfs func(int)
dfs = func(i int) {
suspicious[i] = true
for _, j := range g[i] {
if !suspicious[j] {
dfs(j)
}
}
}
dfs(k)
var dfs2 func(int)
dfs2 = func(i int) {
vis[i] = true
for _, j := range f[i] {
if !vis[j] {
suspicious[j] = false
dfs2(j)
}
}
}
for i := 0; i < n; i++ {
if !suspicious[i] && !vis[i] {
dfs2(i)
}
}
var ans []int
for i := 0; i < n; i++ {
if !suspicious[i] {
ans = append(ans, i)
}
}
return ans
}
|
3,310
|
Remove Methods From Project
|
Medium
|
<p>You are maintaining a project that has <code>n</code> methods numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>invocations</code>, where <code>invocations[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that method <code>a<sub>i</sub></code> invokes method <code>b<sub>i</sub></code>.</p>
<p>There is a known bug in method <code>k</code>. Method <code>k</code>, along with any method invoked by it, either <strong>directly</strong> or <strong>indirectly</strong>, are considered <strong>suspicious</strong> and we aim to remove them.</p>
<p>A group of methods can only be removed if no method <strong>outside</strong> the group invokes any methods <strong>within</strong> it.</p>
<p>Return an array containing all the remaining methods after removing all the <strong>suspicious</strong> methods. You may return the answer in <em>any order</em>. If it is not possible to remove <strong>all</strong> the suspicious methods, <strong>none</strong> should be removed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-2.png" style="width: 200px; height: 200px;" /></p>
<p>Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-3.png" style="width: 200px; height: 200px;" /></p>
<p>Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph.png" style="width: 200px; height: 200px;" /></p>
<p>All methods are suspicious. We can remove them.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
<li><code>0 <= invocations.length <= 2 * 10<sup>5</sup></code></li>
<li><code>invocations[i] == [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>invocations[i] != invocations[j]</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Java
|
class Solution {
private boolean[] suspicious;
private boolean[] vis;
private List<Integer>[] f;
private List<Integer>[] g;
public List<Integer> remainingMethods(int n, int k, int[][] invocations) {
suspicious = new boolean[n];
vis = new boolean[n];
f = new List[n];
g = new List[n];
Arrays.setAll(f, i -> new ArrayList<>());
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : invocations) {
int a = e[0], b = e[1];
f[a].add(b);
f[b].add(a);
g[a].add(b);
}
dfs(k);
for (int i = 0; i < n; ++i) {
if (!suspicious[i] && !vis[i]) {
dfs2(i);
}
}
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; ++i) {
if (!suspicious[i]) {
ans.add(i);
}
}
return ans;
}
private void dfs(int i) {
suspicious[i] = true;
for (int j : g[i]) {
if (!suspicious[j]) {
dfs(j);
}
}
}
private void dfs2(int i) {
vis[i] = true;
for (int j : f[i]) {
if (!vis[j]) {
suspicious[j] = false;
dfs2(j);
}
}
}
}
|
3,310
|
Remove Methods From Project
|
Medium
|
<p>You are maintaining a project that has <code>n</code> methods numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>invocations</code>, where <code>invocations[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that method <code>a<sub>i</sub></code> invokes method <code>b<sub>i</sub></code>.</p>
<p>There is a known bug in method <code>k</code>. Method <code>k</code>, along with any method invoked by it, either <strong>directly</strong> or <strong>indirectly</strong>, are considered <strong>suspicious</strong> and we aim to remove them.</p>
<p>A group of methods can only be removed if no method <strong>outside</strong> the group invokes any methods <strong>within</strong> it.</p>
<p>Return an array containing all the remaining methods after removing all the <strong>suspicious</strong> methods. You may return the answer in <em>any order</em>. If it is not possible to remove <strong>all</strong> the suspicious methods, <strong>none</strong> should be removed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-2.png" style="width: 200px; height: 200px;" /></p>
<p>Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-3.png" style="width: 200px; height: 200px;" /></p>
<p>Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph.png" style="width: 200px; height: 200px;" /></p>
<p>All methods are suspicious. We can remove them.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
<li><code>0 <= invocations.length <= 2 * 10<sup>5</sup></code></li>
<li><code>invocations[i] == [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>invocations[i] != invocations[j]</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Python
|
class Solution:
def remainingMethods(
self, n: int, k: int, invocations: List[List[int]]
) -> List[int]:
def dfs(i: int):
suspicious[i] = True
for j in g[i]:
if not suspicious[j]:
dfs(j)
def dfs2(i: int):
vis[i] = True
for j in f[i]:
if not vis[j]:
suspicious[j] = False
dfs2(j)
f = [[] for _ in range(n)]
g = [[] for _ in range(n)]
for a, b in invocations:
f[a].append(b)
f[b].append(a)
g[a].append(b)
suspicious = [False] * n
dfs(k)
vis = [False] * n
ans = []
for i in range(n):
if not suspicious[i] and not vis[i]:
dfs2(i)
return [i for i in range(n) if not suspicious[i]]
|
3,310
|
Remove Methods From Project
|
Medium
|
<p>You are maintaining a project that has <code>n</code> methods numbered from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>invocations</code>, where <code>invocations[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that method <code>a<sub>i</sub></code> invokes method <code>b<sub>i</sub></code>.</p>
<p>There is a known bug in method <code>k</code>. Method <code>k</code>, along with any method invoked by it, either <strong>directly</strong> or <strong>indirectly</strong>, are considered <strong>suspicious</strong> and we aim to remove them.</p>
<p>A group of methods can only be removed if no method <strong>outside</strong> the group invokes any methods <strong>within</strong> it.</p>
<p>Return an array containing all the remaining methods after removing all the <strong>suspicious</strong> methods. You may return the answer in <em>any order</em>. If it is not possible to remove <strong>all</strong> the suspicious methods, <strong>none</strong> should be removed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-2.png" style="width: 200px; height: 200px;" /></p>
<p>Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph-3.png" style="width: 200px; height: 200px;" /></p>
<p>Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3310.Remove%20Methods%20From%20Project/images/graph.png" style="width: 200px; height: 200px;" /></p>
<p>All methods are suspicious. We can remove them.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
<li><code>0 <= invocations.length <= 2 * 10<sup>5</sup></code></li>
<li><code>invocations[i] == [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>invocations[i] != invocations[j]</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
TypeScript
|
function remainingMethods(n: number, k: number, invocations: number[][]): number[] {
const suspicious: boolean[] = Array(n).fill(false);
const vis: boolean[] = Array(n).fill(false);
const f: number[][] = Array.from({ length: n }, () => []);
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of invocations) {
f[a].push(b);
f[b].push(a);
g[a].push(b);
}
const dfs = (i: number) => {
suspicious[i] = true;
for (const j of g[i]) {
if (!suspicious[j]) {
dfs(j);
}
}
};
dfs(k);
const dfs2 = (i: number) => {
vis[i] = true;
for (const j of f[i]) {
if (!vis[j]) {
suspicious[j] = false;
dfs2(j);
}
}
};
for (let i = 0; i < n; i++) {
if (!suspicious[i] && !vis[i]) {
dfs2(i);
}
}
return Array.from({ length: n }, (_, i) => i).filter(i => !suspicious[i]);
}
|
3,311
|
Construct 2D Grid Matching Graph Layout
|
Hard
|
<p>You are given a 2D integer array <code>edges</code> representing an <strong>undirected</strong> graph having <code>n</code> nodes, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Construct a 2D grid that satisfies these conditions:</p>
<ul>
<li>The grid contains <strong>all nodes</strong> from <code>0</code> to <code>n - 1</code> in its cells, with each node appearing exactly <strong>once</strong>.</li>
<li>Two nodes should be in adjacent grid cells (<strong>horizontally</strong> or <strong>vertically</strong>) <strong>if and only if</strong> there is an edge between them in <code>edges</code>.</li>
</ul>
<p>It is guaranteed that <code>edges</code> can form a 2D grid that satisfies the conditions.</p>
<p>Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return <em>any</em> of them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[3,1],[2,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-07-59.png" style="width: 133px; height: 92px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[4,2,3,1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-02.png" style="width: 325px; height: 50px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,6,3],[7,4,2],[1,0,5]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-38.png" style="width: 198px; height: 133px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= edges.length <= 10<sup>5</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>All the edges are distinct.</li>
<li>The input is generated such that <code>edges</code> can form a 2D grid that satisfies the conditions.</li>
</ul>
|
Graph; Array; Hash Table; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> constructGridLayout(int n, vector<vector<int>>& edges) {
vector<vector<int>> g(n);
for (auto& e : edges) {
int u = e[0], v = e[1];
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> deg(5, -1);
for (int x = 0; x < n; ++x) {
deg[g[x].size()] = x;
}
vector<int> row;
if (deg[1] != -1) {
row.push_back(deg[1]);
} else if (deg[4] == -1) {
int x = deg[2];
for (int y : g[x]) {
if (g[y].size() == 2) {
row.push_back(x);
row.push_back(y);
break;
}
}
} else {
int x = deg[2];
row.push_back(x);
int pre = x;
x = g[x][0];
while (g[x].size() > 2) {
row.push_back(x);
for (int y : g[x]) {
if (y != pre && g[y].size() < 4) {
pre = x;
x = y;
break;
}
}
}
row.push_back(x);
}
vector<vector<int>> ans;
ans.push_back(row);
vector<bool> vis(n, false);
int rowSize = row.size();
for (int i = 0; i < n / rowSize - 1; ++i) {
for (int x : row) {
vis[x] = true;
}
vector<int> nxt;
for (int x : row) {
for (int y : g[x]) {
if (!vis[y]) {
nxt.push_back(y);
break;
}
}
}
ans.push_back(nxt);
row = nxt;
}
return ans;
}
};
|
3,311
|
Construct 2D Grid Matching Graph Layout
|
Hard
|
<p>You are given a 2D integer array <code>edges</code> representing an <strong>undirected</strong> graph having <code>n</code> nodes, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Construct a 2D grid that satisfies these conditions:</p>
<ul>
<li>The grid contains <strong>all nodes</strong> from <code>0</code> to <code>n - 1</code> in its cells, with each node appearing exactly <strong>once</strong>.</li>
<li>Two nodes should be in adjacent grid cells (<strong>horizontally</strong> or <strong>vertically</strong>) <strong>if and only if</strong> there is an edge between them in <code>edges</code>.</li>
</ul>
<p>It is guaranteed that <code>edges</code> can form a 2D grid that satisfies the conditions.</p>
<p>Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return <em>any</em> of them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[3,1],[2,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-07-59.png" style="width: 133px; height: 92px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[4,2,3,1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-02.png" style="width: 325px; height: 50px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,6,3],[7,4,2],[1,0,5]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-38.png" style="width: 198px; height: 133px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= edges.length <= 10<sup>5</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>All the edges are distinct.</li>
<li>The input is generated such that <code>edges</code> can form a 2D grid that satisfies the conditions.</li>
</ul>
|
Graph; Array; Hash Table; Matrix
|
Go
|
func constructGridLayout(n int, edges [][]int) [][]int {
g := make([][]int, n)
for _, e := range edges {
u, v := e[0], e[1]
g[u] = append(g[u], v)
g[v] = append(g[v], u)
}
deg := make([]int, 5)
for i := range deg {
deg[i] = -1
}
for x := 0; x < n; x++ {
deg[len(g[x])] = x
}
var row []int
if deg[1] != -1 {
row = append(row, deg[1])
} else if deg[4] == -1 {
x := deg[2]
for _, y := range g[x] {
if len(g[y]) == 2 {
row = append(row, x, y)
break
}
}
} else {
x := deg[2]
row = append(row, x)
pre := x
x = g[x][0]
for len(g[x]) > 2 {
row = append(row, x)
for _, y := range g[x] {
if y != pre && len(g[y]) < 4 {
pre = x
x = y
break
}
}
}
row = append(row, x)
}
ans := [][]int{row}
vis := make([]bool, n)
rowSize := len(row)
for i := 0; i < n/rowSize-1; i++ {
for _, x := range row {
vis[x] = true
}
nxt := []int{}
for _, x := range row {
for _, y := range g[x] {
if !vis[y] {
nxt = append(nxt, y)
break
}
}
}
ans = append(ans, nxt)
row = nxt
}
return ans
}
|
3,311
|
Construct 2D Grid Matching Graph Layout
|
Hard
|
<p>You are given a 2D integer array <code>edges</code> representing an <strong>undirected</strong> graph having <code>n</code> nodes, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Construct a 2D grid that satisfies these conditions:</p>
<ul>
<li>The grid contains <strong>all nodes</strong> from <code>0</code> to <code>n - 1</code> in its cells, with each node appearing exactly <strong>once</strong>.</li>
<li>Two nodes should be in adjacent grid cells (<strong>horizontally</strong> or <strong>vertically</strong>) <strong>if and only if</strong> there is an edge between them in <code>edges</code>.</li>
</ul>
<p>It is guaranteed that <code>edges</code> can form a 2D grid that satisfies the conditions.</p>
<p>Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return <em>any</em> of them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[3,1],[2,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-07-59.png" style="width: 133px; height: 92px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[4,2,3,1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-02.png" style="width: 325px; height: 50px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,6,3],[7,4,2],[1,0,5]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-38.png" style="width: 198px; height: 133px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= edges.length <= 10<sup>5</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>All the edges are distinct.</li>
<li>The input is generated such that <code>edges</code> can form a 2D grid that satisfies the conditions.</li>
</ul>
|
Graph; Array; Hash Table; Matrix
|
Java
|
class Solution {
public int[][] constructGridLayout(int n, int[][] edges) {
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int u = e[0], v = e[1];
g[u].add(v);
g[v].add(u);
}
int[] deg = new int[5];
Arrays.fill(deg, -1);
for (int x = 0; x < n; x++) {
deg[g[x].size()] = x;
}
List<Integer> row = new ArrayList<>();
if (deg[1] != -1) {
row.add(deg[1]);
} else if (deg[4] == -1) {
int x = deg[2];
for (int y : g[x]) {
if (g[y].size() == 2) {
row.add(x);
row.add(y);
break;
}
}
} else {
int x = deg[2];
row.add(x);
int pre = x;
x = g[x].get(0);
while (g[x].size() > 2) {
row.add(x);
for (int y : g[x]) {
if (y != pre && g[y].size() < 4) {
pre = x;
x = y;
break;
}
}
}
row.add(x);
}
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>(row));
boolean[] vis = new boolean[n];
int rowSize = row.size();
for (int i = 0; i < n / rowSize - 1; i++) {
for (int x : row) {
vis[x] = true;
}
List<Integer> nxt = new ArrayList<>();
for (int x : row) {
for (int y : g[x]) {
if (!vis[y]) {
nxt.add(y);
break;
}
}
}
res.add(new ArrayList<>(nxt));
row = nxt;
}
int[][] ans = new int[res.size()][rowSize];
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < rowSize; j++) {
ans[i][j] = res.get(i).get(j);
}
}
return ans;
}
}
|
3,311
|
Construct 2D Grid Matching Graph Layout
|
Hard
|
<p>You are given a 2D integer array <code>edges</code> representing an <strong>undirected</strong> graph having <code>n</code> nodes, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Construct a 2D grid that satisfies these conditions:</p>
<ul>
<li>The grid contains <strong>all nodes</strong> from <code>0</code> to <code>n - 1</code> in its cells, with each node appearing exactly <strong>once</strong>.</li>
<li>Two nodes should be in adjacent grid cells (<strong>horizontally</strong> or <strong>vertically</strong>) <strong>if and only if</strong> there is an edge between them in <code>edges</code>.</li>
</ul>
<p>It is guaranteed that <code>edges</code> can form a 2D grid that satisfies the conditions.</p>
<p>Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return <em>any</em> of them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[3,1],[2,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-07-59.png" style="width: 133px; height: 92px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[4,2,3,1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-02.png" style="width: 325px; height: 50px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,6,3],[7,4,2],[1,0,5]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-38.png" style="width: 198px; height: 133px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= edges.length <= 10<sup>5</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>All the edges are distinct.</li>
<li>The input is generated such that <code>edges</code> can form a 2D grid that satisfies the conditions.</li>
</ul>
|
Graph; Array; Hash Table; Matrix
|
Python
|
class Solution:
def constructGridLayout(self, n: int, edges: List[List[int]]) -> List[List[int]]:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
deg = [-1] * 5
for x, ys in enumerate(g):
deg[len(ys)] = x
if deg[1] != -1:
row = [deg[1]]
elif deg[4] == -1:
x = deg[2]
for y in g[x]:
if len(g[y]) == 2:
row = [x, y]
break
else:
x = deg[2]
row = [x]
pre = x
x = g[x][0]
while len(g[x]) > 2:
row.append(x)
for y in g[x]:
if y != pre and len(g[y]) < 4:
pre = x
x = y
break
row.append(x)
ans = [row]
vis = [False] * n
for _ in range(n // len(row) - 1):
for x in row:
vis[x] = True
nxt = []
for x in row:
for y in g[x]:
if not vis[y]:
nxt.append(y)
break
ans.append(nxt)
row = nxt
return ans
|
3,311
|
Construct 2D Grid Matching Graph Layout
|
Hard
|
<p>You are given a 2D integer array <code>edges</code> representing an <strong>undirected</strong> graph having <code>n</code> nodes, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Construct a 2D grid that satisfies these conditions:</p>
<ul>
<li>The grid contains <strong>all nodes</strong> from <code>0</code> to <code>n - 1</code> in its cells, with each node appearing exactly <strong>once</strong>.</li>
<li>Two nodes should be in adjacent grid cells (<strong>horizontally</strong> or <strong>vertically</strong>) <strong>if and only if</strong> there is an edge between them in <code>edges</code>.</li>
</ul>
<p>It is guaranteed that <code>edges</code> can form a 2D grid that satisfies the conditions.</p>
<p>Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return <em>any</em> of them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[3,1],[2,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-07-59.png" style="width: 133px; height: 92px;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[4,2,3,1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-02.png" style="width: 325px; height: 50px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,6,3],[7,4,2],[1,0,5]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3311.Construct%202D%20Grid%20Matching%20Graph%20Layout/images/screenshot-from-2024-08-11-14-06-38.png" style="width: 198px; height: 133px;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= edges.length <= 10<sup>5</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>All the edges are distinct.</li>
<li>The input is generated such that <code>edges</code> can form a 2D grid that satisfies the conditions.</li>
</ul>
|
Graph; Array; Hash Table; Matrix
|
TypeScript
|
function constructGridLayout(n: number, edges: number[][]): number[][] {
const g: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
g[u].push(v);
g[v].push(u);
}
const deg: number[] = Array(5).fill(-1);
for (let x = 0; x < n; x++) {
deg[g[x].length] = x;
}
let row: number[] = [];
if (deg[1] !== -1) {
row.push(deg[1]);
} else if (deg[4] === -1) {
let x = deg[2];
for (const y of g[x]) {
if (g[y].length === 2) {
row.push(x, y);
break;
}
}
} else {
let x = deg[2];
row.push(x);
let pre = x;
x = g[x][0];
while (g[x].length > 2) {
row.push(x);
for (const y of g[x]) {
if (y !== pre && g[y].length < 4) {
pre = x;
x = y;
break;
}
}
}
row.push(x);
}
const ans: number[][] = [row];
const vis: boolean[] = Array(n).fill(false);
const rowSize = row.length;
for (let i = 0; i < Math.floor(n / rowSize) - 1; i++) {
for (const x of row) {
vis[x] = true;
}
const nxt: number[] = [];
for (const x of row) {
for (const y of g[x]) {
if (!vis[y]) {
nxt.push(y);
break;
}
}
}
ans.push(nxt);
row = nxt;
}
return ans;
}
|
3,312
|
Sorted GCD Pair Queries
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and an integer array <code>queries</code>.</p>
<p>Let <code>gcdPairs</code> denote an array obtained by calculating the <span data-keyword="gcd-function">GCD</span> of all possible pairs <code>(nums[i], nums[j])</code>, where <code>0 <= i < j < n</code>, and then sorting these values in <strong>ascending</strong> order.</p>
<p>For each query <code>queries[i]</code>, you need to find the element at index <code>queries[i]</code> in <code>gcdPairs</code>.</p>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the value at <code>gcdPairs[queries[i]]</code> for each query.</p>
<p>The term <code>gcd(a, b)</code> denotes the <strong>greatest common divisor</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4], queries = [0,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]</code>.</p>
<p>After sorting in ascending order, <code>gcdPairs = [1, 1, 2]</code>.</p>
<p>So, the answer is <code>[gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,2,1], queries = [5,3,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,2,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs</code> sorted in ascending order is <code>[1, 1, 1, 2, 2, 4]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], queries = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [2]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>0 <= queries[i] < n * (n - 1) / 2</code></li>
</ul>
|
Array; Hash Table; Math; Binary Search; Combinatorics; Counting; Number Theory; Prefix Sum
|
C++
|
class Solution {
public:
vector<int> gcdValues(vector<int>& nums, vector<long long>& queries) {
int mx = ranges::max(nums);
vector<int> cnt(mx + 1);
vector<long long> cntG(mx + 1);
for (int x : nums) {
++cnt[x];
}
for (int i = mx; i; --i) {
long long v = 0;
for (int j = i; j <= mx; j += i) {
v += cnt[j];
cntG[i] -= cntG[j];
}
cntG[i] += 1LL * v * (v - 1) / 2;
}
for (int i = 2; i <= mx; ++i) {
cntG[i] += cntG[i - 1];
}
vector<int> ans;
for (auto&& q : queries) {
ans.push_back(upper_bound(cntG.begin(), cntG.end(), q) - cntG.begin());
}
return ans;
}
};
|
3,312
|
Sorted GCD Pair Queries
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and an integer array <code>queries</code>.</p>
<p>Let <code>gcdPairs</code> denote an array obtained by calculating the <span data-keyword="gcd-function">GCD</span> of all possible pairs <code>(nums[i], nums[j])</code>, where <code>0 <= i < j < n</code>, and then sorting these values in <strong>ascending</strong> order.</p>
<p>For each query <code>queries[i]</code>, you need to find the element at index <code>queries[i]</code> in <code>gcdPairs</code>.</p>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the value at <code>gcdPairs[queries[i]]</code> for each query.</p>
<p>The term <code>gcd(a, b)</code> denotes the <strong>greatest common divisor</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4], queries = [0,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]</code>.</p>
<p>After sorting in ascending order, <code>gcdPairs = [1, 1, 2]</code>.</p>
<p>So, the answer is <code>[gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,2,1], queries = [5,3,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,2,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs</code> sorted in ascending order is <code>[1, 1, 1, 2, 2, 4]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], queries = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [2]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>0 <= queries[i] < n * (n - 1) / 2</code></li>
</ul>
|
Array; Hash Table; Math; Binary Search; Combinatorics; Counting; Number Theory; Prefix Sum
|
Go
|
func gcdValues(nums []int, queries []int64) (ans []int) {
mx := slices.Max(nums)
cnt := make([]int, mx+1)
cntG := make([]int, mx+1)
for _, x := range nums {
cnt[x]++
}
for i := mx; i > 0; i-- {
var v int
for j := i; j <= mx; j += i {
v += cnt[j]
cntG[i] -= cntG[j]
}
cntG[i] += v * (v - 1) / 2
}
for i := 2; i <= mx; i++ {
cntG[i] += cntG[i-1]
}
for _, q := range queries {
ans = append(ans, sort.SearchInts(cntG, int(q)+1))
}
return
}
|
3,312
|
Sorted GCD Pair Queries
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and an integer array <code>queries</code>.</p>
<p>Let <code>gcdPairs</code> denote an array obtained by calculating the <span data-keyword="gcd-function">GCD</span> of all possible pairs <code>(nums[i], nums[j])</code>, where <code>0 <= i < j < n</code>, and then sorting these values in <strong>ascending</strong> order.</p>
<p>For each query <code>queries[i]</code>, you need to find the element at index <code>queries[i]</code> in <code>gcdPairs</code>.</p>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the value at <code>gcdPairs[queries[i]]</code> for each query.</p>
<p>The term <code>gcd(a, b)</code> denotes the <strong>greatest common divisor</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4], queries = [0,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]</code>.</p>
<p>After sorting in ascending order, <code>gcdPairs = [1, 1, 2]</code>.</p>
<p>So, the answer is <code>[gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,2,1], queries = [5,3,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,2,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs</code> sorted in ascending order is <code>[1, 1, 1, 2, 2, 4]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], queries = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [2]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>0 <= queries[i] < n * (n - 1) / 2</code></li>
</ul>
|
Array; Hash Table; Math; Binary Search; Combinatorics; Counting; Number Theory; Prefix Sum
|
Java
|
class Solution {
public int[] gcdValues(int[] nums, long[] queries) {
int mx = Arrays.stream(nums).max().getAsInt();
int[] cnt = new int[mx + 1];
long[] cntG = new long[mx + 1];
for (int x : nums) {
++cnt[x];
}
for (int i = mx; i > 0; --i) {
int v = 0;
for (int j = i; j <= mx; j += i) {
v += cnt[j];
cntG[i] -= cntG[j];
}
cntG[i] += 1L * v * (v - 1) / 2;
}
for (int i = 2; i <= mx; ++i) {
cntG[i] += cntG[i - 1];
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
ans[i] = search(cntG, queries[i]);
}
return ans;
}
private int search(long[] nums, long x) {
int n = nums.length;
int l = 0, r = n;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] > x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
|
3,312
|
Sorted GCD Pair Queries
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and an integer array <code>queries</code>.</p>
<p>Let <code>gcdPairs</code> denote an array obtained by calculating the <span data-keyword="gcd-function">GCD</span> of all possible pairs <code>(nums[i], nums[j])</code>, where <code>0 <= i < j < n</code>, and then sorting these values in <strong>ascending</strong> order.</p>
<p>For each query <code>queries[i]</code>, you need to find the element at index <code>queries[i]</code> in <code>gcdPairs</code>.</p>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the value at <code>gcdPairs[queries[i]]</code> for each query.</p>
<p>The term <code>gcd(a, b)</code> denotes the <strong>greatest common divisor</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4], queries = [0,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]</code>.</p>
<p>After sorting in ascending order, <code>gcdPairs = [1, 1, 2]</code>.</p>
<p>So, the answer is <code>[gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,2,1], queries = [5,3,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,2,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs</code> sorted in ascending order is <code>[1, 1, 1, 2, 2, 4]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], queries = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>gcdPairs = [2]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>0 <= queries[i] < n * (n - 1) / 2</code></li>
</ul>
|
Array; Hash Table; Math; Binary Search; Combinatorics; Counting; Number Theory; Prefix Sum
|
Python
|
class Solution:
def gcdValues(self, nums: List[int], queries: List[int]) -> List[int]:
mx = max(nums)
cnt = Counter(nums)
cnt_g = [0] * (mx + 1)
for i in range(mx, 0, -1):
v = 0
for j in range(i, mx + 1, i):
v += cnt[j]
cnt_g[i] -= cnt_g[j]
cnt_g[i] += v * (v - 1) // 2
s = list(accumulate(cnt_g))
return [bisect_right(s, q) for q in queries]
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
C++
|
class Solution {
public:
vector<int> lastMarkedNodes(vector<vector<int>>& edges) {
int n = edges.size() + 1;
g.resize(n);
for (const auto& e : edges) {
int u = e[0], v = e[1];
g[u].push_back(v);
g[v].push_back(u);
}
vector<int> dist1(n);
dfs(0, -1, dist1);
int a = max_element(dist1.begin(), dist1.end()) - dist1.begin();
vector<int> dist2(n);
dfs(a, -1, dist2);
int b = max_element(dist2.begin(), dist2.end()) - dist2.begin();
vector<int> dist3(n);
dfs(b, -1, dist3);
vector<int> ans;
for (int i = 0; i < n; ++i) {
ans.push_back(dist2[i] > dist3[i] ? a : b);
}
return ans;
}
private:
vector<vector<int>> g;
void dfs(int i, int fa, vector<int>& dist) {
for (int j : g[i]) {
if (j != fa) {
dist[j] = dist[i] + 1;
dfs(j, i, dist);
}
}
}
};
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Go
|
func lastMarkedNodes(edges [][]int) (ans []int) {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
u, v := e[0], e[1]
g[u] = append(g[u], v)
g[v] = append(g[v], u)
}
var dfs func(int, int, []int)
dfs = func(i, fa int, dist []int) {
for _, j := range g[i] {
if j != fa {
dist[j] = dist[i] + 1
dfs(j, i, dist)
}
}
}
maxNode := func(dist []int) int {
mx := 0
for i, d := range dist {
if dist[mx] < d {
mx = i
}
}
return mx
}
dist1 := make([]int, n)
dfs(0, -1, dist1)
a := maxNode(dist1)
dist2 := make([]int, n)
dfs(a, -1, dist2)
b := maxNode(dist2)
dist3 := make([]int, n)
dfs(b, -1, dist3)
for i, x := range dist2 {
if x > dist3[i] {
ans = append(ans, a)
} else {
ans = append(ans, b)
}
}
return
}
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Java
|
class Solution {
private List<Integer>[] g;
public int[] lastMarkedNodes(int[][] edges) {
int n = edges.length + 1;
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int u = e[0], v = e[1];
g[u].add(v);
g[v].add(u);
}
int[] dist1 = new int[n];
dist1[0] = 0;
dfs(0, -1, dist1);
int a = maxNode(dist1);
int[] dist2 = new int[n];
dist2[a] = 0;
dfs(a, -1, dist2);
int b = maxNode(dist2);
int[] dist3 = new int[n];
dist3[b] = 0;
dfs(b, -1, dist3);
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = dist2[i] > dist3[i] ? a : b;
}
return ans;
}
private void dfs(int i, int fa, int[] dist) {
for (int j : g[i]) {
if (j != fa) {
dist[j] = dist[i] + 1;
dfs(j, i, dist);
}
}
}
private int maxNode(int[] dist) {
int mx = 0;
for (int i = 0; i < dist.length; ++i) {
if (dist[mx] < dist[i]) {
mx = i;
}
}
return mx;
}
}
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
JavaScript
|
/**
* @param {number[][]} edges
* @return {number[]}
*/
var lastMarkedNodes = function (edges) {
const n = edges.length + 1;
const g = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
g[u].push(v);
g[v].push(u);
}
const dfs = (i, fa, dist) => {
for (const j of g[i]) {
if (j !== fa) {
dist[j] = dist[i] + 1;
dfs(j, i, dist);
}
}
};
const dist1 = Array(n).fill(0);
dfs(0, -1, dist1);
const a = dist1.indexOf(Math.max(...dist1));
const dist2 = Array(n).fill(0);
dfs(a, -1, dist2);
const b = dist2.indexOf(Math.max(...dist2));
const dist3 = Array(n).fill(0);
dfs(b, -1, dist3);
const ans = [];
for (let i = 0; i < n; ++i) {
ans.push(dist2[i] > dist3[i] ? a : b);
}
return ans;
};
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Python
|
class Solution:
def lastMarkedNodes(self, edges: List[List[int]]) -> List[int]:
def dfs(i: int, fa: int, dist: List[int]):
for j in g[i]:
if j != fa:
dist[j] = dist[i] + 1
dfs(j, i, dist)
n = len(edges) + 1
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
dist1 = [-1] * n
dist1[0] = 0
dfs(0, -1, dist1)
a = dist1.index(max(dist1))
dist2 = [-1] * n
dist2[a] = 0
dfs(a, -1, dist2)
b = dist2.index(max(dist2))
dist3 = [-1] * n
dist3[b] = 0
dfs(b, -1, dist3)
return [a if x > y else b for x, y in zip(dist2, dist3)]
|
3,313
|
Find the Last Marked Nodes in Tree
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p>
<p>Initially, <strong>all</strong> nodes are <strong>unmarked</strong>. After every second, you mark all unmarked nodes which have <strong>at least</strong> one marked node <em>adjacent</em> to them.</p>
<p>Return an array <code>nodes</code> where <code>nodes[i]</code> is the last node to get marked in the tree, if you mark node <code>i</code> at time <code>t = 0</code>. If <code>nodes[i]</code> has <em>multiple</em> answers for any node <code>i</code>, you can choose<strong> any</strong> one answer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2]]</span></p>
<p><strong>Output:</strong> [2,2,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122236.png" style="width: 450px; height: 217px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2]</code>. Either 1 or 2 can be the answer.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2]</code>. Node 2 is marked last.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2] -> [0,1,2]</code>. Node 1 is marked last.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1]]</span></p>
<p><strong>Output:</strong> [1,0]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-02-122249.png" style="width: 350px; height: 180px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[2,3],[2,4]]</span></p>
<p><strong>Output:</strong> [3,3,1,1,1]</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3313.Find%20the%20Last%20Marked%20Nodes%20in%20Tree/images/screenshot-2024-06-03-210550.png" style="height: 240px; width: 450px;" /></p>
<ul>
<li>For <code>i = 0</code>, the nodes are marked in the sequence: <code>[0] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 1</code>, the nodes are marked in the sequence: <code>[1] -> [0,1] -> [0,1,2] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 2</code>, the nodes are marked in the sequence: <code>[2] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 3</code>, the nodes are marked in the sequence: <code>[3] -> [2,3] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
<li>For <code>i = 4</code>, the nodes are marked in the sequence: <code>[4] -> [2,4] -> [0,2,3,4] -> [0,1,2,3,4]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
TypeScript
|
function lastMarkedNodes(edges: number[][]): number[] {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
g[u].push(v);
g[v].push(u);
}
const dfs = (i: number, fa: number, dist: number[]) => {
for (const j of g[i]) {
if (j !== fa) {
dist[j] = dist[i] + 1;
dfs(j, i, dist);
}
}
};
const dist1: number[] = Array(n).fill(0);
dfs(0, -1, dist1);
const a = dist1.indexOf(Math.max(...dist1));
const dist2: number[] = Array(n).fill(0);
dfs(a, -1, dist2);
const b = dist2.indexOf(Math.max(...dist2));
const dist3: number[] = Array(n).fill(0);
dfs(b, -1, dist3);
const ans: number[] = [];
for (let i = 0; i < n; ++i) {
ans.push(dist2[i] > dist3[i] ? a : b);
}
return ans;
}
|
3,314
|
Construct the Minimum Bitwise Array I
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 1000</code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector<int> ans;
for (int x : nums) {
if (x == 2) {
ans.push_back(-1);
} else {
for (int i = 1; i < 32; ++i) {
if (x >> i & 1 ^ 1) {
ans.push_back(x ^ 1 << (i - 1));
break;
}
}
}
}
return ans;
}
};
|
3,314
|
Construct the Minimum Bitwise Array I
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 1000</code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func minBitwiseArray(nums []int) (ans []int) {
for _, x := range nums {
if x == 2 {
ans = append(ans, -1)
} else {
for i := 1; i < 32; i++ {
if x>>i&1 == 0 {
ans = append(ans, x^1<<(i-1))
break
}
}
}
}
return
}
|
3,314
|
Construct the Minimum Bitwise Array I
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 1000</code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int n = nums.size();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int x = nums.get(i);
if (x == 2) {
ans[i] = -1;
} else {
for (int j = 1; j < 32; ++j) {
if ((x >> j & 1) == 0) {
ans[i] = x ^ 1 << (j - 1);
break;
}
}
}
}
return ans;
}
}
|
3,314
|
Construct the Minimum Bitwise Array I
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 1000</code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
break
return ans
|
3,314
|
Construct the Minimum Bitwise Array I
|
Easy
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 1000</code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function minBitwiseArray(nums: number[]): number[] {
const ans: number[] = [];
for (const x of nums) {
if (x === 2) {
ans.push(-1);
} else {
for (let i = 1; i < 32; ++i) {
if (((x >> i) & 1) ^ 1) {
ans.push(x ^ (1 << (i - 1)));
break;
}
}
}
}
return ans;
}
|
3,315
|
Construct the Minimum Bitwise Array II
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector<int> ans;
for (int x : nums) {
if (x == 2) {
ans.push_back(-1);
} else {
for (int i = 1; i < 32; ++i) {
if (x >> i & 1 ^ 1) {
ans.push_back(x ^ 1 << (i - 1));
break;
}
}
}
}
return ans;
}
};
|
3,315
|
Construct the Minimum Bitwise Array II
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func minBitwiseArray(nums []int) (ans []int) {
for _, x := range nums {
if x == 2 {
ans = append(ans, -1)
} else {
for i := 1; i < 32; i++ {
if x>>i&1 == 0 {
ans = append(ans, x^1<<(i-1))
break
}
}
}
}
return
}
|
3,315
|
Construct the Minimum Bitwise Array II
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int n = nums.size();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int x = nums.get(i);
if (x == 2) {
ans[i] = -1;
} else {
for (int j = 1; j < 32; ++j) {
if ((x >> j & 1) == 0) {
ans[i] = x ^ 1 << (j - 1);
break;
}
}
}
}
return ans;
}
}
|
3,315
|
Construct the Minimum Bitwise Array II
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
break
return ans
|
3,315
|
Construct the Minimum Bitwise Array II
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <code>n</code> <span data-keyword="prime-number">prime</span> integers.</p>
<p>You need to construct an array <code>ans</code> of length <code>n</code>, such that, for each index <code>i</code>, the bitwise <code>OR</code> of <code>ans[i]</code> and <code>ans[i] + 1</code> is equal to <code>nums[i]</code>, i.e. <code>ans[i] OR (ans[i] + 1) == nums[i]</code>.</p>
<p>Additionally, you must <strong>minimize</strong> each value of <code>ans[i]</code> in the resulting array.</p>
<p>If it is <em>not possible</em> to find such a value for <code>ans[i]</code> that satisfies the <strong>condition</strong>, then set <code>ans[i] = -1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,4,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, as there is no value for <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 2</code>, so <code>ans[0] = -1</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 3</code> is <code>1</code>, because <code>1 OR (1 + 1) = 3</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 5</code> is <code>4</code>, because <code>4 OR (4 + 1) = 5</code>.</li>
<li>For <code>i = 3</code>, the smallest <code>ans[3]</code> that satisfies <code>ans[3] OR (ans[3] + 1) = 7</code> is <code>3</code>, because <code>3 OR (3 + 1) = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [11,13,31]</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,12,15]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the smallest <code>ans[0]</code> that satisfies <code>ans[0] OR (ans[0] + 1) = 11</code> is <code>9</code>, because <code>9 OR (9 + 1) = 11</code>.</li>
<li>For <code>i = 1</code>, the smallest <code>ans[1]</code> that satisfies <code>ans[1] OR (ans[1] + 1) = 13</code> is <code>12</code>, because <code>12 OR (12 + 1) = 13</code>.</li>
<li>For <code>i = 2</code>, the smallest <code>ans[2]</code> that satisfies <code>ans[2] OR (ans[2] + 1) = 31</code> is <code>15</code>, because <code>15 OR (15 + 1) = 31</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>2 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>nums[i]</code> is a prime number.</li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function minBitwiseArray(nums: number[]): number[] {
const ans: number[] = [];
for (const x of nums) {
if (x === 2) {
ans.push(-1);
} else {
for (let i = 1; i < 32; ++i) {
if (((x >> i) & 1) ^ 1) {
ans.push(x ^ (1 << (i - 1)));
break;
}
}
}
}
return ans;
}
|
3,316
|
Find Maximum Removals From Source String
|
Medium
|
<p>You are given a string <code>source</code> of size <code>n</code>, a string <code>pattern</code> that is a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code>, and a <strong>sorted</strong> integer array <code>targetIndices</code> that contains <strong>distinct</strong> numbers in the range <code>[0, n - 1]</code>.</p>
<p>We define an <strong>operation</strong> as removing a character at an index <code>idx</code> from <code>source</code> such that:</p>
<ul>
<li><code>idx</code> is an element of <code>targetIndices</code>.</li>
<li><code>pattern</code> remains a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code> after removing the character.</li>
</ul>
<p>Performing an operation <strong>does not</strong> change the indices of the other characters in <code>source</code>. For example, if you remove <code>'c'</code> from <code>"acb"</code>, the character at index 2 would still be <code>'b'</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>operations</em> that can be performed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "abbaa", pattern = "aba", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>We can't remove <code>source[0]</code> but we can do either of these two operations:</p>
<ul>
<li>Remove <code>source[1]</code>, so that <code>source</code> becomes <code>"a_baa"</code>.</li>
<li>Remove <code>source[2]</code>, so that <code>source</code> becomes <code>"ab_aa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "bcda", pattern = "d", </span>targetIndices<span class="example-io"> = [0,3]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[0]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "dda", pattern = "dda", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We can't remove any character from <code>source</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = </span>"yeyeykyded"<span class="example-io">, pattern = </span>"yeyyd"<span class="example-io">, </span>targetIndices<span class="example-io"> = </span>[0,2,3,4]</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[2]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == source.length <= 3 * 10<sup>3</sup></code></li>
<li><code>1 <= pattern.length <= n</code></li>
<li><code>1 <= targetIndices.length <= n</code></li>
<li><code>targetIndices</code> is sorted in ascending order.</li>
<li>The input is generated such that <code>targetIndices</code> contains distinct elements in the range <code>[0, n - 1]</code>.</li>
<li><code>source</code> and <code>pattern</code> consist only of lowercase English letters.</li>
<li>The input is generated such that <code>pattern</code> appears as a subsequence in <code>source</code>.</li>
</ul>
|
Array; Hash Table; Two Pointers; String; Dynamic Programming
|
C++
|
class Solution {
public:
int maxRemovals(string source, string pattern, vector<int>& targetIndices) {
int m = source.length(), n = pattern.length();
vector<vector<int>> f(m + 1, vector<int>(n + 1, INT_MIN / 2));
f[0][0] = 0;
vector<int> s(m);
for (int i : targetIndices) {
s[i] = 1;
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j] + s[i - 1];
if (j > 0 && source[i - 1] == pattern[j - 1]) {
f[i][j] = max(f[i][j], f[i - 1][j - 1]);
}
}
}
return f[m][n];
}
};
|
3,316
|
Find Maximum Removals From Source String
|
Medium
|
<p>You are given a string <code>source</code> of size <code>n</code>, a string <code>pattern</code> that is a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code>, and a <strong>sorted</strong> integer array <code>targetIndices</code> that contains <strong>distinct</strong> numbers in the range <code>[0, n - 1]</code>.</p>
<p>We define an <strong>operation</strong> as removing a character at an index <code>idx</code> from <code>source</code> such that:</p>
<ul>
<li><code>idx</code> is an element of <code>targetIndices</code>.</li>
<li><code>pattern</code> remains a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code> after removing the character.</li>
</ul>
<p>Performing an operation <strong>does not</strong> change the indices of the other characters in <code>source</code>. For example, if you remove <code>'c'</code> from <code>"acb"</code>, the character at index 2 would still be <code>'b'</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>operations</em> that can be performed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "abbaa", pattern = "aba", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>We can't remove <code>source[0]</code> but we can do either of these two operations:</p>
<ul>
<li>Remove <code>source[1]</code>, so that <code>source</code> becomes <code>"a_baa"</code>.</li>
<li>Remove <code>source[2]</code>, so that <code>source</code> becomes <code>"ab_aa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "bcda", pattern = "d", </span>targetIndices<span class="example-io"> = [0,3]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[0]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "dda", pattern = "dda", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We can't remove any character from <code>source</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = </span>"yeyeykyded"<span class="example-io">, pattern = </span>"yeyyd"<span class="example-io">, </span>targetIndices<span class="example-io"> = </span>[0,2,3,4]</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[2]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == source.length <= 3 * 10<sup>3</sup></code></li>
<li><code>1 <= pattern.length <= n</code></li>
<li><code>1 <= targetIndices.length <= n</code></li>
<li><code>targetIndices</code> is sorted in ascending order.</li>
<li>The input is generated such that <code>targetIndices</code> contains distinct elements in the range <code>[0, n - 1]</code>.</li>
<li><code>source</code> and <code>pattern</code> consist only of lowercase English letters.</li>
<li>The input is generated such that <code>pattern</code> appears as a subsequence in <code>source</code>.</li>
</ul>
|
Array; Hash Table; Two Pointers; String; Dynamic Programming
|
Go
|
func maxRemovals(source string, pattern string, targetIndices []int) int {
m, n := len(source), len(pattern)
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
for j := range f[i] {
f[i][j] = -math.MaxInt32 / 2
}
}
f[0][0] = 0
s := make([]int, m)
for _, i := range targetIndices {
s[i] = 1
}
for i := 1; i <= m; i++ {
for j := 0; j <= n; j++ {
f[i][j] = f[i-1][j] + s[i-1]
if j > 0 && source[i-1] == pattern[j-1] {
f[i][j] = max(f[i][j], f[i-1][j-1])
}
}
}
return f[m][n]
}
|
3,316
|
Find Maximum Removals From Source String
|
Medium
|
<p>You are given a string <code>source</code> of size <code>n</code>, a string <code>pattern</code> that is a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code>, and a <strong>sorted</strong> integer array <code>targetIndices</code> that contains <strong>distinct</strong> numbers in the range <code>[0, n - 1]</code>.</p>
<p>We define an <strong>operation</strong> as removing a character at an index <code>idx</code> from <code>source</code> such that:</p>
<ul>
<li><code>idx</code> is an element of <code>targetIndices</code>.</li>
<li><code>pattern</code> remains a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code> after removing the character.</li>
</ul>
<p>Performing an operation <strong>does not</strong> change the indices of the other characters in <code>source</code>. For example, if you remove <code>'c'</code> from <code>"acb"</code>, the character at index 2 would still be <code>'b'</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>operations</em> that can be performed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "abbaa", pattern = "aba", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>We can't remove <code>source[0]</code> but we can do either of these two operations:</p>
<ul>
<li>Remove <code>source[1]</code>, so that <code>source</code> becomes <code>"a_baa"</code>.</li>
<li>Remove <code>source[2]</code>, so that <code>source</code> becomes <code>"ab_aa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "bcda", pattern = "d", </span>targetIndices<span class="example-io"> = [0,3]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[0]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "dda", pattern = "dda", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We can't remove any character from <code>source</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = </span>"yeyeykyded"<span class="example-io">, pattern = </span>"yeyyd"<span class="example-io">, </span>targetIndices<span class="example-io"> = </span>[0,2,3,4]</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[2]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == source.length <= 3 * 10<sup>3</sup></code></li>
<li><code>1 <= pattern.length <= n</code></li>
<li><code>1 <= targetIndices.length <= n</code></li>
<li><code>targetIndices</code> is sorted in ascending order.</li>
<li>The input is generated such that <code>targetIndices</code> contains distinct elements in the range <code>[0, n - 1]</code>.</li>
<li><code>source</code> and <code>pattern</code> consist only of lowercase English letters.</li>
<li>The input is generated such that <code>pattern</code> appears as a subsequence in <code>source</code>.</li>
</ul>
|
Array; Hash Table; Two Pointers; String; Dynamic Programming
|
Java
|
class Solution {
public int maxRemovals(String source, String pattern, int[] targetIndices) {
int m = source.length(), n = pattern.length();
int[][] f = new int[m + 1][n + 1];
final int inf = Integer.MAX_VALUE / 2;
for (var g : f) {
Arrays.fill(g, -inf);
}
f[0][0] = 0;
int[] s = new int[m];
for (int i : targetIndices) {
s[i] = 1;
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j] + s[i - 1];
if (j > 0 && source.charAt(i - 1) == pattern.charAt(j - 1)) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - 1]);
}
}
}
return f[m][n];
}
}
|
3,316
|
Find Maximum Removals From Source String
|
Medium
|
<p>You are given a string <code>source</code> of size <code>n</code>, a string <code>pattern</code> that is a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code>, and a <strong>sorted</strong> integer array <code>targetIndices</code> that contains <strong>distinct</strong> numbers in the range <code>[0, n - 1]</code>.</p>
<p>We define an <strong>operation</strong> as removing a character at an index <code>idx</code> from <code>source</code> such that:</p>
<ul>
<li><code>idx</code> is an element of <code>targetIndices</code>.</li>
<li><code>pattern</code> remains a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code> after removing the character.</li>
</ul>
<p>Performing an operation <strong>does not</strong> change the indices of the other characters in <code>source</code>. For example, if you remove <code>'c'</code> from <code>"acb"</code>, the character at index 2 would still be <code>'b'</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>operations</em> that can be performed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "abbaa", pattern = "aba", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>We can't remove <code>source[0]</code> but we can do either of these two operations:</p>
<ul>
<li>Remove <code>source[1]</code>, so that <code>source</code> becomes <code>"a_baa"</code>.</li>
<li>Remove <code>source[2]</code>, so that <code>source</code> becomes <code>"ab_aa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "bcda", pattern = "d", </span>targetIndices<span class="example-io"> = [0,3]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[0]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "dda", pattern = "dda", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We can't remove any character from <code>source</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = </span>"yeyeykyded"<span class="example-io">, pattern = </span>"yeyyd"<span class="example-io">, </span>targetIndices<span class="example-io"> = </span>[0,2,3,4]</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[2]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == source.length <= 3 * 10<sup>3</sup></code></li>
<li><code>1 <= pattern.length <= n</code></li>
<li><code>1 <= targetIndices.length <= n</code></li>
<li><code>targetIndices</code> is sorted in ascending order.</li>
<li>The input is generated such that <code>targetIndices</code> contains distinct elements in the range <code>[0, n - 1]</code>.</li>
<li><code>source</code> and <code>pattern</code> consist only of lowercase English letters.</li>
<li>The input is generated such that <code>pattern</code> appears as a subsequence in <code>source</code>.</li>
</ul>
|
Array; Hash Table; Two Pointers; String; Dynamic Programming
|
Python
|
class Solution:
def maxRemovals(self, source: str, pattern: str, targetIndices: List[int]) -> int:
m, n = len(source), len(pattern)
f = [[-inf] * (n + 1) for _ in range(m + 1)]
f[0][0] = 0
s = set(targetIndices)
for i, c in enumerate(source, 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j] + int((i - 1) in s)
if j and c == pattern[j - 1]:
f[i][j] = max(f[i][j], f[i - 1][j - 1])
return f[m][n]
|
3,316
|
Find Maximum Removals From Source String
|
Medium
|
<p>You are given a string <code>source</code> of size <code>n</code>, a string <code>pattern</code> that is a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code>, and a <strong>sorted</strong> integer array <code>targetIndices</code> that contains <strong>distinct</strong> numbers in the range <code>[0, n - 1]</code>.</p>
<p>We define an <strong>operation</strong> as removing a character at an index <code>idx</code> from <code>source</code> such that:</p>
<ul>
<li><code>idx</code> is an element of <code>targetIndices</code>.</li>
<li><code>pattern</code> remains a <span data-keyword="subsequence-string">subsequence</span> of <code>source</code> after removing the character.</li>
</ul>
<p>Performing an operation <strong>does not</strong> change the indices of the other characters in <code>source</code>. For example, if you remove <code>'c'</code> from <code>"acb"</code>, the character at index 2 would still be <code>'b'</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>operations</em> that can be performed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "abbaa", pattern = "aba", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>We can't remove <code>source[0]</code> but we can do either of these two operations:</p>
<ul>
<li>Remove <code>source[1]</code>, so that <code>source</code> becomes <code>"a_baa"</code>.</li>
<li>Remove <code>source[2]</code>, so that <code>source</code> becomes <code>"ab_aa"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "bcda", pattern = "d", </span>targetIndices<span class="example-io"> = [0,3]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[0]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = "dda", pattern = "dda", </span>targetIndices<span class="example-io"> = [0,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We can't remove any character from <code>source</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">source = </span>"yeyeykyded"<span class="example-io">, pattern = </span>"yeyyd"<span class="example-io">, </span>targetIndices<span class="example-io"> = </span>[0,2,3,4]</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<p>We can remove <code>source[2]</code> and <code>source[3]</code> in two operations.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == source.length <= 3 * 10<sup>3</sup></code></li>
<li><code>1 <= pattern.length <= n</code></li>
<li><code>1 <= targetIndices.length <= n</code></li>
<li><code>targetIndices</code> is sorted in ascending order.</li>
<li>The input is generated such that <code>targetIndices</code> contains distinct elements in the range <code>[0, n - 1]</code>.</li>
<li><code>source</code> and <code>pattern</code> consist only of lowercase English letters.</li>
<li>The input is generated such that <code>pattern</code> appears as a subsequence in <code>source</code>.</li>
</ul>
|
Array; Hash Table; Two Pointers; String; Dynamic Programming
|
TypeScript
|
function maxRemovals(source: string, pattern: string, targetIndices: number[]): number {
const m = source.length;
const n = pattern.length;
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-Infinity));
f[0][0] = 0;
const s = Array(m).fill(0);
for (const i of targetIndices) {
s[i] = 1;
}
for (let i = 1; i <= m; i++) {
for (let j = 0; j <= n; j++) {
f[i][j] = f[i - 1][j] + s[i - 1];
if (j > 0 && source[i - 1] === pattern[j - 1]) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - 1]);
}
}
}
return f[m][n];
}
|
3,317
|
Find the Number of Possible Ways for an Event
|
Hard
|
<p>You are given three integers <code>n</code>, <code>x</code>, and <code>y</code>.</p>
<p>An event is being held for <code>n</code> performers. When a performer arrives, they are <strong>assigned</strong> to one of the <code>x</code> stages. All performers assigned to the <strong>same</strong> stage will perform together as a band, though some stages <em>might</em> remain <strong>empty</strong>.</p>
<p>After all performances are completed, the jury will <strong>award</strong> each band a score in the range <code>[1, y]</code>.</p>
<p>Return the <strong>total</strong> number of possible ways the event can take place.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that two events are considered to have been held <strong>differently</strong> if <strong>either</strong> of the following conditions is satisfied:</p>
<ul>
<li><strong>Any</strong> performer is <em>assigned</em> a different stage.</li>
<li><strong>Any</strong> band is <em>awarded</em> a different score.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, x = 2, y = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 2 ways to assign a stage to the performer.</li>
<li>The jury can award a score of either 1, 2, or 3 to the only band.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, x = 2, y = 1</span></p>
<p><strong>Output:</strong> 32</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Each performer will be assigned either stage 1 or stage 2.</li>
<li>All bands will be awarded a score of 1.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 3, y = 4</span></p>
<p><strong>Output:</strong> 684</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x, y <= 1000</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
C++
|
class Solution {
public:
int numberOfWays(int n, int x, int y) {
const int mod = 1e9 + 7;
long long f[n + 1][x + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= x; ++j) {
f[i][j] = (f[i - 1][j] * j % mod + f[i - 1][j - 1] * (x - (j - 1) % mod)) % mod;
}
}
long long ans = 0, p = 1;
for (int j = 1; j <= x; ++j) {
p = p * y % mod;
ans = (ans + f[n][j] * p) % mod;
}
return ans;
}
};
|
3,317
|
Find the Number of Possible Ways for an Event
|
Hard
|
<p>You are given three integers <code>n</code>, <code>x</code>, and <code>y</code>.</p>
<p>An event is being held for <code>n</code> performers. When a performer arrives, they are <strong>assigned</strong> to one of the <code>x</code> stages. All performers assigned to the <strong>same</strong> stage will perform together as a band, though some stages <em>might</em> remain <strong>empty</strong>.</p>
<p>After all performances are completed, the jury will <strong>award</strong> each band a score in the range <code>[1, y]</code>.</p>
<p>Return the <strong>total</strong> number of possible ways the event can take place.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that two events are considered to have been held <strong>differently</strong> if <strong>either</strong> of the following conditions is satisfied:</p>
<ul>
<li><strong>Any</strong> performer is <em>assigned</em> a different stage.</li>
<li><strong>Any</strong> band is <em>awarded</em> a different score.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, x = 2, y = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 2 ways to assign a stage to the performer.</li>
<li>The jury can award a score of either 1, 2, or 3 to the only band.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, x = 2, y = 1</span></p>
<p><strong>Output:</strong> 32</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Each performer will be assigned either stage 1 or stage 2.</li>
<li>All bands will be awarded a score of 1.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 3, y = 4</span></p>
<p><strong>Output:</strong> 684</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x, y <= 1000</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Go
|
func numberOfWays(n int, x int, y int) int {
const mod int = 1e9 + 7
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, x+1)
}
f[0][0] = 1
for i := 1; i <= n; i++ {
for j := 1; j <= x; j++ {
f[i][j] = (f[i-1][j]*j%mod + f[i-1][j-1]*(x-(j-1))%mod) % mod
}
}
ans, p := 0, 1
for j := 1; j <= x; j++ {
p = p * y % mod
ans = (ans + f[n][j]*p%mod) % mod
}
return ans
}
|
3,317
|
Find the Number of Possible Ways for an Event
|
Hard
|
<p>You are given three integers <code>n</code>, <code>x</code>, and <code>y</code>.</p>
<p>An event is being held for <code>n</code> performers. When a performer arrives, they are <strong>assigned</strong> to one of the <code>x</code> stages. All performers assigned to the <strong>same</strong> stage will perform together as a band, though some stages <em>might</em> remain <strong>empty</strong>.</p>
<p>After all performances are completed, the jury will <strong>award</strong> each band a score in the range <code>[1, y]</code>.</p>
<p>Return the <strong>total</strong> number of possible ways the event can take place.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that two events are considered to have been held <strong>differently</strong> if <strong>either</strong> of the following conditions is satisfied:</p>
<ul>
<li><strong>Any</strong> performer is <em>assigned</em> a different stage.</li>
<li><strong>Any</strong> band is <em>awarded</em> a different score.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, x = 2, y = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 2 ways to assign a stage to the performer.</li>
<li>The jury can award a score of either 1, 2, or 3 to the only band.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, x = 2, y = 1</span></p>
<p><strong>Output:</strong> 32</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Each performer will be assigned either stage 1 or stage 2.</li>
<li>All bands will be awarded a score of 1.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 3, y = 4</span></p>
<p><strong>Output:</strong> 684</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x, y <= 1000</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Java
|
class Solution {
public int numberOfWays(int n, int x, int y) {
final int mod = (int) 1e9 + 7;
long[][] f = new long[n + 1][x + 1];
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= x; ++j) {
f[i][j] = (f[i - 1][j] * j % mod + f[i - 1][j - 1] * (x - (j - 1) % mod)) % mod;
}
}
long ans = 0, p = 1;
for (int j = 1; j <= x; ++j) {
p = p * y % mod;
ans = (ans + f[n][j] * p) % mod;
}
return (int) ans;
}
}
|
3,317
|
Find the Number of Possible Ways for an Event
|
Hard
|
<p>You are given three integers <code>n</code>, <code>x</code>, and <code>y</code>.</p>
<p>An event is being held for <code>n</code> performers. When a performer arrives, they are <strong>assigned</strong> to one of the <code>x</code> stages. All performers assigned to the <strong>same</strong> stage will perform together as a band, though some stages <em>might</em> remain <strong>empty</strong>.</p>
<p>After all performances are completed, the jury will <strong>award</strong> each band a score in the range <code>[1, y]</code>.</p>
<p>Return the <strong>total</strong> number of possible ways the event can take place.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that two events are considered to have been held <strong>differently</strong> if <strong>either</strong> of the following conditions is satisfied:</p>
<ul>
<li><strong>Any</strong> performer is <em>assigned</em> a different stage.</li>
<li><strong>Any</strong> band is <em>awarded</em> a different score.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, x = 2, y = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 2 ways to assign a stage to the performer.</li>
<li>The jury can award a score of either 1, 2, or 3 to the only band.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, x = 2, y = 1</span></p>
<p><strong>Output:</strong> 32</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Each performer will be assigned either stage 1 or stage 2.</li>
<li>All bands will be awarded a score of 1.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 3, y = 4</span></p>
<p><strong>Output:</strong> 684</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x, y <= 1000</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def numberOfWays(self, n: int, x: int, y: int) -> int:
mod = 10**9 + 7
f = [[0] * (x + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, x + 1):
f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1] * (x - (j - 1))) % mod
ans, p = 0, 1
for j in range(1, x + 1):
p = p * y % mod
ans = (ans + f[n][j] * p) % mod
return ans
|
3,317
|
Find the Number of Possible Ways for an Event
|
Hard
|
<p>You are given three integers <code>n</code>, <code>x</code>, and <code>y</code>.</p>
<p>An event is being held for <code>n</code> performers. When a performer arrives, they are <strong>assigned</strong> to one of the <code>x</code> stages. All performers assigned to the <strong>same</strong> stage will perform together as a band, though some stages <em>might</em> remain <strong>empty</strong>.</p>
<p>After all performances are completed, the jury will <strong>award</strong> each band a score in the range <code>[1, y]</code>.</p>
<p>Return the <strong>total</strong> number of possible ways the event can take place.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that two events are considered to have been held <strong>differently</strong> if <strong>either</strong> of the following conditions is satisfied:</p>
<ul>
<li><strong>Any</strong> performer is <em>assigned</em> a different stage.</li>
<li><strong>Any</strong> band is <em>awarded</em> a different score.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, x = 2, y = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 2 ways to assign a stage to the performer.</li>
<li>The jury can award a score of either 1, 2, or 3 to the only band.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, x = 2, y = 1</span></p>
<p><strong>Output:</strong> 32</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Each performer will be assigned either stage 1 or stage 2.</li>
<li>All bands will be awarded a score of 1.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 3, y = 4</span></p>
<p><strong>Output:</strong> 684</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x, y <= 1000</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
TypeScript
|
function numberOfWays(n: number, x: number, y: number): number {
const mod = BigInt(10 ** 9 + 7);
const f: bigint[][] = Array.from({ length: n + 1 }, () => Array(x + 1).fill(0n));
f[0][0] = 1n;
for (let i = 1; i <= n; ++i) {
for (let j = 1; j <= x; ++j) {
f[i][j] = (f[i - 1][j] * BigInt(j) + f[i - 1][j - 1] * BigInt(x - (j - 1))) % mod;
}
}
let [ans, p] = [0n, 1n];
for (let j = 1; j <= x; ++j) {
p = (p * BigInt(y)) % mod;
ans = (ans + f[n][j] * p) % mod;
}
return Number(ans);
}
|
3,318
|
Find X-Sum of All K-Long Subarrays I
|
Easy
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<int> findXSum(vector<int>& nums, int k, int x) {
using pii = pair<int, int>;
set<pii> l, r;
int s = 0;
unordered_map<int, int> cnt;
auto add = [&](int v) {
if (cnt[v] == 0) {
return;
}
pii p = {cnt[v], v};
if (!l.empty() && p > *l.begin()) {
s += p.first * p.second;
l.insert(p);
} else {
r.insert(p);
}
};
auto remove = [&](int v) {
if (cnt[v] == 0) {
return;
}
pii p = {cnt[v], v};
auto it = l.find(p);
if (it != l.end()) {
s -= p.first * p.second;
l.erase(it);
} else {
r.erase(p);
}
};
vector<int> ans;
for (int i = 0; i < nums.size(); ++i) {
remove(nums[i]);
++cnt[nums[i]];
add(nums[i]);
int j = i - k + 1;
if (j < 0) {
continue;
}
while (!r.empty() && l.size() < x) {
pii p = *r.rbegin();
s += p.first * p.second;
r.erase(p);
l.insert(p);
}
while (l.size() > x) {
pii p = *l.begin();
s -= p.first * p.second;
l.erase(p);
r.insert(p);
}
ans.push_back(s);
remove(nums[j]);
--cnt[nums[j]];
add(nums[j]);
}
return ans;
}
};
|
3,318
|
Find X-Sum of All K-Long Subarrays I
|
Easy
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Java
|
class Solution {
private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
private TreeSet<int[]> r = new TreeSet<>(l.comparator());
private Map<Integer, Integer> cnt = new HashMap<>();
private int s;
public int[] findXSum(int[] nums, int k, int x) {
int n = nums.length;
int[] ans = new int[n - k + 1];
for (int i = 0; i < n; ++i) {
int v = nums[i];
remove(v);
cnt.merge(v, 1, Integer::sum);
add(v);
int j = i - k + 1;
if (j < 0) {
continue;
}
while (!r.isEmpty() && l.size() < x) {
var p = r.pollLast();
s += p[0] * p[1];
l.add(p);
}
while (l.size() > x) {
var p = l.pollFirst();
s -= p[0] * p[1];
r.add(p);
}
ans[j] = s;
remove(nums[j]);
cnt.merge(nums[j], -1, Integer::sum);
add(nums[j]);
}
return ans;
}
private void remove(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (l.contains(p)) {
l.remove(p);
s -= p[0] * p[1];
} else {
r.remove(p);
}
}
private void add(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
l.add(p);
s += p[0] * p[1];
} else {
r.add(p);
}
}
}
|
3,318
|
Find X-Sum of All K-Long Subarrays I
|
Easy
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Python
|
class Solution:
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
def add(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if l and p > l[0]:
nonlocal s
s += p[0] * p[1]
l.add(p)
else:
r.add(p)
def remove(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if p in l:
nonlocal s
s -= p[0] * p[1]
l.remove(p)
else:
r.remove(p)
l = SortedList()
r = SortedList()
cnt = Counter()
s = 0
n = len(nums)
ans = [0] * (n - k + 1)
for i, v in enumerate(nums):
remove(v)
cnt[v] += 1
add(v)
j = i - k + 1
if j < 0:
continue
while r and len(l) < x:
p = r.pop()
l.add(p)
s += p[0] * p[1]
while len(l) > x:
p = l.pop(0)
s -= p[0] * p[1]
r.add(p)
ans[j] = s
remove(nums[j])
cnt[nums[j]] -= 1
add(nums[j])
return ans
|
3,319
|
K-th Largest Perfect Subtree Size in Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p>
<p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn't exist.</p>
<p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p>
<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br />
The <code>2<sup>nd</sup></code> largest size is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li>
<li><code>1 <= Node.val <= 2000</code></li>
<li><code>1 <= k <= 1024</code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; Sorting
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int kthLargestPerfectSubtree(TreeNode* root, int k) {
vector<int> nums;
auto dfs = [&](this auto&& dfs, TreeNode* root) -> int {
if (!root) {
return 0;
}
int l = dfs(root->left);
int r = dfs(root->right);
if (l < 0 || l != r) {
return -1;
}
int cnt = l + r + 1;
nums.push_back(cnt);
return cnt;
};
dfs(root);
if (nums.size() < k) {
return -1;
}
ranges::sort(nums, greater<int>());
return nums[k - 1];
}
};
|
3,319
|
K-th Largest Perfect Subtree Size in Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p>
<p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn't exist.</p>
<p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p>
<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br />
The <code>2<sup>nd</sup></code> largest size is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li>
<li><code>1 <= Node.val <= 2000</code></li>
<li><code>1 <= k <= 1024</code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; Sorting
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargestPerfectSubtree(root *TreeNode, k int) int {
nums := []int{}
var dfs func(*TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
l, r := dfs(root.Left), dfs(root.Right)
if l < 0 || l != r {
return -1
}
cnt := l + r + 1
nums = append(nums, cnt)
return cnt
}
dfs(root)
if len(nums) < k {
return -1
}
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
return nums[k-1]
}
|
3,319
|
K-th Largest Perfect Subtree Size in Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p>
<p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn't exist.</p>
<p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p>
<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br />
The <code>2<sup>nd</sup></code> largest size is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li>
<li><code>1 <= Node.val <= 2000</code></li>
<li><code>1 <= k <= 1024</code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; Sorting
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> nums = new ArrayList<>();
public int kthLargestPerfectSubtree(TreeNode root, int k) {
dfs(root);
if (nums.size() < k) {
return -1;
}
nums.sort(Comparator.reverseOrder());
return nums.get(k - 1);
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int l = dfs(root.left);
int r = dfs(root.right);
if (l < 0 || l != r) {
return -1;
}
int cnt = l + r + 1;
nums.add(cnt);
return cnt;
}
}
|
3,319
|
K-th Largest Perfect Subtree Size in Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p>
<p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn't exist.</p>
<p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p>
<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br />
The <code>2<sup>nd</sup></code> largest size is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li>
<li><code>1 <= Node.val <= 2000</code></li>
<li><code>1 <= k <= 1024</code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; Sorting
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
if l < 0 or l != r:
return -1
cnt = l + r + 1
nums.append(cnt)
return cnt
nums = []
dfs(root)
if len(nums) < k:
return -1
nums.sort(reverse=True)
return nums[k - 1]
|
3,319
|
K-th Largest Perfect Subtree Size in Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p>
<p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn't exist.</p>
<p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p>
<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br />
The <code>2<sup>nd</sup></code> largest size is 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p>
<p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li>
<li><code>1 <= Node.val <= 2000</code></li>
<li><code>1 <= k <= 1024</code></li>
</ul>
|
Tree; Depth-First Search; Binary Tree; Sorting
|
TypeScript
|
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function kthLargestPerfectSubtree(root: TreeNode | null, k: number): number {
const nums: number[] = [];
const dfs = (root: TreeNode | null): number => {
if (!root) {
return 0;
}
const l = dfs(root.left);
const r = dfs(root.right);
if (l < 0 || l !== r) {
return -1;
}
const cnt = l + r + 1;
nums.push(cnt);
return cnt;
};
dfs(root);
if (nums.length < k) {
return -1;
}
return nums.sort((a, b) => b - a)[k - 1];
}
|
3,320
|
Count The Number of Winning Sequences
|
Hard
|
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p>
<ul>
<li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li>
<li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li>
<li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li>
<li>If both players summon the same creature, no player is awarded a point.</li>
</ul>
<p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>'F'</code>, <code>'W'</code>, and <code>'E'</code>, representing the sequence of creatures Alice will summon in each round:</p>
<ul>
<li>If <code>s[i] == 'F'</code>, Alice summons a Fire Dragon.</li>
<li>If <code>s[i] == 'W'</code>, Alice summons a Water Serpent.</li>
<li>If <code>s[i] == 'E'</code>, Alice summons an Earth Golem.</li>
</ul>
<p>Bob’s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p>
<p>Return the number of distinct sequences Bob can use to beat Alice.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FFF"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Bob can beat Alice by making one of the following sequences of moves: <code>"WFW"</code>, <code>"FWF"</code>, or <code>"WEW"</code>. Note that other winning sequences like <code>"WWE"</code> or <code>"EWW"</code> are invalid since Bob cannot make the same move twice in a row.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FWEFW"</span></p>
<p><strong>Output:</strong> <span class="example-io">18</span></p>
<p><strong>Explanation:</strong></p>
<p><w>Bob can beat Alice by making one of the following sequences of moves: <code>"FWFWF"</code>, <code>"FWFWE"</code>, <code>"FWEFE"</code>, <code>"FWEWE"</code>, <code>"FEFWF"</code>, <code>"FEFWE"</code>, <code>"FEFEW"</code>, <code>"FEWFE"</code>, <code>"WFEFE"</code>, <code>"WFEWE"</code>, <code>"WEFWF"</code>, <code>"WEFWE"</code>, <code>"WEFEF"</code>, <code>"WEFEW"</code>, <code>"WEWFW"</code>, <code>"WEWFE"</code>, <code>"EWFWE"</code>, or <code>"EWEWE"</code>.</w></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s[i]</code> is one of <code>'F'</code>, <code>'W'</code>, or <code>'E'</code>.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int countWinningSequences(string s) {
int n = s.size();
int d[26]{};
d['W' - 'A'] = 1;
d['E' - 'A'] = 2;
int f[n][n + n + 1][4];
memset(f, -1, sizeof(f));
auto calc = [](int x, int y) -> int {
if (x == y) {
return 0;
}
if (x < y) {
return x == 0 && y == 2 ? 1 : -1;
}
return x == 2 && y == 0 ? -1 : 1;
};
const int mod = 1e9 + 7;
auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return j - n < 0 ? 1 : 0;
}
if (f[i][j][k] != -1) {
return f[i][j][k];
}
int ans = 0;
for (int l = 0; l < 3; ++l) {
if (l == k) {
continue;
}
ans = (ans + dfs(i + 1, j + calc(d[s[i] - 'A'], l), l)) % mod;
}
return f[i][j][k] = ans;
};
return dfs(0, n, 3);
}
};
|
3,320
|
Count The Number of Winning Sequences
|
Hard
|
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p>
<ul>
<li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li>
<li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li>
<li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li>
<li>If both players summon the same creature, no player is awarded a point.</li>
</ul>
<p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>'F'</code>, <code>'W'</code>, and <code>'E'</code>, representing the sequence of creatures Alice will summon in each round:</p>
<ul>
<li>If <code>s[i] == 'F'</code>, Alice summons a Fire Dragon.</li>
<li>If <code>s[i] == 'W'</code>, Alice summons a Water Serpent.</li>
<li>If <code>s[i] == 'E'</code>, Alice summons an Earth Golem.</li>
</ul>
<p>Bob’s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p>
<p>Return the number of distinct sequences Bob can use to beat Alice.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FFF"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Bob can beat Alice by making one of the following sequences of moves: <code>"WFW"</code>, <code>"FWF"</code>, or <code>"WEW"</code>. Note that other winning sequences like <code>"WWE"</code> or <code>"EWW"</code> are invalid since Bob cannot make the same move twice in a row.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FWEFW"</span></p>
<p><strong>Output:</strong> <span class="example-io">18</span></p>
<p><strong>Explanation:</strong></p>
<p><w>Bob can beat Alice by making one of the following sequences of moves: <code>"FWFWF"</code>, <code>"FWFWE"</code>, <code>"FWEFE"</code>, <code>"FWEWE"</code>, <code>"FEFWF"</code>, <code>"FEFWE"</code>, <code>"FEFEW"</code>, <code>"FEWFE"</code>, <code>"WFEFE"</code>, <code>"WFEWE"</code>, <code>"WEFWF"</code>, <code>"WEFWE"</code>, <code>"WEFEF"</code>, <code>"WEFEW"</code>, <code>"WEWFW"</code>, <code>"WEWFE"</code>, <code>"EWFWE"</code>, or <code>"EWEWE"</code>.</w></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s[i]</code> is one of <code>'F'</code>, <code>'W'</code>, or <code>'E'</code>.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func countWinningSequences(s string) int {
const mod int = 1e9 + 7
d := [26]int{}
d['W'-'A'] = 1
d['E'-'A'] = 2
n := len(s)
f := make([][][4]int, n)
for i := range f {
f[i] = make([][4]int, n+n+1)
for j := range f[i] {
for k := range f[i][j] {
f[i][j][k] = -1
}
}
}
calc := func(x, y int) int {
if x == y {
return 0
}
if x < y {
if x == 0 && y == 2 {
return 1
}
return -1
}
if x == 2 && y == 0 {
return -1
}
return 1
}
var dfs func(int, int, int) int
dfs = func(i, j, k int) int {
if n-i <= j-n {
return 0
}
if i >= n {
if j-n < 0 {
return 1
}
return 0
}
if v := f[i][j][k]; v != -1 {
return v
}
ans := 0
for l := 0; l < 3; l++ {
if l == k {
continue
}
ans = (ans + dfs(i+1, j+calc(d[s[i]-'A'], l), l)) % mod
}
f[i][j][k] = ans
return ans
}
return dfs(0, n, 3)
}
|
3,320
|
Count The Number of Winning Sequences
|
Hard
|
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p>
<ul>
<li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li>
<li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li>
<li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li>
<li>If both players summon the same creature, no player is awarded a point.</li>
</ul>
<p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>'F'</code>, <code>'W'</code>, and <code>'E'</code>, representing the sequence of creatures Alice will summon in each round:</p>
<ul>
<li>If <code>s[i] == 'F'</code>, Alice summons a Fire Dragon.</li>
<li>If <code>s[i] == 'W'</code>, Alice summons a Water Serpent.</li>
<li>If <code>s[i] == 'E'</code>, Alice summons an Earth Golem.</li>
</ul>
<p>Bob’s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p>
<p>Return the number of distinct sequences Bob can use to beat Alice.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FFF"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Bob can beat Alice by making one of the following sequences of moves: <code>"WFW"</code>, <code>"FWF"</code>, or <code>"WEW"</code>. Note that other winning sequences like <code>"WWE"</code> or <code>"EWW"</code> are invalid since Bob cannot make the same move twice in a row.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FWEFW"</span></p>
<p><strong>Output:</strong> <span class="example-io">18</span></p>
<p><strong>Explanation:</strong></p>
<p><w>Bob can beat Alice by making one of the following sequences of moves: <code>"FWFWF"</code>, <code>"FWFWE"</code>, <code>"FWEFE"</code>, <code>"FWEWE"</code>, <code>"FEFWF"</code>, <code>"FEFWE"</code>, <code>"FEFEW"</code>, <code>"FEWFE"</code>, <code>"WFEFE"</code>, <code>"WFEWE"</code>, <code>"WEFWF"</code>, <code>"WEFWE"</code>, <code>"WEFEF"</code>, <code>"WEFEW"</code>, <code>"WEWFW"</code>, <code>"WEWFE"</code>, <code>"EWFWE"</code>, or <code>"EWEWE"</code>.</w></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s[i]</code> is one of <code>'F'</code>, <code>'W'</code>, or <code>'E'</code>.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
private int n;
private char[] s;
private int[] d = new int[26];
private Integer[][][] f;
private final int mod = (int) 1e9 + 7;
public int countWinningSequences(String s) {
d['W' - 'A'] = 1;
d['E' - 'A'] = 2;
this.s = s.toCharArray();
n = this.s.length;
f = new Integer[n][n + n + 1][4];
return dfs(0, n, 3);
}
private int dfs(int i, int j, int k) {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return j - n < 0 ? 1 : 0;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int ans = 0;
for (int l = 0; l < 3; ++l) {
if (l == k) {
continue;
}
ans = (ans + dfs(i + 1, j + calc(d[s[i] - 'A'], l), l)) % mod;
}
return f[i][j][k] = ans;
}
private int calc(int x, int y) {
if (x == y) {
return 0;
}
if (x < y) {
return x == 0 && y == 2 ? 1 : -1;
}
return x == 2 && y == 0 ? -1 : 1;
}
}
|
3,320
|
Count The Number of Winning Sequences
|
Hard
|
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p>
<ul>
<li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li>
<li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li>
<li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li>
<li>If both players summon the same creature, no player is awarded a point.</li>
</ul>
<p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>'F'</code>, <code>'W'</code>, and <code>'E'</code>, representing the sequence of creatures Alice will summon in each round:</p>
<ul>
<li>If <code>s[i] == 'F'</code>, Alice summons a Fire Dragon.</li>
<li>If <code>s[i] == 'W'</code>, Alice summons a Water Serpent.</li>
<li>If <code>s[i] == 'E'</code>, Alice summons an Earth Golem.</li>
</ul>
<p>Bob’s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p>
<p>Return the number of distinct sequences Bob can use to beat Alice.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FFF"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Bob can beat Alice by making one of the following sequences of moves: <code>"WFW"</code>, <code>"FWF"</code>, or <code>"WEW"</code>. Note that other winning sequences like <code>"WWE"</code> or <code>"EWW"</code> are invalid since Bob cannot make the same move twice in a row.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "FWEFW"</span></p>
<p><strong>Output:</strong> <span class="example-io">18</span></p>
<p><strong>Explanation:</strong></p>
<p><w>Bob can beat Alice by making one of the following sequences of moves: <code>"FWFWF"</code>, <code>"FWFWE"</code>, <code>"FWEFE"</code>, <code>"FWEWE"</code>, <code>"FEFWF"</code>, <code>"FEFWE"</code>, <code>"FEFEW"</code>, <code>"FEWFE"</code>, <code>"WFEFE"</code>, <code>"WFEWE"</code>, <code>"WEFWF"</code>, <code>"WEFWE"</code>, <code>"WEFEF"</code>, <code>"WEFEW"</code>, <code>"WEWFW"</code>, <code>"WEWFE"</code>, <code>"EWFWE"</code>, or <code>"EWEWE"</code>.</w></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s[i]</code> is one of <code>'F'</code>, <code>'W'</code>, or <code>'E'</code>.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def countWinningSequences(self, s: str) -> int:
def calc(x: int, y: int) -> int:
if x == y:
return 0
if x < y:
return 1 if x == 0 and y == 2 else -1
return -1 if x == 2 and y == 0 else 1
@cache
def dfs(i: int, j: int, k: int) -> int:
if len(s) - i <= j:
return 0
if i >= len(s):
return int(j < 0)
res = 0
for l in range(3):
if l == k:
continue
res = (res + dfs(i + 1, j + calc(d[s[i]], l), l)) % mod
return res
mod = 10**9 + 7
d = {"F": 0, "W": 1, "E": 2}
ans = dfs(0, 0, -1)
dfs.cache_clear()
return ans
|
3,321
|
Find X-Sum of All K-Long Subarrays II
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == n</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<long long> findXSum(vector<int>& nums, int k, int x) {
using pii = pair<int, int>;
set<pii> l, r;
long long s = 0;
unordered_map<int, int> cnt;
auto add = [&](int v) {
if (cnt[v] == 0) {
return;
}
pii p = {cnt[v], v};
if (!l.empty() && p > *l.begin()) {
s += 1LL * p.first * p.second;
l.insert(p);
} else {
r.insert(p);
}
};
auto remove = [&](int v) {
if (cnt[v] == 0) {
return;
}
pii p = {cnt[v], v};
auto it = l.find(p);
if (it != l.end()) {
s -= 1LL * p.first * p.second;
l.erase(it);
} else {
r.erase(p);
}
};
vector<long long> ans;
for (int i = 0; i < nums.size(); ++i) {
remove(nums[i]);
++cnt[nums[i]];
add(nums[i]);
int j = i - k + 1;
if (j < 0) {
continue;
}
while (!r.empty() && l.size() < x) {
pii p = *r.rbegin();
s += 1LL * p.first * p.second;
r.erase(p);
l.insert(p);
}
while (l.size() > x) {
pii p = *l.begin();
s -= 1LL * p.first * p.second;
l.erase(p);
r.insert(p);
}
ans.push_back(s);
remove(nums[j]);
--cnt[nums[j]];
add(nums[j]);
}
return ans;
}
};
|
3,321
|
Find X-Sum of All K-Long Subarrays II
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == n</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Java
|
class Solution {
private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
private TreeSet<int[]> r = new TreeSet<>(l.comparator());
private Map<Integer, Integer> cnt = new HashMap<>();
private long s;
public long[] findXSum(int[] nums, int k, int x) {
int n = nums.length;
long[] ans = new long[n - k + 1];
for (int i = 0; i < n; ++i) {
int v = nums[i];
remove(v);
cnt.merge(v, 1, Integer::sum);
add(v);
int j = i - k + 1;
if (j < 0) {
continue;
}
while (!r.isEmpty() && l.size() < x) {
var p = r.pollLast();
s += 1L * p[0] * p[1];
l.add(p);
}
while (l.size() > x) {
var p = l.pollFirst();
s -= 1L * p[0] * p[1];
r.add(p);
}
ans[j] = s;
remove(nums[j]);
cnt.merge(nums[j], -1, Integer::sum);
add(nums[j]);
}
return ans;
}
private void remove(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (l.contains(p)) {
l.remove(p);
s -= 1L * p[0] * p[1];
} else {
r.remove(p);
}
}
private void add(int v) {
if (!cnt.containsKey(v)) {
return;
}
var p = new int[] {cnt.get(v), v};
if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) {
l.add(p);
s += 1L * p[0] * p[1];
} else {
r.add(p);
}
}
}
|
3,321
|
Find X-Sum of All K-Long Subarrays II
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p>
<p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p>
<ul>
<li>Count the occurrences of all elements in the array.</li>
<li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li>
<li>Calculate the sum of the resulting array.</li>
</ul>
<p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p>
<p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,4,2,3], k = 6, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li>
<li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li>
<li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == n</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table; Sliding Window; Heap (Priority Queue)
|
Python
|
class Solution:
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
def add(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if l and p > l[0]:
nonlocal s
s += p[0] * p[1]
l.add(p)
else:
r.add(p)
def remove(v: int):
if cnt[v] == 0:
return
p = (cnt[v], v)
if p in l:
nonlocal s
s -= p[0] * p[1]
l.remove(p)
else:
r.remove(p)
l = SortedList()
r = SortedList()
cnt = Counter()
s = 0
n = len(nums)
ans = [0] * (n - k + 1)
for i, v in enumerate(nums):
remove(v)
cnt[v] += 1
add(v)
j = i - k + 1
if j < 0:
continue
while r and len(l) < x:
p = r.pop()
l.add(p)
s += p[0] * p[1]
while len(l) > x:
p = l.pop(0)
s -= p[0] * p[1]
r.add(p)
ans[j] = s
remove(nums[j])
cnt[nums[j]] -= 1
add(nums[j])
return ans
|
3,322
|
Premier League Table Ranking III
|
Medium
|
<p>Table: <code>SeasonStats</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| season_id | int |
| team_id | int |
| team_name | varchar |
| matches_played | int |
| wins | int |
| draws | int |
| losses | int |
| goals_for | int |
| goals_against | int |
+------------------+---------+
(season_id, team_id) is the unique key for this table.
This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season.
</pre>
<p>Write a solution to calculate the <strong>points</strong>, <strong>goal difference</strong>, and <b>position </b>for <strong>each team</strong> in <strong>each season</strong>. The position ranking should be determined as follows:</p>
<ul>
<li>Teams are first ranked by their total points (highest to lowest)</li>
<li>If points are tied, teams are then ranked by their goal difference (highest to lowest)</li>
<li>If goal difference is also tied, teams are then ranked alphabetically by team name</li>
</ul>
<p>Points are calculated as follows:</p>
<ul>
<li><code>3</code> points for a <strong>win</strong></li>
<li><code>1</code> point for a <strong>draw</strong></li>
<li><code>0</code> points for a <strong>loss</strong></li>
</ul>
<p>Goal difference is calculated as: <code>goals_for - goals_against</code></p>
<p>Return <em>the result table ordered by</em> <code>season_id</code> <em>in <strong>ascending</strong> order, then by</em> <font face="monospace">position </font><em>in <strong>ascending</strong> order, and finally by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The query result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<p><strong>Input:</strong></p>
<p><code>SeasonStats</code> table:</p>
<pre>
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| season_id | team_id | team_name | matches_played | wins | draws | losses | goals_for | goals_against |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| 2021 | 1 | Manchester City | 38 | 29 | 6 | 3 | 99 | 26 |
| 2021 | 2 | Liverpool | 38 | 28 | 8 | 2 | 94 | 26 |
| 2021 | 3 | Chelsea | 38 | 21 | 11 | 6 | 76 | 33 |
| 2021 | 4 | Tottenham | 38 | 22 | 5 | 11 | 69 | 40 |
| 2021 | 5 | Arsenal | 38 | 22 | 3 | 13 | 61 | 48 |
| 2022 | 1 | Manchester City | 38 | 28 | 5 | 5 | 94 | 33 |
| 2022 | 2 | Arsenal | 38 | 26 | 6 | 6 | 88 | 43 |
| 2022 | 3 | Manchester United | 38 | 23 | 6 | 9 | 58 | 43 |
| 2022 | 4 | Newcastle | 38 | 19 | 14 | 5 | 68 | 33 |
| 2022 | 5 | Liverpool | 38 | 19 | 10 | 9 | 75 | 47 |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
</pre>
<p><strong>Output:</strong></p>
<pre>
+------------+---------+-------------------+--------+-----------------+----------+
| season_id | team_id | team_name | points | goal_difference | position |
+------------+---------+-------------------+--------+-----------------+----------+
| 2021 | 1 | Manchester City | 93 | 73 | 1 |
| 2021 | 2 | Liverpool | 92 | 68 | 2 |
| 2021 | 3 | Chelsea | 74 | 43 | 3 |
| 2021 | 4 | Tottenham | 71 | 29 | 4 |
| 2021 | 5 | Arsenal | 69 | 13 | 5 |
| 2022 | 1 | Manchester City | 89 | 61 | 1 |
| 2022 | 2 | Arsenal | 84 | 45 | 2 |
| 2022 | 3 | Manchester United | 75 | 15 | 3 |
| 2022 | 4 | Newcastle | 71 | 35 | 4 |
| 2022 | 5 | Liverpool | 67 | 28 | 5 |
+------------+---------+-------------------+--------+-----------------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 2021 season:
<ul>
<li>Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).</li>
<li>Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).</li>
<li>Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).</li>
<li>Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).</li>
<li>Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).</li>
</ul>
</li>
<li>For the 2022 season:
<ul>
<li>Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).</li>
<li>Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).</li>
<li>Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).</li>
<li>Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).</li>
<li>Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).</li>
</ul>
</li>
<li>The teams are ranked first by points, then by goal difference, and finally by team name.</li>
<li>The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.</li>
</ul>
|
Database
|
Python
|
import pandas as pd
def process_team_standings(season_stats: pd.DataFrame) -> pd.DataFrame:
season_stats["points"] = season_stats["wins"] * 3 + season_stats["draws"]
season_stats["goal_difference"] = (
season_stats["goals_for"] - season_stats["goals_against"]
)
season_stats = season_stats.sort_values(
["season_id", "points", "goal_difference", "team_name"],
ascending=[True, False, False, True],
)
season_stats["position"] = season_stats.groupby("season_id").cumcount() + 1
return season_stats[
["season_id", "team_id", "team_name", "points", "goal_difference", "position"]
]
|
3,322
|
Premier League Table Ranking III
|
Medium
|
<p>Table: <code>SeasonStats</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| season_id | int |
| team_id | int |
| team_name | varchar |
| matches_played | int |
| wins | int |
| draws | int |
| losses | int |
| goals_for | int |
| goals_against | int |
+------------------+---------+
(season_id, team_id) is the unique key for this table.
This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season.
</pre>
<p>Write a solution to calculate the <strong>points</strong>, <strong>goal difference</strong>, and <b>position </b>for <strong>each team</strong> in <strong>each season</strong>. The position ranking should be determined as follows:</p>
<ul>
<li>Teams are first ranked by their total points (highest to lowest)</li>
<li>If points are tied, teams are then ranked by their goal difference (highest to lowest)</li>
<li>If goal difference is also tied, teams are then ranked alphabetically by team name</li>
</ul>
<p>Points are calculated as follows:</p>
<ul>
<li><code>3</code> points for a <strong>win</strong></li>
<li><code>1</code> point for a <strong>draw</strong></li>
<li><code>0</code> points for a <strong>loss</strong></li>
</ul>
<p>Goal difference is calculated as: <code>goals_for - goals_against</code></p>
<p>Return <em>the result table ordered by</em> <code>season_id</code> <em>in <strong>ascending</strong> order, then by</em> <font face="monospace">position </font><em>in <strong>ascending</strong> order, and finally by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The query result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<p><strong>Input:</strong></p>
<p><code>SeasonStats</code> table:</p>
<pre>
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| season_id | team_id | team_name | matches_played | wins | draws | losses | goals_for | goals_against |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| 2021 | 1 | Manchester City | 38 | 29 | 6 | 3 | 99 | 26 |
| 2021 | 2 | Liverpool | 38 | 28 | 8 | 2 | 94 | 26 |
| 2021 | 3 | Chelsea | 38 | 21 | 11 | 6 | 76 | 33 |
| 2021 | 4 | Tottenham | 38 | 22 | 5 | 11 | 69 | 40 |
| 2021 | 5 | Arsenal | 38 | 22 | 3 | 13 | 61 | 48 |
| 2022 | 1 | Manchester City | 38 | 28 | 5 | 5 | 94 | 33 |
| 2022 | 2 | Arsenal | 38 | 26 | 6 | 6 | 88 | 43 |
| 2022 | 3 | Manchester United | 38 | 23 | 6 | 9 | 58 | 43 |
| 2022 | 4 | Newcastle | 38 | 19 | 14 | 5 | 68 | 33 |
| 2022 | 5 | Liverpool | 38 | 19 | 10 | 9 | 75 | 47 |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
</pre>
<p><strong>Output:</strong></p>
<pre>
+------------+---------+-------------------+--------+-----------------+----------+
| season_id | team_id | team_name | points | goal_difference | position |
+------------+---------+-------------------+--------+-----------------+----------+
| 2021 | 1 | Manchester City | 93 | 73 | 1 |
| 2021 | 2 | Liverpool | 92 | 68 | 2 |
| 2021 | 3 | Chelsea | 74 | 43 | 3 |
| 2021 | 4 | Tottenham | 71 | 29 | 4 |
| 2021 | 5 | Arsenal | 69 | 13 | 5 |
| 2022 | 1 | Manchester City | 89 | 61 | 1 |
| 2022 | 2 | Arsenal | 84 | 45 | 2 |
| 2022 | 3 | Manchester United | 75 | 15 | 3 |
| 2022 | 4 | Newcastle | 71 | 35 | 4 |
| 2022 | 5 | Liverpool | 67 | 28 | 5 |
+------------+---------+-------------------+--------+-----------------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For the 2021 season:
<ul>
<li>Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).</li>
<li>Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).</li>
<li>Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).</li>
<li>Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).</li>
<li>Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).</li>
</ul>
</li>
<li>For the 2022 season:
<ul>
<li>Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).</li>
<li>Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).</li>
<li>Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).</li>
<li>Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).</li>
<li>Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).</li>
</ul>
</li>
<li>The teams are ranked first by points, then by goal difference, and finally by team name.</li>
<li>The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.</li>
</ul>
|
Database
|
SQL
|
SELECT
season_id,
team_id,
team_name,
wins * 3 + draws points,
goals_for - goals_against goal_difference,
RANK() OVER (
PARTITION BY season_id
ORDER BY wins * 3 + draws DESC, goals_for - goals_against DESC, team_name
) position
FROM SeasonStats
ORDER BY 1, 6, 3;
|
3,323
|
Minimize Connected Groups by Inserting Interval
|
Medium
|
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p>
<p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p>
<ul>
<li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li>
<li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li>
</ul>
<p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p>
<ul>
<li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li>
<li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li>
</ul>
<p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>5</sup></code></li>
<li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li>
<li><code>1 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Binary Search; Sorting; Sliding Window
|
C++
|
class Solution {
public:
int minConnectedGroups(vector<vector<int>>& intervals, int k) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
for (const auto& interval : intervals) {
int s = interval[0], e = interval[1];
if (merged.empty() || merged.back()[1] < s) {
merged.emplace_back(interval);
} else {
merged.back()[1] = max(merged.back()[1], e);
}
}
int ans = merged.size();
for (int i = 0; i < merged.size(); ++i) {
auto& interval = merged[i];
int j = lower_bound(merged.begin(), merged.end(), vector<int>{interval[1] + k + 1, 0}) - merged.begin();
ans = min(ans, (int) merged.size() - (j - i - 1));
}
return ans;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.