id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
2,734
|
Lexicographically Smallest String After Substring Operation
|
Medium
|
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p>
<ul>
<li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cbabc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"baabc"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">"az"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the last letter.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "acbbc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abaab"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">"kddsbncd"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the entire string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Greedy; String
|
Go
|
func smallestString(s string) string {
n := len(s)
i := 0
for i < n && s[i] == 'a' {
i++
}
cs := []byte(s)
if i == n {
cs[n-1] = 'z'
return string(cs)
}
j := i
for j < n && cs[j] != 'a' {
cs[j] = cs[j] - 1
j++
}
return string(cs)
}
|
2,734
|
Lexicographically Smallest String After Substring Operation
|
Medium
|
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p>
<ul>
<li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cbabc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"baabc"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">"az"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the last letter.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "acbbc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abaab"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">"kddsbncd"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the entire string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Greedy; String
|
Java
|
class Solution {
public String smallestString(String s) {
int n = s.length();
int i = 0;
while (i < n && s.charAt(i) == 'a') {
++i;
}
if (i == n) {
return s.substring(0, n - 1) + "z";
}
int j = i;
char[] cs = s.toCharArray();
while (j < n && cs[j] != 'a') {
cs[j] = (char) (cs[j] - 1);
++j;
}
return String.valueOf(cs);
}
}
|
2,734
|
Lexicographically Smallest String After Substring Operation
|
Medium
|
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p>
<ul>
<li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cbabc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"baabc"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">"az"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the last letter.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "acbbc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abaab"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">"kddsbncd"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the entire string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Greedy; String
|
Python
|
class Solution:
def smallestString(self, s: str) -> str:
n = len(s)
i = 0
while i < n and s[i] == "a":
i += 1
if i == n:
return s[:-1] + "z"
j = i
while j < n and s[j] != "a":
j += 1
return s[:i] + "".join(chr(ord(c) - 1) for c in s[i:j]) + s[j:]
|
2,734
|
Lexicographically Smallest String After Substring Operation
|
Medium
|
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p>
<ul>
<li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cbabc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"baabc"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">"az"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the last letter.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "acbbc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abaab"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">"kddsbncd"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the entire string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Greedy; String
|
Rust
|
impl Solution {
pub fn smallest_string(s: String) -> String {
let mut cs: Vec<char> = s.chars().collect();
let n = cs.len();
let mut i = 0;
while i < n && cs[i] == 'a' {
i += 1;
}
if i == n {
cs[n - 1] = 'z';
return cs.into_iter().collect();
}
let mut j = i;
while j < n && cs[j] != 'a' {
cs[j] = ((cs[j] as u8) - 1) as char;
j += 1;
}
cs.into_iter().collect()
}
}
|
2,734
|
Lexicographically Smallest String After Substring Operation
|
Medium
|
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p>
<ul>
<li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'.</li>
</ul>
<p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cbabc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"baabc"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">"az"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the last letter.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "acbbc"</span></p>
<p><strong>Output:</strong> <span class="example-io">"abaab"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">"kddsbncd"</span></p>
<p><strong>Explanation:</strong></p>
<p>Perform the operation on the entire string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Greedy; String
|
TypeScript
|
function smallestString(s: string): string {
const cs: string[] = s.split('');
const n: number = cs.length;
let i: number = 0;
while (i < n && cs[i] === 'a') {
i++;
}
if (i === n) {
cs[n - 1] = 'z';
return cs.join('');
}
let j: number = i;
while (j < n && cs[j] !== 'a') {
const c: number = cs[j].charCodeAt(0);
cs[j] = String.fromCharCode(c - 1);
j++;
}
return cs.join('');
}
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
C++
|
class Solution {
public:
long long minCost(vector<int>& nums, int x) {
int n = nums.size();
int f[n][n];
for (int i = 0; i < n; ++i) {
f[i][0] = nums[i];
for (int j = 1; j < n; ++j) {
f[i][j] = min(f[i][j - 1], nums[(i - j + n) % n]);
}
}
long long ans = 1LL << 60;
for (int j = 0; j < n; ++j) {
long long cost = 1LL * x * j;
for (int i = 0; i < n; ++i) {
cost += f[i][j];
}
ans = min(ans, cost);
}
return ans;
}
};
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Go
|
func minCost(nums []int, x int) int64 {
n := len(nums)
f := make([][]int, n)
for i, v := range nums {
f[i] = make([]int, n)
f[i][0] = v
for j := 1; j < n; j++ {
f[i][j] = min(f[i][j-1], nums[(i-j+n)%n])
}
}
ans := 1 << 60
for j := 0; j < n; j++ {
cost := x * j
for i := 0; i < n; i++ {
cost += f[i][j]
}
ans = min(ans, cost)
}
return int64(ans)
}
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Java
|
class Solution {
public long minCost(int[] nums, int x) {
int n = nums.length;
int[][] f = new int[n][n];
for (int i = 0; i < n; ++i) {
f[i][0] = nums[i];
for (int j = 1; j < n; ++j) {
f[i][j] = Math.min(f[i][j - 1], nums[(i - j + n) % n]);
}
}
long ans = 1L << 60;
for (int j = 0; j < n; ++j) {
long cost = 1L * x * j;
for (int i = 0; i < n; ++i) {
cost += f[i][j];
}
ans = Math.min(ans, cost);
}
return ans;
}
}
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Python
|
class Solution:
def minCost(self, nums: List[int], x: int) -> int:
n = len(nums)
f = [[0] * n for _ in range(n)]
for i, v in enumerate(nums):
f[i][0] = v
for j in range(1, n):
f[i][j] = min(f[i][j - 1], nums[(i - j) % n])
return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n))
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Rust
|
impl Solution {
pub fn min_cost(nums: Vec<i32>, x: i32) -> i64 {
let n = nums.len();
let mut f = vec![vec![0; n]; n];
for i in 0..n {
f[i][0] = nums[i];
for j in 1..n {
f[i][j] = f[i][j - 1].min(nums[(i - j + n) % n]);
}
}
let mut ans = i64::MAX;
for j in 0..n {
let mut cost = (x as i64) * (j as i64);
for i in 0..n {
cost += f[i][j] as i64;
}
ans = ans.min(cost);
}
ans
}
}
|
2,735
|
Collecting Chocolates
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index <code>i</code> is <code>nums[i]</code>. Each chocolate is of a different type, and initially, the chocolate at the index <code>i</code> is of <code>i<sup>th</sup></code> type.</p>
<p>In one operation, you can do the following with an incurred <strong>cost</strong> of <code>x</code>:</p>
<ul>
<li>Simultaneously change the chocolate of <code>i<sup>th</sup></code> type to <code>((i + 1) mod n)<sup>th</sup></code> type for all chocolates.</li>
</ul>
<p>Return <em>the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [20,1,15], x = 5
<strong>Output:</strong> 13
<strong>Explanation:</strong> Initially, the chocolate types are [0,1,2]. We will buy the 1<sup>st</sup> type of chocolate at a cost of 1.
Now, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2<sup>nd</sup><sup> </sup>type of chocolate at a cost of 1.
Now, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0<sup>th </sup>type of chocolate at a cost of 1.
Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], x = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= x <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
TypeScript
|
function minCost(nums: number[], x: number): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let i = 0; i < n; ++i) {
f[i][0] = nums[i];
for (let j = 1; j < n; ++j) {
f[i][j] = Math.min(f[i][j - 1], nums[(i - j + n) % n]);
}
}
let ans = Infinity;
for (let j = 0; j < n; ++j) {
let cost = x * j;
for (let i = 0; i < n; ++i) {
cost += f[i][j];
}
ans = Math.min(ans, cost);
}
return ans;
}
|
2,736
|
Maximum Sum Queries
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, each of length <code>n</code>, and a <strong>1-indexed 2D array</strong> <code>queries</code> where <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>For the <code>i<sup>th</sup></code> query, find the <strong>maximum value</strong> of <code>nums1[j] + nums2[j]</code> among all indices <code>j</code> <code>(0 <= j < n)</code>, where <code>nums1[j] >= x<sub>i</sub></code> and <code>nums2[j] >= y<sub>i</sub></code>, or <strong>-1</strong> if there is no <code>j</code> satisfying the constraints.</p>
<p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]
<strong>Output:</strong> [6,10,7]
<strong>Explanation:</strong>
For the 1st query <code node="[object Object]">x<sub>i</sub> = 4</code> and <code node="[object Object]">y<sub>i</sub> = 1</code>, we can select index <code node="[object Object]">j = 0</code> since <code node="[object Object]">nums1[j] >= 4</code> and <code node="[object Object]">nums2[j] >= 1</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 6, and we can show that 6 is the maximum we can obtain.
For the 2nd query <code node="[object Object]">x<sub>i</sub> = 1</code> and <code node="[object Object]">y<sub>i</sub> = 3</code>, we can select index <code node="[object Object]">j = 2</code> since <code node="[object Object]">nums1[j] >= 1</code> and <code node="[object Object]">nums2[j] >= 3</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 10, and we can show that 10 is the maximum we can obtain.
For the 3rd query <code node="[object Object]">x<sub>i</sub> = 2</code> and <code node="[object Object]">y<sub>i</sub> = 5</code>, we can select index <code node="[object Object]">j = 3</code> since <code node="[object Object]">nums1[j] >= 2</code> and <code node="[object Object]">nums2[j] >= 5</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 7, and we can show that 7 is the maximum we can obtain.
Therefore, we return <code node="[object Object]">[6,10,7]</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]
<strong>Output:</strong> [9,9,9]
<strong>Explanation:</strong> For this example, we can use index <code node="[object Object]">j = 2</code> for all the queries since it satisfies the constraints for each query.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> There is one query in this example with <code node="[object Object]">x<sub>i</sub></code> = 3 and <code node="[object Object]">y<sub>i</sub></code> = 3. For every index, j, either nums1[j] < <code node="[object Object]">x<sub>i</sub></code> or nums2[j] < <code node="[object Object]">y<sub>i</sub></code>. Hence, there is no solution.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code> </li>
<li><code>n == nums1.length </code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup> </code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>x<sub>i</sub> == queries[i][1]</code></li>
<li><code>y<sub>i</sub> == queries[i][2]</code></li>
<li><code>1 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>9</sup></code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Sorting; Monotonic Stack
|
C++
|
class BinaryIndexedTree {
private:
int n;
vector<int> c;
public:
BinaryIndexedTree(int n) {
this->n = n;
c.resize(n + 1, -1);
}
void update(int x, int v) {
while (x <= n) {
c[x] = max(c[x], v);
x += x & -x;
}
}
int query(int x) {
int mx = -1;
while (x > 0) {
mx = max(mx, c[x]);
x -= x & -x;
}
return mx;
}
};
class Solution {
public:
vector<int> maximumSumQueries(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) {
vector<pair<int, int>> nums;
int n = nums1.size(), m = queries.size();
for (int i = 0; i < n; ++i) {
nums.emplace_back(-nums1[i], nums2[i]);
}
sort(nums.begin(), nums.end());
sort(nums2.begin(), nums2.end());
vector<int> idx(m);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) { return queries[j][0] < queries[i][0]; });
vector<int> ans(m);
int j = 0;
BinaryIndexedTree tree(n);
for (int i : idx) {
int x = queries[i][0], y = queries[i][1];
for (; j < n && -nums[j].first >= x; ++j) {
int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), nums[j].second);
tree.update(k, -nums[j].first + nums[j].second);
}
int k = nums2.end() - lower_bound(nums2.begin(), nums2.end(), y);
ans[i] = tree.query(k);
}
return ans;
}
};
|
2,736
|
Maximum Sum Queries
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, each of length <code>n</code>, and a <strong>1-indexed 2D array</strong> <code>queries</code> where <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>For the <code>i<sup>th</sup></code> query, find the <strong>maximum value</strong> of <code>nums1[j] + nums2[j]</code> among all indices <code>j</code> <code>(0 <= j < n)</code>, where <code>nums1[j] >= x<sub>i</sub></code> and <code>nums2[j] >= y<sub>i</sub></code>, or <strong>-1</strong> if there is no <code>j</code> satisfying the constraints.</p>
<p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]
<strong>Output:</strong> [6,10,7]
<strong>Explanation:</strong>
For the 1st query <code node="[object Object]">x<sub>i</sub> = 4</code> and <code node="[object Object]">y<sub>i</sub> = 1</code>, we can select index <code node="[object Object]">j = 0</code> since <code node="[object Object]">nums1[j] >= 4</code> and <code node="[object Object]">nums2[j] >= 1</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 6, and we can show that 6 is the maximum we can obtain.
For the 2nd query <code node="[object Object]">x<sub>i</sub> = 1</code> and <code node="[object Object]">y<sub>i</sub> = 3</code>, we can select index <code node="[object Object]">j = 2</code> since <code node="[object Object]">nums1[j] >= 1</code> and <code node="[object Object]">nums2[j] >= 3</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 10, and we can show that 10 is the maximum we can obtain.
For the 3rd query <code node="[object Object]">x<sub>i</sub> = 2</code> and <code node="[object Object]">y<sub>i</sub> = 5</code>, we can select index <code node="[object Object]">j = 3</code> since <code node="[object Object]">nums1[j] >= 2</code> and <code node="[object Object]">nums2[j] >= 5</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 7, and we can show that 7 is the maximum we can obtain.
Therefore, we return <code node="[object Object]">[6,10,7]</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]
<strong>Output:</strong> [9,9,9]
<strong>Explanation:</strong> For this example, we can use index <code node="[object Object]">j = 2</code> for all the queries since it satisfies the constraints for each query.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> There is one query in this example with <code node="[object Object]">x<sub>i</sub></code> = 3 and <code node="[object Object]">y<sub>i</sub></code> = 3. For every index, j, either nums1[j] < <code node="[object Object]">x<sub>i</sub></code> or nums2[j] < <code node="[object Object]">y<sub>i</sub></code>. Hence, there is no solution.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code> </li>
<li><code>n == nums1.length </code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup> </code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>x<sub>i</sub> == queries[i][1]</code></li>
<li><code>y<sub>i</sub> == queries[i][2]</code></li>
<li><code>1 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>9</sup></code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Sorting; Monotonic Stack
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
c := make([]int, n+1)
for i := range c {
c[i] = -1
}
return BinaryIndexedTree{n: n, c: c}
}
func (bit *BinaryIndexedTree) update(x, v int) {
for x <= bit.n {
bit.c[x] = max(bit.c[x], v)
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) int {
mx := -1
for x > 0 {
mx = max(mx, bit.c[x])
x -= x & -x
}
return mx
}
func maximumSumQueries(nums1 []int, nums2 []int, queries [][]int) []int {
n, m := len(nums1), len(queries)
nums := make([][2]int, n)
for i := range nums {
nums[i] = [2]int{nums1[i], nums2[i]}
}
sort.Slice(nums, func(i, j int) bool { return nums[j][0] < nums[i][0] })
sort.Ints(nums2)
idx := make([]int, m)
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(i, j int) bool { return queries[idx[j]][0] < queries[idx[i]][0] })
tree := NewBinaryIndexedTree(n)
ans := make([]int, m)
j := 0
for _, i := range idx {
x, y := queries[i][0], queries[i][1]
for ; j < n && nums[j][0] >= x; j++ {
k := n - sort.SearchInts(nums2, nums[j][1])
tree.update(k, nums[j][0]+nums[j][1])
}
k := n - sort.SearchInts(nums2, y)
ans[i] = tree.query(k)
}
return ans
}
|
2,736
|
Maximum Sum Queries
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, each of length <code>n</code>, and a <strong>1-indexed 2D array</strong> <code>queries</code> where <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>For the <code>i<sup>th</sup></code> query, find the <strong>maximum value</strong> of <code>nums1[j] + nums2[j]</code> among all indices <code>j</code> <code>(0 <= j < n)</code>, where <code>nums1[j] >= x<sub>i</sub></code> and <code>nums2[j] >= y<sub>i</sub></code>, or <strong>-1</strong> if there is no <code>j</code> satisfying the constraints.</p>
<p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]
<strong>Output:</strong> [6,10,7]
<strong>Explanation:</strong>
For the 1st query <code node="[object Object]">x<sub>i</sub> = 4</code> and <code node="[object Object]">y<sub>i</sub> = 1</code>, we can select index <code node="[object Object]">j = 0</code> since <code node="[object Object]">nums1[j] >= 4</code> and <code node="[object Object]">nums2[j] >= 1</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 6, and we can show that 6 is the maximum we can obtain.
For the 2nd query <code node="[object Object]">x<sub>i</sub> = 1</code> and <code node="[object Object]">y<sub>i</sub> = 3</code>, we can select index <code node="[object Object]">j = 2</code> since <code node="[object Object]">nums1[j] >= 1</code> and <code node="[object Object]">nums2[j] >= 3</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 10, and we can show that 10 is the maximum we can obtain.
For the 3rd query <code node="[object Object]">x<sub>i</sub> = 2</code> and <code node="[object Object]">y<sub>i</sub> = 5</code>, we can select index <code node="[object Object]">j = 3</code> since <code node="[object Object]">nums1[j] >= 2</code> and <code node="[object Object]">nums2[j] >= 5</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 7, and we can show that 7 is the maximum we can obtain.
Therefore, we return <code node="[object Object]">[6,10,7]</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]
<strong>Output:</strong> [9,9,9]
<strong>Explanation:</strong> For this example, we can use index <code node="[object Object]">j = 2</code> for all the queries since it satisfies the constraints for each query.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> There is one query in this example with <code node="[object Object]">x<sub>i</sub></code> = 3 and <code node="[object Object]">y<sub>i</sub></code> = 3. For every index, j, either nums1[j] < <code node="[object Object]">x<sub>i</sub></code> or nums2[j] < <code node="[object Object]">y<sub>i</sub></code>. Hence, there is no solution.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code> </li>
<li><code>n == nums1.length </code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup> </code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>x<sub>i</sub> == queries[i][1]</code></li>
<li><code>y<sub>i</sub> == queries[i][2]</code></li>
<li><code>1 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>9</sup></code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Sorting; Monotonic Stack
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
Arrays.fill(c, -1);
}
public void update(int x, int v) {
while (x <= n) {
c[x] = Math.max(c[x], v);
x += x & -x;
}
}
public int query(int x) {
int mx = -1;
while (x > 0) {
mx = Math.max(mx, c[x]);
x -= x & -x;
}
return mx;
}
}
class Solution {
public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] queries) {
int n = nums1.length;
int[][] nums = new int[n][0];
for (int i = 0; i < n; ++i) {
nums[i] = new int[] {nums1[i], nums2[i]};
}
Arrays.sort(nums, (a, b) -> b[0] - a[0]);
Arrays.sort(nums2);
int m = queries.length;
Integer[] idx = new Integer[m];
for (int i = 0; i < m; ++i) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> queries[j][0] - queries[i][0]);
int[] ans = new int[m];
int j = 0;
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int i : idx) {
int x = queries[i][0], y = queries[i][1];
for (; j < n && nums[j][0] >= x; ++j) {
int k = n - Arrays.binarySearch(nums2, nums[j][1]);
tree.update(k, nums[j][0] + nums[j][1]);
}
int p = Arrays.binarySearch(nums2, y);
int k = p >= 0 ? n - p : n + p + 1;
ans[i] = tree.query(k);
}
return ans;
}
}
|
2,736
|
Maximum Sum Queries
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, each of length <code>n</code>, and a <strong>1-indexed 2D array</strong> <code>queries</code> where <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>For the <code>i<sup>th</sup></code> query, find the <strong>maximum value</strong> of <code>nums1[j] + nums2[j]</code> among all indices <code>j</code> <code>(0 <= j < n)</code>, where <code>nums1[j] >= x<sub>i</sub></code> and <code>nums2[j] >= y<sub>i</sub></code>, or <strong>-1</strong> if there is no <code>j</code> satisfying the constraints.</p>
<p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]
<strong>Output:</strong> [6,10,7]
<strong>Explanation:</strong>
For the 1st query <code node="[object Object]">x<sub>i</sub> = 4</code> and <code node="[object Object]">y<sub>i</sub> = 1</code>, we can select index <code node="[object Object]">j = 0</code> since <code node="[object Object]">nums1[j] >= 4</code> and <code node="[object Object]">nums2[j] >= 1</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 6, and we can show that 6 is the maximum we can obtain.
For the 2nd query <code node="[object Object]">x<sub>i</sub> = 1</code> and <code node="[object Object]">y<sub>i</sub> = 3</code>, we can select index <code node="[object Object]">j = 2</code> since <code node="[object Object]">nums1[j] >= 1</code> and <code node="[object Object]">nums2[j] >= 3</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 10, and we can show that 10 is the maximum we can obtain.
For the 3rd query <code node="[object Object]">x<sub>i</sub> = 2</code> and <code node="[object Object]">y<sub>i</sub> = 5</code>, we can select index <code node="[object Object]">j = 3</code> since <code node="[object Object]">nums1[j] >= 2</code> and <code node="[object Object]">nums2[j] >= 5</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 7, and we can show that 7 is the maximum we can obtain.
Therefore, we return <code node="[object Object]">[6,10,7]</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]
<strong>Output:</strong> [9,9,9]
<strong>Explanation:</strong> For this example, we can use index <code node="[object Object]">j = 2</code> for all the queries since it satisfies the constraints for each query.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> There is one query in this example with <code node="[object Object]">x<sub>i</sub></code> = 3 and <code node="[object Object]">y<sub>i</sub></code> = 3. For every index, j, either nums1[j] < <code node="[object Object]">x<sub>i</sub></code> or nums2[j] < <code node="[object Object]">y<sub>i</sub></code>. Hence, there is no solution.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code> </li>
<li><code>n == nums1.length </code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup> </code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>x<sub>i</sub> == queries[i][1]</code></li>
<li><code>y<sub>i</sub> == queries[i][2]</code></li>
<li><code>1 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>9</sup></code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Sorting; Monotonic Stack
|
Python
|
class BinaryIndexedTree:
__slots__ = ["n", "c"]
def __init__(self, n: int):
self.n = n
self.c = [-1] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = -1
while x:
mx = max(mx, self.c[x])
x -= x & -x
return mx
class Solution:
def maximumSumQueries(
self, nums1: List[int], nums2: List[int], queries: List[List[int]]
) -> List[int]:
nums = sorted(zip(nums1, nums2), key=lambda x: -x[0])
nums2.sort()
n, m = len(nums1), len(queries)
ans = [-1] * m
j = 0
tree = BinaryIndexedTree(n)
for i in sorted(range(m), key=lambda i: -queries[i][0]):
x, y = queries[i]
while j < n and nums[j][0] >= x:
k = n - bisect_left(nums2, nums[j][1])
tree.update(k, nums[j][0] + nums[j][1])
j += 1
k = n - bisect_left(nums2, y)
ans[i] = tree.query(k)
return ans
|
2,736
|
Maximum Sum Queries
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, each of length <code>n</code>, and a <strong>1-indexed 2D array</strong> <code>queries</code> where <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>For the <code>i<sup>th</sup></code> query, find the <strong>maximum value</strong> of <code>nums1[j] + nums2[j]</code> among all indices <code>j</code> <code>(0 <= j < n)</code>, where <code>nums1[j] >= x<sub>i</sub></code> and <code>nums2[j] >= y<sub>i</sub></code>, or <strong>-1</strong> if there is no <code>j</code> satisfying the constraints.</p>
<p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]
<strong>Output:</strong> [6,10,7]
<strong>Explanation:</strong>
For the 1st query <code node="[object Object]">x<sub>i</sub> = 4</code> and <code node="[object Object]">y<sub>i</sub> = 1</code>, we can select index <code node="[object Object]">j = 0</code> since <code node="[object Object]">nums1[j] >= 4</code> and <code node="[object Object]">nums2[j] >= 1</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 6, and we can show that 6 is the maximum we can obtain.
For the 2nd query <code node="[object Object]">x<sub>i</sub> = 1</code> and <code node="[object Object]">y<sub>i</sub> = 3</code>, we can select index <code node="[object Object]">j = 2</code> since <code node="[object Object]">nums1[j] >= 1</code> and <code node="[object Object]">nums2[j] >= 3</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 10, and we can show that 10 is the maximum we can obtain.
For the 3rd query <code node="[object Object]">x<sub>i</sub> = 2</code> and <code node="[object Object]">y<sub>i</sub> = 5</code>, we can select index <code node="[object Object]">j = 3</code> since <code node="[object Object]">nums1[j] >= 2</code> and <code node="[object Object]">nums2[j] >= 5</code>. The sum <code node="[object Object]">nums1[j] + nums2[j]</code> is 7, and we can show that 7 is the maximum we can obtain.
Therefore, we return <code node="[object Object]">[6,10,7]</code>.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]
<strong>Output:</strong> [9,9,9]
<strong>Explanation:</strong> For this example, we can use index <code node="[object Object]">j = 2</code> for all the queries since it satisfies the constraints for each query.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> There is one query in this example with <code node="[object Object]">x<sub>i</sub></code> = 3 and <code node="[object Object]">y<sub>i</sub></code> = 3. For every index, j, either nums1[j] < <code node="[object Object]">x<sub>i</sub></code> or nums2[j] < <code node="[object Object]">y<sub>i</sub></code>. Hence, there is no solution.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code> </li>
<li><code>n == nums1.length </code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup> </code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>x<sub>i</sub> == queries[i][1]</code></li>
<li><code>y<sub>i</sub> == queries[i][2]</code></li>
<li><code>1 <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>9</sup></code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Sorting; Monotonic Stack
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(-1);
}
update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] = Math.max(this.c[x], v);
x += x & -x;
}
}
query(x: number): number {
let mx = -1;
while (x > 0) {
mx = Math.max(mx, this.c[x]);
x -= x & -x;
}
return mx;
}
}
function maximumSumQueries(nums1: number[], nums2: number[], queries: number[][]): number[] {
const n = nums1.length;
const m = queries.length;
const nums: [number, number][] = [];
for (let i = 0; i < n; ++i) {
nums.push([nums1[i], nums2[i]]);
}
nums.sort((a, b) => b[0] - a[0]);
nums2.sort((a, b) => a - b);
const idx: number[] = Array(m)
.fill(0)
.map((_, i) => i);
idx.sort((i, j) => queries[j][0] - queries[i][0]);
const ans: number[] = Array(m).fill(0);
let j = 0;
const search = (x: number) => {
let [l, r] = [0, n];
while (l < r) {
const mid = (l + r) >> 1;
if (nums2[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const tree = new BinaryIndexedTree(n);
for (const i of idx) {
const [x, y] = queries[i];
for (; j < n && nums[j][0] >= x; ++j) {
const k = n - search(nums[j][1]);
tree.update(k, nums[j][0] + nums[j][1]);
}
const k = n - search(y);
ans[i] = tree.query(k);
}
return ans;
}
|
2,737
|
Find the Closest Marked Node
|
Medium
|
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed directed weighted</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p>
<p>You are also given a node <code>s</code> and a node array <code>marked</code>; your task is to find the <strong>minimum</strong> distance from <code>s</code> to <strong>any</strong> of the nodes in <code>marked</code>.</p>
<p>Return <em>an integer denoting the minimum distance from </em><code>s</code><em> to any node in </em><code>marked</code><em> or </em><code>-1</code><em> if there are no paths from s to any of the marked nodes</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2],[0,3,4]], s = 0, marked = [2,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There is one path from node 0 (the green node) to node 2 (a red node), which is 0->1->2, and has a distance of 1 + 3 = 4.
There are two paths from node 0 to node 3 (a red node), which are 0->1->2->3 and 0->3, the first one has a distance of 1 + 3 + 2 = 6 and the second one has a distance of 4.
The minimum of them is 4.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-34-38.png" style="width: 185px; height: 180px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,2]], s = 1, marked = [0,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are no paths from node 1 (the green node) to node 0 (a red node).
There is one path from node 1 to node 4 (a red node), which is 1->3->4, and has a distance of 1 + 2 = 3.
So the answer is 3.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-13.png" style="width: 300px; height: 285px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2]], s = 3, marked = [0,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no paths from node 3 (the green node) to any of the marked nodes (the red nodes), so the answer is -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-47.png" style="width: 420px; height: 80px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 500</code></li>
<li><code>1 <= edges.length <= 10<sup>4</sup></code></li>
<li><code>edges[i].length = 3</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li><code>1 <= edges[i][2] <= 10<sup>6</sup></code></li>
<li><code>1 <= marked.length <= n - 1</code></li>
<li><code>0 <= s, marked[i] <= n - 1</code></li>
<li><code>s != marked[i]</code></li>
<li><code>marked[i] != marked[j]</code> for every <code>i != j</code></li>
<li>The graph might have <strong>repeated edges</strong>.</li>
<li>The graph is generated such that it has no <strong>self-loops</strong>.</li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int minimumDistance(int n, vector<vector<int>>& edges, int s, vector<int>& marked) {
const int inf = 1 << 29;
vector<vector<int>> g(n, vector<int>(n, inf));
vector<int> dist(n, inf);
dist[s] = 0;
vector<bool> vis(n);
for (auto& e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u][v] = min(g[u][v], w);
}
for (int i = 0; i < n; ++i) {
int t = -1;
for (int j = 0; j < n; ++j) {
if (!vis[j] && (t == -1 || dist[t] > dist[j])) {
t = j;
}
}
vis[t] = true;
for (int j = 0; j < n; ++j) {
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
int ans = inf;
for (int i : marked) {
ans = min(ans, dist[i]);
}
return ans >= inf ? -1 : ans;
}
};
|
2,737
|
Find the Closest Marked Node
|
Medium
|
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed directed weighted</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p>
<p>You are also given a node <code>s</code> and a node array <code>marked</code>; your task is to find the <strong>minimum</strong> distance from <code>s</code> to <strong>any</strong> of the nodes in <code>marked</code>.</p>
<p>Return <em>an integer denoting the minimum distance from </em><code>s</code><em> to any node in </em><code>marked</code><em> or </em><code>-1</code><em> if there are no paths from s to any of the marked nodes</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2],[0,3,4]], s = 0, marked = [2,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There is one path from node 0 (the green node) to node 2 (a red node), which is 0->1->2, and has a distance of 1 + 3 = 4.
There are two paths from node 0 to node 3 (a red node), which are 0->1->2->3 and 0->3, the first one has a distance of 1 + 3 + 2 = 6 and the second one has a distance of 4.
The minimum of them is 4.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-34-38.png" style="width: 185px; height: 180px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,2]], s = 1, marked = [0,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are no paths from node 1 (the green node) to node 0 (a red node).
There is one path from node 1 to node 4 (a red node), which is 1->3->4, and has a distance of 1 + 2 = 3.
So the answer is 3.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-13.png" style="width: 300px; height: 285px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2]], s = 3, marked = [0,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no paths from node 3 (the green node) to any of the marked nodes (the red nodes), so the answer is -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-47.png" style="width: 420px; height: 80px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 500</code></li>
<li><code>1 <= edges.length <= 10<sup>4</sup></code></li>
<li><code>edges[i].length = 3</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li><code>1 <= edges[i][2] <= 10<sup>6</sup></code></li>
<li><code>1 <= marked.length <= n - 1</code></li>
<li><code>0 <= s, marked[i] <= n - 1</code></li>
<li><code>s != marked[i]</code></li>
<li><code>marked[i] != marked[j]</code> for every <code>i != j</code></li>
<li>The graph might have <strong>repeated edges</strong>.</li>
<li>The graph is generated such that it has no <strong>self-loops</strong>.</li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Go
|
func minimumDistance(n int, edges [][]int, s int, marked []int) int {
const inf = 1 << 29
g := make([][]int, n)
dist := make([]int, n)
for i := range g {
g[i] = make([]int, n)
for j := range g[i] {
g[i][j] = inf
}
dist[i] = inf
}
dist[s] = 0
for _, e := range edges {
u, v, w := e[0], e[1], e[2]
g[u][v] = min(g[u][v], w)
}
vis := make([]bool, n)
for _ = range g {
t := -1
for j := 0; j < n; j++ {
if !vis[j] && (t == -1 || dist[j] < dist[t]) {
t = j
}
}
vis[t] = true
for j := 0; j < n; j++ {
dist[j] = min(dist[j], dist[t]+g[t][j])
}
}
ans := inf
for _, i := range marked {
ans = min(ans, dist[i])
}
if ans >= inf {
return -1
}
return ans
}
|
2,737
|
Find the Closest Marked Node
|
Medium
|
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed directed weighted</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p>
<p>You are also given a node <code>s</code> and a node array <code>marked</code>; your task is to find the <strong>minimum</strong> distance from <code>s</code> to <strong>any</strong> of the nodes in <code>marked</code>.</p>
<p>Return <em>an integer denoting the minimum distance from </em><code>s</code><em> to any node in </em><code>marked</code><em> or </em><code>-1</code><em> if there are no paths from s to any of the marked nodes</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2],[0,3,4]], s = 0, marked = [2,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There is one path from node 0 (the green node) to node 2 (a red node), which is 0->1->2, and has a distance of 1 + 3 = 4.
There are two paths from node 0 to node 3 (a red node), which are 0->1->2->3 and 0->3, the first one has a distance of 1 + 3 + 2 = 6 and the second one has a distance of 4.
The minimum of them is 4.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-34-38.png" style="width: 185px; height: 180px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,2]], s = 1, marked = [0,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are no paths from node 1 (the green node) to node 0 (a red node).
There is one path from node 1 to node 4 (a red node), which is 1->3->4, and has a distance of 1 + 2 = 3.
So the answer is 3.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-13.png" style="width: 300px; height: 285px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2]], s = 3, marked = [0,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no paths from node 3 (the green node) to any of the marked nodes (the red nodes), so the answer is -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-47.png" style="width: 420px; height: 80px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 500</code></li>
<li><code>1 <= edges.length <= 10<sup>4</sup></code></li>
<li><code>edges[i].length = 3</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li><code>1 <= edges[i][2] <= 10<sup>6</sup></code></li>
<li><code>1 <= marked.length <= n - 1</code></li>
<li><code>0 <= s, marked[i] <= n - 1</code></li>
<li><code>s != marked[i]</code></li>
<li><code>marked[i] != marked[j]</code> for every <code>i != j</code></li>
<li>The graph might have <strong>repeated edges</strong>.</li>
<li>The graph is generated such that it has no <strong>self-loops</strong>.</li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Java
|
class Solution {
public int minimumDistance(int n, List<List<Integer>> edges, int s, int[] marked) {
final int inf = 1 << 29;
int[][] g = new int[n][n];
for (var e : g) {
Arrays.fill(e, inf);
}
for (var e : edges) {
int u = e.get(0), v = e.get(1), w = e.get(2);
g[u][v] = Math.min(g[u][v], w);
}
int[] dist = new int[n];
Arrays.fill(dist, inf);
dist[s] = 0;
boolean[] vis = new boolean[n];
for (int i = 0; i < n; ++i) {
int t = -1;
for (int j = 0; j < n; ++j) {
if (!vis[j] && (t == -1 || dist[t] > dist[j])) {
t = j;
}
}
vis[t] = true;
for (int j = 0; j < n; ++j) {
dist[j] = Math.min(dist[j], dist[t] + g[t][j]);
}
}
int ans = inf;
for (int i : marked) {
ans = Math.min(ans, dist[i]);
}
return ans >= inf ? -1 : ans;
}
}
|
2,737
|
Find the Closest Marked Node
|
Medium
|
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed directed weighted</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p>
<p>You are also given a node <code>s</code> and a node array <code>marked</code>; your task is to find the <strong>minimum</strong> distance from <code>s</code> to <strong>any</strong> of the nodes in <code>marked</code>.</p>
<p>Return <em>an integer denoting the minimum distance from </em><code>s</code><em> to any node in </em><code>marked</code><em> or </em><code>-1</code><em> if there are no paths from s to any of the marked nodes</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2],[0,3,4]], s = 0, marked = [2,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There is one path from node 0 (the green node) to node 2 (a red node), which is 0->1->2, and has a distance of 1 + 3 = 4.
There are two paths from node 0 to node 3 (a red node), which are 0->1->2->3 and 0->3, the first one has a distance of 1 + 3 + 2 = 6 and the second one has a distance of 4.
The minimum of them is 4.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-34-38.png" style="width: 185px; height: 180px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,2]], s = 1, marked = [0,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are no paths from node 1 (the green node) to node 0 (a red node).
There is one path from node 1 to node 4 (a red node), which is 1->3->4, and has a distance of 1 + 2 = 3.
So the answer is 3.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-13.png" style="width: 300px; height: 285px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2]], s = 3, marked = [0,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no paths from node 3 (the green node) to any of the marked nodes (the red nodes), so the answer is -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-47.png" style="width: 420px; height: 80px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 500</code></li>
<li><code>1 <= edges.length <= 10<sup>4</sup></code></li>
<li><code>edges[i].length = 3</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li><code>1 <= edges[i][2] <= 10<sup>6</sup></code></li>
<li><code>1 <= marked.length <= n - 1</code></li>
<li><code>0 <= s, marked[i] <= n - 1</code></li>
<li><code>s != marked[i]</code></li>
<li><code>marked[i] != marked[j]</code> for every <code>i != j</code></li>
<li>The graph might have <strong>repeated edges</strong>.</li>
<li>The graph is generated such that it has no <strong>self-loops</strong>.</li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Python
|
class Solution:
def minimumDistance(
self, n: int, edges: List[List[int]], s: int, marked: List[int]
) -> int:
g = [[inf] * n for _ in range(n)]
for u, v, w in edges:
g[u][v] = min(g[u][v], w)
dist = [inf] * n
vis = [False] * n
dist[s] = 0
for _ in range(n):
t = -1
for j in range(n):
if not vis[j] and (t == -1 or dist[t] > dist[j]):
t = j
vis[t] = True
for j in range(n):
dist[j] = min(dist[j], dist[t] + g[t][j])
ans = min(dist[i] for i in marked)
return -1 if ans >= inf else ans
|
2,737
|
Find the Closest Marked Node
|
Medium
|
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed directed weighted</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p>
<p>You are also given a node <code>s</code> and a node array <code>marked</code>; your task is to find the <strong>minimum</strong> distance from <code>s</code> to <strong>any</strong> of the nodes in <code>marked</code>.</p>
<p>Return <em>an integer denoting the minimum distance from </em><code>s</code><em> to any node in </em><code>marked</code><em> or </em><code>-1</code><em> if there are no paths from s to any of the marked nodes</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2],[0,3,4]], s = 0, marked = [2,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There is one path from node 0 (the green node) to node 2 (a red node), which is 0->1->2, and has a distance of 1 + 3 = 4.
There are two paths from node 0 to node 3 (a red node), which are 0->1->2->3 and 0->3, the first one has a distance of 1 + 3 + 2 = 6 and the second one has a distance of 4.
The minimum of them is 4.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-34-38.png" style="width: 185px; height: 180px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 5, edges = [[0,1,2],[0,2,4],[1,3,1],[2,3,3],[3,4,2]], s = 1, marked = [0,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are no paths from node 1 (the green node) to node 0 (a red node).
There is one path from node 1 to node 4 (a red node), which is 1->3->4, and has a distance of 1 + 2 = 3.
So the answer is 3.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-13.png" style="width: 300px; height: 285px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,1,1],[1,2,3],[2,3,2]], s = 3, marked = [0,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no paths from node 3 (the green node) to any of the marked nodes (the red nodes), so the answer is -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2737.Find%20the%20Closest%20Marked%20Node/images/image_2023-06-13_16-35-47.png" style="width: 420px; height: 80px;" /></p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 500</code></li>
<li><code>1 <= edges.length <= 10<sup>4</sup></code></li>
<li><code>edges[i].length = 3</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li><code>1 <= edges[i][2] <= 10<sup>6</sup></code></li>
<li><code>1 <= marked.length <= n - 1</code></li>
<li><code>0 <= s, marked[i] <= n - 1</code></li>
<li><code>s != marked[i]</code></li>
<li><code>marked[i] != marked[j]</code> for every <code>i != j</code></li>
<li>The graph might have <strong>repeated edges</strong>.</li>
<li>The graph is generated such that it has no <strong>self-loops</strong>.</li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
TypeScript
|
function minimumDistance(n: number, edges: number[][], s: number, marked: number[]): number {
const inf = 1 << 29;
const g: number[][] = Array(n)
.fill(0)
.map(() => Array(n).fill(inf));
const dist: number[] = Array(n).fill(inf);
const vis: boolean[] = Array(n).fill(false);
for (const [u, v, w] of edges) {
g[u][v] = Math.min(g[u][v], w);
}
dist[s] = 0;
for (let i = 0; i < n; ++i) {
let t = -1;
for (let j = 0; j < n; ++j) {
if (!vis[j] && (t == -1 || dist[t] > dist[j])) {
t = j;
}
}
vis[t] = true;
for (let j = 0; j < n; ++j) {
dist[j] = Math.min(dist[j], dist[t] + g[t][j]);
}
}
let ans = inf;
for (const i of marked) {
ans = Math.min(ans, dist[i]);
}
return ans >= inf ? -1 : ans;
}
|
2,738
|
Count Occurrences in Text
|
Medium
|
<p>Table:<font face="monospace"> <code>Files</code></font></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-- ----------+---------+
| file_name | varchar |
| content | text |
+-------------+---------+
file_name is the column with unique values of this table.
Each row contains file_name and the content of that file.
</pre>
<p>Write a solution to find the number of files that have at least one occurrence of the words <strong>'bull'</strong> and <strong>'bear'</strong> as a <strong>standalone word</strong>, respectively, disregarding any instances where it appears without space on either side (e.g. 'bullet', 'bears', 'bull.', or 'bear' at the beginning or end of a sentence will <strong>not</strong> be considered) </p>
<p>Return <em>the word 'bull' and 'bear' along with the corresponding number of occurrences in <strong>any order.</strong></em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Files table:
+------------+----------------------------------------------------------------------------------+
| file_name | content |
+------------+----------------------------------------------------------------------------------+
| draft1.txt | The stock exchange predicts a bull market which would make many investors happy. |
| draft2.txt | The stock exchange predicts a bull market which would make many investors happy, |
| | but analysts warn of possibility of too much optimism and that in fact we are |
| | awaiting a bear market. |
| draft3.txt | The stock exchange predicts a bull market which would make many investors happy, |
| | but analysts warn of possibility of too much optimism and that in fact we are |
| | awaiting a bear market. As always predicting the future market is an uncertain |
| | game and all investors should follow their instincts and best practices. |
+------------+----------------------------------------------------------------------------------+
<strong>Output:</strong>
+------+-------+
| word | count |
+------+-------+
| bull | 3 |
| bear | 2 |
+------+-------+
<strong>Explanation:</strong>
- The word "bull" appears 1 time in "draft1.txt", 1 time in "draft2.txt", and 1 time in "draft3.txt". Therefore, the total number of occurrences for the word "bull" is 3.
- The word "bear" appears 1 time in "draft2.txt", and 1 time in "draft3.txt". Therefore, the total number of occurrences for the word "bear" is 2.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT 'bull' AS word, COUNT(*) AS count
FROM Files
WHERE content LIKE '% bull %'
UNION
SELECT 'bear' AS word, COUNT(*) AS count
FROM Files
WHERE content LIKE '% bear %';
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
C++
|
class Solution {
public:
int distanceTraveled(int mainTank, int additionalTank) {
int ans = 0, cur = 0;
while (mainTank > 0) {
cur++;
ans += 10;
mainTank--;
if (cur % 5 == 0 && additionalTank > 0) {
additionalTank--;
mainTank++;
}
}
return ans;
}
};
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
Go
|
func distanceTraveled(mainTank int, additionalTank int) (ans int) {
cur := 0
for mainTank > 0 {
cur++
ans += 10
mainTank--
if cur%5 == 0 && additionalTank > 0 {
additionalTank--
mainTank++
}
}
return
}
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
Java
|
class Solution {
public int distanceTraveled(int mainTank, int additionalTank) {
int ans = 0, cur = 0;
while (mainTank > 0) {
cur++;
ans += 10;
mainTank--;
if (cur % 5 == 0 && additionalTank > 0) {
additionalTank--;
mainTank++;
}
}
return ans;
}
}
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
JavaScript
|
var distanceTraveled = function (mainTank, additionalTank) {
let ans = 0,
cur = 0;
while (mainTank) {
cur++;
ans += 10;
mainTank--;
if (cur % 5 === 0 && additionalTank) {
additionalTank--;
mainTank++;
}
}
return ans;
};
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
Python
|
class Solution:
def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
ans = cur = 0
while mainTank:
cur += 1
ans += 10
mainTank -= 1
if cur % 5 == 0 and additionalTank:
additionalTank -= 1
mainTank += 1
return ans
|
2,739
|
Total Distance Traveled
|
Easy
|
<p>A truck has two fuel tanks. You are given two integers, <code>mainTank</code> representing the fuel present in the main tank in liters and <code>additionalTank</code> representing the fuel present in the additional tank in liters.</p>
<p>The truck has a mileage of <code>10</code> km per liter. Whenever <code>5</code> liters of fuel get used up in the main tank, if the additional tank has at least <code>1</code> liters of fuel, <code>1</code> liters of fuel will be transferred from the additional tank to the main tank.</p>
<p>Return <em>the maximum distance which can be traveled.</em></p>
<p><strong>Note: </strong>Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 5, additionalTank = 10
<strong>Output:</strong> 60
<strong>Explanation:</strong>
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.
After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance traveled is 60km.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mainTank = 1, additionalTank = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong>
After spending 1 litre of fuel, the main tank becomes empty.
Total distance traveled is 10km.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= mainTank, additionalTank <= 100</code></li>
</ul>
|
Math; Simulation
|
Rust
|
impl Solution {
pub fn distance_traveled(mut main_tank: i32, mut additional_tank: i32) -> i32 {
let mut cur = 0;
let mut ans = 0;
while main_tank > 0 {
cur += 1;
main_tank -= 1;
ans += 10;
if cur % 5 == 0 && additional_tank > 0 {
additional_tank -= 1;
main_tank += 1;
}
}
ans
}
}
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
C++
|
class Solution {
public:
int findValueOfPartition(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 1 << 30;
for (int i = 1; i < nums.size(); ++i) {
ans = min(ans, nums[i] - nums[i - 1]);
}
return ans;
}
};
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
Go
|
func findValueOfPartition(nums []int) int {
sort.Ints(nums)
ans := 1 << 30
for i, x := range nums[1:] {
ans = min(ans, x-nums[i])
}
return ans
}
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
Java
|
class Solution {
public int findValueOfPartition(int[] nums) {
Arrays.sort(nums);
int ans = 1 << 30;
for (int i = 1; i < nums.length; ++i) {
ans = Math.min(ans, nums[i] - nums[i - 1]);
}
return ans;
}
}
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
Python
|
class Solution:
def findValueOfPartition(self, nums: List[int]) -> int:
nums.sort()
return min(b - a for a, b in pairwise(nums))
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
Rust
|
impl Solution {
pub fn find_value_of_partition(mut nums: Vec<i32>) -> i32 {
nums.sort();
let mut ans = i32::MAX;
for i in 1..nums.len() {
ans = ans.min(nums[i] - nums[i - 1]);
}
ans
}
}
|
2,740
|
Find the Value of the Partition
|
Medium
|
<p>You are given a <strong>positive</strong> integer array <code>nums</code>.</p>
<p>Partition <code>nums</code> into two arrays, <code>nums1</code> and <code>nums2</code>, such that:</p>
<ul>
<li>Each element of the array <code>nums</code> belongs to either the array <code>nums1</code> or the array <code>nums2</code>.</li>
<li>Both arrays are <strong>non-empty</strong>.</li>
<li>The value of the partition is <strong>minimized</strong>.</li>
</ul>
<p>The value of the partition is <code>|max(nums1) - min(nums2)|</code>.</p>
<p>Here, <code>max(nums1)</code> denotes the maximum element of the array <code>nums1</code>, and <code>min(nums2)</code> denotes the minimum element of the array <code>nums2</code>.</p>
<p>Return <em>the integer denoting the value of such partition</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1.
It can be proven that 1 is the minimum value out of all partitions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [100,1,10]
<strong>Output:</strong> 9
<strong>Explanation:</strong> We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Sorting
|
TypeScript
|
function findValueOfPartition(nums: number[]): number {
nums.sort((a, b) => a - b);
let ans = Infinity;
for (let i = 1; i < nums.length; ++i) {
ans = Math.min(ans, Math.abs(nums[i] - nums[i - 1]));
}
return ans;
}
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
C++
|
class Solution {
public:
int specialPerm(vector<int>& nums) {
const int mod = 1e9 + 7;
int n = nums.size();
int m = 1 << n;
int f[m][n];
memset(f, 0, sizeof(f));
for (int i = 1; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
int ii = i ^ (1 << j);
if (ii == 0) {
f[i][j] = 1;
continue;
}
for (int k = 0; k < n; ++k) {
if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) {
f[i][j] = (f[i][j] + f[ii][k]) % mod;
}
}
}
}
}
int ans = 0;
for (int x : f[m - 1]) {
ans = (ans + x) % mod;
}
return ans;
}
};
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Go
|
func specialPerm(nums []int) (ans int) {
const mod int = 1e9 + 7
n := len(nums)
m := 1 << n
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
for i := 1; i < m; i++ {
for j, x := range nums {
if i>>j&1 == 1 {
ii := i ^ (1 << j)
if ii == 0 {
f[i][j] = 1
continue
}
for k, y := range nums {
if x%y == 0 || y%x == 0 {
f[i][j] = (f[i][j] + f[ii][k]) % mod
}
}
}
}
}
for _, x := range f[m-1] {
ans = (ans + x) % mod
}
return
}
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Java
|
class Solution {
public int specialPerm(int[] nums) {
final int mod = (int) 1e9 + 7;
int n = nums.length;
int m = 1 << n;
int[][] f = new int[m][n];
for (int i = 1; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
int ii = i ^ (1 << j);
if (ii == 0) {
f[i][j] = 1;
continue;
}
for (int k = 0; k < n; ++k) {
if (nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0) {
f[i][j] = (f[i][j] + f[ii][k]) % mod;
}
}
}
}
}
int ans = 0;
for (int x : f[m - 1]) {
ans = (ans + x) % mod;
}
return ans;
}
}
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Python
|
class Solution:
def specialPerm(self, nums: List[int]) -> int:
mod = 10**9 + 7
n = len(nums)
m = 1 << n
f = [[0] * n for _ in range(m)]
for i in range(1, m):
for j, x in enumerate(nums):
if i >> j & 1:
ii = i ^ (1 << j)
if ii == 0:
f[i][j] = 1
continue
for k, y in enumerate(nums):
if x % y == 0 or y % x == 0:
f[i][j] = (f[i][j] + f[ii][k]) % mod
return sum(f[-1]) % mod
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Rust
|
impl Solution {
pub fn special_perm(nums: Vec<i32>) -> i32 {
const MOD: i32 = 1_000_000_007;
let n = nums.len();
let m = 1 << n;
let mut f = vec![vec![0; n]; m];
for i in 1..m {
for j in 0..n {
if (i >> j) & 1 == 1 {
let ii = i ^ (1 << j);
if ii == 0 {
f[i][j] = 1;
continue;
}
for k in 0..n {
if nums[j] % nums[k] == 0 || nums[k] % nums[j] == 0 {
f[i][j] = (f[i][j] + f[ii][k]) % MOD;
}
}
}
}
}
let mut ans = 0;
for &x in &f[m - 1] {
ans = (ans + x) % MOD;
}
ans
}
}
|
2,741
|
Special Permutations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <code>n</code> <strong>distinct</strong> positive integers. A permutation of <code>nums</code> is called special if:</p>
<ul>
<li>For all indexes <code>0 <= i < n - 1</code>, either <code>nums[i] % nums[i+1] == 0</code> or <code>nums[i+1] % nums[i] == 0</code>.</li>
</ul>
<p>Return <em>the total number of special permutations. </em>As the answer could be large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,6]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,6,2] and [2,6,3] are the two special permutations of nums.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [3,1,4] and [4,1,3] are the two special permutations of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 14</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
TypeScript
|
function specialPerm(nums: number[]): number {
const mod = 1e9 + 7;
const n = nums.length;
const m = 1 << n;
const f = Array.from({ length: m }, () => Array(n).fill(0));
for (let i = 1; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (((i >> j) & 1) === 1) {
const ii = i ^ (1 << j);
if (ii === 0) {
f[i][j] = 1;
continue;
}
for (let k = 0; k < n; ++k) {
if (nums[j] % nums[k] === 0 || nums[k] % nums[j] === 0) {
f[i][j] = (f[i][j] + f[ii][k]) % mod;
}
}
}
}
}
return f[m - 1].reduce((acc, x) => (acc + x) % mod);
}
|
2,742
|
Painting the Walls
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>cost</code> and <code>time</code>, of size <code>n</code> representing the costs and the time taken to paint <code>n</code> different walls respectively. There are two painters available:</p>
<ul>
<li>A<strong> paid painter</strong> that paints the <code>i<sup>th</sup></code> wall in <code>time[i]</code> units of time and takes <code>cost[i]</code> units of money.</li>
<li>A<strong> free painter</strong> that paints <strong>any</strong> wall in <code>1</code> unit of time at a cost of <code>0</code>. But the free painter can only be used if the paid painter is already <strong>occupied</strong>.</li>
</ul>
<p>Return <em>the minimum amount of money required to paint the </em><code>n</code><em> walls.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> cost = [1,2,3,2], time = [1,2,3,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> cost = [2,3,4,2], time = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= cost.length <= 500</code></li>
<li><code>cost.length == time.length</code></li>
<li><code>1 <= cost[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= time[i] <= 500</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int paintWalls(vector<int>& cost, vector<int>& time) {
int n = cost.size();
int f[n][n << 1 | 1];
memset(f, -1, sizeof(f));
function<int(int, int)> dfs = [&](int i, int j) -> int {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return 1 << 30;
}
if (f[i][j] == -1) {
f[i][j] = min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1));
}
return f[i][j];
};
return dfs(0, n);
}
};
|
2,742
|
Painting the Walls
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>cost</code> and <code>time</code>, of size <code>n</code> representing the costs and the time taken to paint <code>n</code> different walls respectively. There are two painters available:</p>
<ul>
<li>A<strong> paid painter</strong> that paints the <code>i<sup>th</sup></code> wall in <code>time[i]</code> units of time and takes <code>cost[i]</code> units of money.</li>
<li>A<strong> free painter</strong> that paints <strong>any</strong> wall in <code>1</code> unit of time at a cost of <code>0</code>. But the free painter can only be used if the paid painter is already <strong>occupied</strong>.</li>
</ul>
<p>Return <em>the minimum amount of money required to paint the </em><code>n</code><em> walls.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> cost = [1,2,3,2], time = [1,2,3,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> cost = [2,3,4,2], time = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= cost.length <= 500</code></li>
<li><code>cost.length == time.length</code></li>
<li><code>1 <= cost[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= time[i] <= 500</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func paintWalls(cost []int, time []int) int {
n := len(cost)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n<<1|1)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if n-i <= j-n {
return 0
}
if i >= n {
return 1 << 30
}
if f[i][j] == -1 {
f[i][j] = min(dfs(i+1, j+time[i])+cost[i], dfs(i+1, j-1))
}
return f[i][j]
}
return dfs(0, n)
}
|
2,742
|
Painting the Walls
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>cost</code> and <code>time</code>, of size <code>n</code> representing the costs and the time taken to paint <code>n</code> different walls respectively. There are two painters available:</p>
<ul>
<li>A<strong> paid painter</strong> that paints the <code>i<sup>th</sup></code> wall in <code>time[i]</code> units of time and takes <code>cost[i]</code> units of money.</li>
<li>A<strong> free painter</strong> that paints <strong>any</strong> wall in <code>1</code> unit of time at a cost of <code>0</code>. But the free painter can only be used if the paid painter is already <strong>occupied</strong>.</li>
</ul>
<p>Return <em>the minimum amount of money required to paint the </em><code>n</code><em> walls.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> cost = [1,2,3,2], time = [1,2,3,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> cost = [2,3,4,2], time = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= cost.length <= 500</code></li>
<li><code>cost.length == time.length</code></li>
<li><code>1 <= cost[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= time[i] <= 500</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
private int n;
private int[] cost;
private int[] time;
private Integer[][] f;
public int paintWalls(int[] cost, int[] time) {
n = cost.length;
this.cost = cost;
this.time = time;
f = new Integer[n][n << 1 | 1];
return dfs(0, n);
}
private int dfs(int i, int j) {
if (n - i <= j - n) {
return 0;
}
if (i >= n) {
return 1 << 30;
}
if (f[i][j] == null) {
f[i][j] = Math.min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1));
}
return f[i][j];
}
}
|
2,742
|
Painting the Walls
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>cost</code> and <code>time</code>, of size <code>n</code> representing the costs and the time taken to paint <code>n</code> different walls respectively. There are two painters available:</p>
<ul>
<li>A<strong> paid painter</strong> that paints the <code>i<sup>th</sup></code> wall in <code>time[i]</code> units of time and takes <code>cost[i]</code> units of money.</li>
<li>A<strong> free painter</strong> that paints <strong>any</strong> wall in <code>1</code> unit of time at a cost of <code>0</code>. But the free painter can only be used if the paid painter is already <strong>occupied</strong>.</li>
</ul>
<p>Return <em>the minimum amount of money required to paint the </em><code>n</code><em> walls.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> cost = [1,2,3,2], time = [1,2,3,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> cost = [2,3,4,2], time = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= cost.length <= 500</code></li>
<li><code>cost.length == time.length</code></li>
<li><code>1 <= cost[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= time[i] <= 500</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def paintWalls(self, cost: List[int], time: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if n - i <= j:
return 0
if i >= n:
return inf
return min(dfs(i + 1, j + time[i]) + cost[i], dfs(i + 1, j - 1))
n = len(cost)
return dfs(0, 0)
|
2,742
|
Painting the Walls
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>cost</code> and <code>time</code>, of size <code>n</code> representing the costs and the time taken to paint <code>n</code> different walls respectively. There are two painters available:</p>
<ul>
<li>A<strong> paid painter</strong> that paints the <code>i<sup>th</sup></code> wall in <code>time[i]</code> units of time and takes <code>cost[i]</code> units of money.</li>
<li>A<strong> free painter</strong> that paints <strong>any</strong> wall in <code>1</code> unit of time at a cost of <code>0</code>. But the free painter can only be used if the paid painter is already <strong>occupied</strong>.</li>
</ul>
<p>Return <em>the minimum amount of money required to paint the </em><code>n</code><em> walls.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> cost = [1,2,3,2], time = [1,2,3,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> cost = [2,3,4,2], time = [1,1,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= cost.length <= 500</code></li>
<li><code>cost.length == time.length</code></li>
<li><code>1 <= cost[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= time[i] <= 500</code></li>
</ul>
|
Array; Dynamic Programming
|
Rust
|
impl Solution {
#[allow(dead_code)]
pub fn paint_walls(cost: Vec<i32>, time: Vec<i32>) -> i32 {
let n = cost.len();
let mut record_vec: Vec<Vec<i32>> = vec![vec![-1; n << 1 | 1]; n];
Self::dfs(&mut record_vec, 0, n as i32, n as i32, &time, &cost)
}
#[allow(dead_code)]
fn dfs(
record_vec: &mut Vec<Vec<i32>>,
i: i32,
j: i32,
n: i32,
time: &Vec<i32>,
cost: &Vec<i32>,
) -> i32 {
if n - i <= j - n {
// All the remaining walls can be printed at no cost
// Just return 0
return 0;
}
if i >= n {
// No way this case can be achieved
// Just return +INF
return 1 << 30;
}
if record_vec[i as usize][j as usize] == -1 {
// This record hasn't been written
record_vec[i as usize][j as usize] = std::cmp::min(
Self::dfs(record_vec, i + 1, j + time[i as usize], n, time, cost)
+ cost[i as usize],
Self::dfs(record_vec, i + 1, j - 1, n, time, cost),
);
}
record_vec[i as usize][j as usize]
}
}
|
2,743
|
Count Substrings Without Repeating Character
|
Medium
|
<p>You are given a string <code>s</code> consisting only of lowercase English letters. We call a substring <b>special</b> if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of <b>special</b> substrings. For example, in the string <code>"pop"</code>, the substring <code>"po"</code> is a <strong>special</strong> substring, however, <code>"pop"</code> is not <strong>special</strong> (since <code>'p'</code> has occurred twice).</p>
<p>Return <em>the number of <b>special</b> substrings.</em></p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string. For example, <code>"abc"</code> is a substring of <code>"abcd"</code>, but <code>"acd"</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "ooo"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> 7
<strong>Explanation:</strong> Special substrings are as follows (sorted by their start positions):
Special substrings of length 1: "a", "b", "a", "b"
Special substrings of length 2: "ab", "ba", "ab"
And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Hash Table; String; Sliding Window
|
C++
|
class Solution {
public:
int numberOfSpecialSubstrings(string s) {
int n = s.size();
int cnt[26]{};
int ans = 0;
for (int i = 0, j = 0; i < n; ++i) {
int k = s[i] - 'a';
++cnt[k];
while (cnt[k] > 1) {
--cnt[s[j++] - 'a'];
}
ans += i - j + 1;
}
return ans;
}
};
|
2,743
|
Count Substrings Without Repeating Character
|
Medium
|
<p>You are given a string <code>s</code> consisting only of lowercase English letters. We call a substring <b>special</b> if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of <b>special</b> substrings. For example, in the string <code>"pop"</code>, the substring <code>"po"</code> is a <strong>special</strong> substring, however, <code>"pop"</code> is not <strong>special</strong> (since <code>'p'</code> has occurred twice).</p>
<p>Return <em>the number of <b>special</b> substrings.</em></p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string. For example, <code>"abc"</code> is a substring of <code>"abcd"</code>, but <code>"acd"</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "ooo"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> 7
<strong>Explanation:</strong> Special substrings are as follows (sorted by their start positions):
Special substrings of length 1: "a", "b", "a", "b"
Special substrings of length 2: "ab", "ba", "ab"
And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Hash Table; String; Sliding Window
|
Go
|
func numberOfSpecialSubstrings(s string) (ans int) {
j := 0
cnt := [26]int{}
for i, c := range s {
k := c - 'a'
cnt[k]++
for cnt[k] > 1 {
cnt[s[j]-'a']--
j++
}
ans += i - j + 1
}
return
}
|
2,743
|
Count Substrings Without Repeating Character
|
Medium
|
<p>You are given a string <code>s</code> consisting only of lowercase English letters. We call a substring <b>special</b> if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of <b>special</b> substrings. For example, in the string <code>"pop"</code>, the substring <code>"po"</code> is a <strong>special</strong> substring, however, <code>"pop"</code> is not <strong>special</strong> (since <code>'p'</code> has occurred twice).</p>
<p>Return <em>the number of <b>special</b> substrings.</em></p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string. For example, <code>"abc"</code> is a substring of <code>"abcd"</code>, but <code>"acd"</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "ooo"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> 7
<strong>Explanation:</strong> Special substrings are as follows (sorted by their start positions):
Special substrings of length 1: "a", "b", "a", "b"
Special substrings of length 2: "ab", "ba", "ab"
And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Hash Table; String; Sliding Window
|
Java
|
class Solution {
public int numberOfSpecialSubstrings(String s) {
int n = s.length();
int ans = 0;
int[] cnt = new int[26];
for (int i = 0, j = 0; i < n; ++i) {
int k = s.charAt(i) - 'a';
++cnt[k];
while (cnt[k] > 1) {
--cnt[s.charAt(j++) - 'a'];
}
ans += i - j + 1;
}
return ans;
}
}
|
2,743
|
Count Substrings Without Repeating Character
|
Medium
|
<p>You are given a string <code>s</code> consisting only of lowercase English letters. We call a substring <b>special</b> if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of <b>special</b> substrings. For example, in the string <code>"pop"</code>, the substring <code>"po"</code> is a <strong>special</strong> substring, however, <code>"pop"</code> is not <strong>special</strong> (since <code>'p'</code> has occurred twice).</p>
<p>Return <em>the number of <b>special</b> substrings.</em></p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string. For example, <code>"abc"</code> is a substring of <code>"abcd"</code>, but <code>"acd"</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "ooo"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> 7
<strong>Explanation:</strong> Special substrings are as follows (sorted by their start positions):
Special substrings of length 1: "a", "b", "a", "b"
Special substrings of length 2: "ab", "ba", "ab"
And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Hash Table; String; Sliding Window
|
Python
|
class Solution:
def numberOfSpecialSubstrings(self, s: str) -> int:
cnt = Counter()
ans = j = 0
for i, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[j]] -= 1
j += 1
ans += i - j + 1
return ans
|
2,743
|
Count Substrings Without Repeating Character
|
Medium
|
<p>You are given a string <code>s</code> consisting only of lowercase English letters. We call a substring <b>special</b> if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of <b>special</b> substrings. For example, in the string <code>"pop"</code>, the substring <code>"po"</code> is a <strong>special</strong> substring, however, <code>"pop"</code> is not <strong>special</strong> (since <code>'p'</code> has occurred twice).</p>
<p>Return <em>the number of <b>special</b> substrings.</em></p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string. For example, <code>"abc"</code> is a substring of <code>"abcd"</code>, but <code>"acd"</code> is not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "ooo"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Any substring with a length of at least two contains a repeating character. So we have to count the number of substrings of length one, which is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> 7
<strong>Explanation:</strong> Special substrings are as follows (sorted by their start positions):
Special substrings of length 1: "a", "b", "a", "b"
Special substrings of length 2: "ab", "ba", "ab"
And it can be shown that there are no special substrings with a length of at least three. So the answer would be 4 + 3 = 7.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters</li>
</ul>
|
Hash Table; String; Sliding Window
|
TypeScript
|
function numberOfSpecialSubstrings(s: string): number {
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
const n = s.length;
const cnt: number[] = Array(26).fill(0);
let ans = 0;
for (let i = 0, j = 0; i < n; ++i) {
const k = idx(s[i]);
++cnt[k];
while (cnt[k] > 1) {
--cnt[idx(s[j++])];
}
ans += i - j + 1;
}
return ans;
}
|
2,744
|
Find Maximum Number of String Pairs
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> consisting of <strong>distinct</strong> strings.</p>
<p>The string <code>words[i]</code> can be paired with the string <code>words[j]</code> if:</p>
<ul>
<li>The string <code>words[i]</code> is equal to the reversed string of <code>words[j]</code>.</li>
<li><code>0 <= i < j < words.length</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of pairs that can be formed from the array </em><code>words</code><em>.</em></p>
<p>Note that each string can belong in <strong>at most one</strong> pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ac","dc","ca","zz"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can form 2 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 2<sup>nd</sup> string, as the reversed string of word[0] is "dc" and is equal to words[2].
- We pair the 1<sup>st</sup> string with the 3<sup>rd</sup> string, as the reversed string of word[1] is "ca" and is equal to words[3].
It can be proven that 2 is the maximum number of pairs that can be formed.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","ba","cc"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can form 1 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 1<sup>st</sup> string, as the reversed string of words[1] is "ab" and is equal to words[0].
It can be proven that 1 is the maximum number of pairs that can be formed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, we are unable to form any pair of strings.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>words[i].length == 2</code></li>
<li><code>words</code> consists of distinct strings.</li>
<li><code>words[i]</code> contains only lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Simulation
|
C++
|
class Solution {
public:
int maximumNumberOfStringPairs(vector<string>& words) {
unordered_map<int, int> cnt;
int ans = 0;
for (auto& w : words) {
int a = w[0] - 'a', b = w[1] - 'a';
ans += cnt[b << 5 | a];
cnt[a << 5 | b]++;
}
return ans;
}
};
|
2,744
|
Find Maximum Number of String Pairs
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> consisting of <strong>distinct</strong> strings.</p>
<p>The string <code>words[i]</code> can be paired with the string <code>words[j]</code> if:</p>
<ul>
<li>The string <code>words[i]</code> is equal to the reversed string of <code>words[j]</code>.</li>
<li><code>0 <= i < j < words.length</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of pairs that can be formed from the array </em><code>words</code><em>.</em></p>
<p>Note that each string can belong in <strong>at most one</strong> pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ac","dc","ca","zz"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can form 2 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 2<sup>nd</sup> string, as the reversed string of word[0] is "dc" and is equal to words[2].
- We pair the 1<sup>st</sup> string with the 3<sup>rd</sup> string, as the reversed string of word[1] is "ca" and is equal to words[3].
It can be proven that 2 is the maximum number of pairs that can be formed.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","ba","cc"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can form 1 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 1<sup>st</sup> string, as the reversed string of words[1] is "ab" and is equal to words[0].
It can be proven that 1 is the maximum number of pairs that can be formed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, we are unable to form any pair of strings.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>words[i].length == 2</code></li>
<li><code>words</code> consists of distinct strings.</li>
<li><code>words[i]</code> contains only lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Simulation
|
Go
|
func maximumNumberOfStringPairs(words []string) (ans int) {
cnt := map[int]int{}
for _, w := range words {
a, b := int(w[0]-'a'), int(w[1]-'a')
ans += cnt[b<<5|a]
cnt[a<<5|b]++
}
return
}
|
2,744
|
Find Maximum Number of String Pairs
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> consisting of <strong>distinct</strong> strings.</p>
<p>The string <code>words[i]</code> can be paired with the string <code>words[j]</code> if:</p>
<ul>
<li>The string <code>words[i]</code> is equal to the reversed string of <code>words[j]</code>.</li>
<li><code>0 <= i < j < words.length</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of pairs that can be formed from the array </em><code>words</code><em>.</em></p>
<p>Note that each string can belong in <strong>at most one</strong> pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ac","dc","ca","zz"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can form 2 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 2<sup>nd</sup> string, as the reversed string of word[0] is "dc" and is equal to words[2].
- We pair the 1<sup>st</sup> string with the 3<sup>rd</sup> string, as the reversed string of word[1] is "ca" and is equal to words[3].
It can be proven that 2 is the maximum number of pairs that can be formed.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","ba","cc"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can form 1 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 1<sup>st</sup> string, as the reversed string of words[1] is "ab" and is equal to words[0].
It can be proven that 1 is the maximum number of pairs that can be formed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, we are unable to form any pair of strings.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>words[i].length == 2</code></li>
<li><code>words</code> consists of distinct strings.</li>
<li><code>words[i]</code> contains only lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Simulation
|
Java
|
class Solution {
public int maximumNumberOfStringPairs(String[] words) {
Map<Integer, Integer> cnt = new HashMap<>();
int ans = 0;
for (var w : words) {
int a = w.charAt(0) - 'a', b = w.charAt(1) - 'a';
ans += cnt.getOrDefault(b << 5 | a, 0);
cnt.merge(a << 5 | b, 1, Integer::sum);
}
return ans;
}
}
|
2,744
|
Find Maximum Number of String Pairs
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> consisting of <strong>distinct</strong> strings.</p>
<p>The string <code>words[i]</code> can be paired with the string <code>words[j]</code> if:</p>
<ul>
<li>The string <code>words[i]</code> is equal to the reversed string of <code>words[j]</code>.</li>
<li><code>0 <= i < j < words.length</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of pairs that can be formed from the array </em><code>words</code><em>.</em></p>
<p>Note that each string can belong in <strong>at most one</strong> pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ac","dc","ca","zz"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can form 2 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 2<sup>nd</sup> string, as the reversed string of word[0] is "dc" and is equal to words[2].
- We pair the 1<sup>st</sup> string with the 3<sup>rd</sup> string, as the reversed string of word[1] is "ca" and is equal to words[3].
It can be proven that 2 is the maximum number of pairs that can be formed.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","ba","cc"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can form 1 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 1<sup>st</sup> string, as the reversed string of words[1] is "ab" and is equal to words[0].
It can be proven that 1 is the maximum number of pairs that can be formed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, we are unable to form any pair of strings.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>words[i].length == 2</code></li>
<li><code>words</code> consists of distinct strings.</li>
<li><code>words[i]</code> contains only lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Simulation
|
Python
|
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
cnt = Counter()
ans = 0
for w in words:
ans += cnt[w[::-1]]
cnt[w] += 1
return ans
|
2,744
|
Find Maximum Number of String Pairs
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> consisting of <strong>distinct</strong> strings.</p>
<p>The string <code>words[i]</code> can be paired with the string <code>words[j]</code> if:</p>
<ul>
<li>The string <code>words[i]</code> is equal to the reversed string of <code>words[j]</code>.</li>
<li><code>0 <= i < j < words.length</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of pairs that can be formed from the array </em><code>words</code><em>.</em></p>
<p>Note that each string can belong in <strong>at most one</strong> pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ac","dc","ca","zz"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, we can form 2 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 2<sup>nd</sup> string, as the reversed string of word[0] is "dc" and is equal to words[2].
- We pair the 1<sup>st</sup> string with the 3<sup>rd</sup> string, as the reversed string of word[1] is "ca" and is equal to words[3].
It can be proven that 2 is the maximum number of pairs that can be formed.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","ba","cc"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, we can form 1 pair of strings in the following way:
- We pair the 0<sup>th</sup> string with the 1<sup>st</sup> string, as the reversed string of words[1] is "ab" and is equal to words[0].
It can be proven that 1 is the maximum number of pairs that can be formed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> In this example, we are unable to form any pair of strings.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>words[i].length == 2</code></li>
<li><code>words</code> consists of distinct strings.</li>
<li><code>words[i]</code> contains only lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Simulation
|
TypeScript
|
function maximumNumberOfStringPairs(words: string[]): number {
const cnt: { [key: number]: number } = {};
let ans = 0;
for (const w of words) {
const [a, b] = [w.charCodeAt(0) - 97, w.charCodeAt(w.length - 1) - 97];
ans += cnt[(b << 5) | a] || 0;
cnt[(a << 5) | b] = (cnt[(a << 5) | b] || 0) + 1;
}
return ans;
}
|
2,745
|
Construct the Longest New String
|
Medium
|
<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>You have <code>x</code> strings equal to <code>"AA"</code>, <code>y</code> strings equal to <code>"BB"</code>, and <code>z</code> strings equal to <code>"AB"</code>. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain <code>"AAA"</code> or <code>"BBB"</code> as a substring.</p>
<p>Return <em>the maximum possible length of the new string</em>.</p>
<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 2, y = 5, z = 1
<strong>Output:</strong> 12
<strong>Explanation: </strong>We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
That string has length 12, and we can show that it is impossible to construct a string of longer length.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 2, z = 2
<strong>Output:</strong> 14
<strong>Explanation:</strong> We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
That string has length 14, and we can show that it is impossible to construct a string of longer length.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 50</code></li>
</ul>
|
Greedy; Brainteaser; Math; Dynamic Programming
|
C++
|
class Solution {
public:
int longestString(int x, int y, int z) {
if (x < y) {
return (x * 2 + z + 1) * 2;
}
if (x > y) {
return (y * 2 + z + 1) * 2;
}
return (x + y + z) * 2;
}
};
|
2,745
|
Construct the Longest New String
|
Medium
|
<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>You have <code>x</code> strings equal to <code>"AA"</code>, <code>y</code> strings equal to <code>"BB"</code>, and <code>z</code> strings equal to <code>"AB"</code>. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain <code>"AAA"</code> or <code>"BBB"</code> as a substring.</p>
<p>Return <em>the maximum possible length of the new string</em>.</p>
<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 2, y = 5, z = 1
<strong>Output:</strong> 12
<strong>Explanation: </strong>We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
That string has length 12, and we can show that it is impossible to construct a string of longer length.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 2, z = 2
<strong>Output:</strong> 14
<strong>Explanation:</strong> We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
That string has length 14, and we can show that it is impossible to construct a string of longer length.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 50</code></li>
</ul>
|
Greedy; Brainteaser; Math; Dynamic Programming
|
Go
|
func longestString(x int, y int, z int) int {
if x < y {
return (x*2 + z + 1) * 2
}
if x > y {
return (y*2 + z + 1) * 2
}
return (x + y + z) * 2
}
|
2,745
|
Construct the Longest New String
|
Medium
|
<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>You have <code>x</code> strings equal to <code>"AA"</code>, <code>y</code> strings equal to <code>"BB"</code>, and <code>z</code> strings equal to <code>"AB"</code>. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain <code>"AAA"</code> or <code>"BBB"</code> as a substring.</p>
<p>Return <em>the maximum possible length of the new string</em>.</p>
<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 2, y = 5, z = 1
<strong>Output:</strong> 12
<strong>Explanation: </strong>We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
That string has length 12, and we can show that it is impossible to construct a string of longer length.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 2, z = 2
<strong>Output:</strong> 14
<strong>Explanation:</strong> We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
That string has length 14, and we can show that it is impossible to construct a string of longer length.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 50</code></li>
</ul>
|
Greedy; Brainteaser; Math; Dynamic Programming
|
Java
|
class Solution {
public int longestString(int x, int y, int z) {
if (x < y) {
return (x * 2 + z + 1) * 2;
}
if (x > y) {
return (y * 2 + z + 1) * 2;
}
return (x + y + z) * 2;
}
}
|
2,745
|
Construct the Longest New String
|
Medium
|
<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>You have <code>x</code> strings equal to <code>"AA"</code>, <code>y</code> strings equal to <code>"BB"</code>, and <code>z</code> strings equal to <code>"AB"</code>. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain <code>"AAA"</code> or <code>"BBB"</code> as a substring.</p>
<p>Return <em>the maximum possible length of the new string</em>.</p>
<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 2, y = 5, z = 1
<strong>Output:</strong> 12
<strong>Explanation: </strong>We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
That string has length 12, and we can show that it is impossible to construct a string of longer length.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 2, z = 2
<strong>Output:</strong> 14
<strong>Explanation:</strong> We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
That string has length 14, and we can show that it is impossible to construct a string of longer length.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 50</code></li>
</ul>
|
Greedy; Brainteaser; Math; Dynamic Programming
|
Python
|
class Solution:
def longestString(self, x: int, y: int, z: int) -> int:
if x < y:
return (x * 2 + z + 1) * 2
if x > y:
return (y * 2 + z + 1) * 2
return (x + y + z) * 2
|
2,745
|
Construct the Longest New String
|
Medium
|
<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>You have <code>x</code> strings equal to <code>"AA"</code>, <code>y</code> strings equal to <code>"BB"</code>, and <code>z</code> strings equal to <code>"AB"</code>. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain <code>"AAA"</code> or <code>"BBB"</code> as a substring.</p>
<p>Return <em>the maximum possible length of the new string</em>.</p>
<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 2, y = 5, z = 1
<strong>Output:</strong> 12
<strong>Explanation: </strong>We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
That string has length 12, and we can show that it is impossible to construct a string of longer length.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 2, z = 2
<strong>Output:</strong> 14
<strong>Explanation:</strong> We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
That string has length 14, and we can show that it is impossible to construct a string of longer length.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 50</code></li>
</ul>
|
Greedy; Brainteaser; Math; Dynamic Programming
|
TypeScript
|
function longestString(x: number, y: number, z: number): number {
if (x < y) {
return (x * 2 + z + 1) * 2;
}
if (x > y) {
return (y * 2 + z + 1) * 2;
}
return (x + y + z) * 2;
}
|
2,746
|
Decremental String Concatenation
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> containing <code>n</code> strings.</p>
<p>Let's define a <strong>join</strong> operation <code>join(x, y)</code> between two strings <code>x</code> and <code>y</code> as concatenating them into <code>xy</code>. However, if the last character of <code>x</code> is equal to the first character of <code>y</code>, one of them is <strong>deleted</strong>.</p>
<p>For example <code>join("ab", "ba") = "aba"</code> and <code>join("ab", "cde") = "abcde"</code>.</p>
<p>You are to perform <code>n - 1</code> <strong>join</strong> operations. Let <code>str<sub>0</sub> = words[0]</code>. Starting from <code>i = 1</code> up to <code>i = n - 1</code>, for the <code>i<sup>th</sup></code> operation, you can do one of the following:</p>
<ul>
<li>Make <code>str<sub>i</sub> = join(str<sub>i - 1</sub>, words[i])</code></li>
<li>Make <code>str<sub>i</sub> = join(words[i], str<sub>i - 1</sub>)</code></li>
</ul>
<p>Your task is to <strong>minimize</strong> the length of <code>str<sub>n - 1</sub></code>.</p>
<p>Return <em>an integer denoting the minimum possible length of</em> <code>str<sub>n - 1</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab","bc"]
<strong>Output:</strong> 4
<strong>Explanation: </strong>In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aa"
str<sub>1</sub> = join(str<sub>0</sub>, "ab") = "aab"
str<sub>2</sub> = join(str<sub>1</sub>, "bc") = "aabc"
It can be shown that the minimum possible length of str<sub>2</sub> is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","b"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, str<sub>0</sub> = "ab", there are two ways to get str<sub>1</sub>:
join(str<sub>0</sub>, "b") = "ab" or join("b", str<sub>0</sub>) = "bab".
The first string, "ab", has the minimum length. Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aaa","c","aba"]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aaa"
str<sub>1</sub> = join(str<sub>0</sub>, "c") = "aaac"
str<sub>2</sub> = join("aba", str<sub>1</sub>) = "abaaac"
It can be shown that the minimum possible length of str<sub>2</sub> is 6.
</pre>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li>Each character in <code>words[i]</code> is an English lowercase letter</li>
</ul>
|
Array; String; Dynamic Programming
|
C++
|
class Solution {
public:
int minimizeConcatenatedLength(vector<string>& words) {
int n = words.size();
int f[n][26][26];
memset(f, 0, sizeof(f));
function<int(int, int, int)> dfs = [&](int i, int a, int b) {
if (i >= n) {
return 0;
}
if (f[i][a][b]) {
return f[i][a][b];
}
auto s = words[i];
int m = s.size();
int x = dfs(i + 1, a, s[m - 1] - 'a') - (s[0] - 'a' == b);
int y = dfs(i + 1, s[0] - 'a', b) - (s[m - 1] - 'a' == a);
return f[i][a][b] = m + min(x, y);
};
return words[0].size() + dfs(1, words[0].front() - 'a', words[0].back() - 'a');
}
};
|
2,746
|
Decremental String Concatenation
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> containing <code>n</code> strings.</p>
<p>Let's define a <strong>join</strong> operation <code>join(x, y)</code> between two strings <code>x</code> and <code>y</code> as concatenating them into <code>xy</code>. However, if the last character of <code>x</code> is equal to the first character of <code>y</code>, one of them is <strong>deleted</strong>.</p>
<p>For example <code>join("ab", "ba") = "aba"</code> and <code>join("ab", "cde") = "abcde"</code>.</p>
<p>You are to perform <code>n - 1</code> <strong>join</strong> operations. Let <code>str<sub>0</sub> = words[0]</code>. Starting from <code>i = 1</code> up to <code>i = n - 1</code>, for the <code>i<sup>th</sup></code> operation, you can do one of the following:</p>
<ul>
<li>Make <code>str<sub>i</sub> = join(str<sub>i - 1</sub>, words[i])</code></li>
<li>Make <code>str<sub>i</sub> = join(words[i], str<sub>i - 1</sub>)</code></li>
</ul>
<p>Your task is to <strong>minimize</strong> the length of <code>str<sub>n - 1</sub></code>.</p>
<p>Return <em>an integer denoting the minimum possible length of</em> <code>str<sub>n - 1</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab","bc"]
<strong>Output:</strong> 4
<strong>Explanation: </strong>In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aa"
str<sub>1</sub> = join(str<sub>0</sub>, "ab") = "aab"
str<sub>2</sub> = join(str<sub>1</sub>, "bc") = "aabc"
It can be shown that the minimum possible length of str<sub>2</sub> is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","b"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, str<sub>0</sub> = "ab", there are two ways to get str<sub>1</sub>:
join(str<sub>0</sub>, "b") = "ab" or join("b", str<sub>0</sub>) = "bab".
The first string, "ab", has the minimum length. Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aaa","c","aba"]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aaa"
str<sub>1</sub> = join(str<sub>0</sub>, "c") = "aaac"
str<sub>2</sub> = join("aba", str<sub>1</sub>) = "abaaac"
It can be shown that the minimum possible length of str<sub>2</sub> is 6.
</pre>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li>Each character in <code>words[i]</code> is an English lowercase letter</li>
</ul>
|
Array; String; Dynamic Programming
|
Go
|
func minimizeConcatenatedLength(words []string) int {
n := len(words)
f := make([][26][26]int, n)
var dfs func(i, a, b int) int
dfs = func(i, a, b int) int {
if i >= n {
return 0
}
if f[i][a][b] > 0 {
return f[i][a][b]
}
s := words[i]
m := len(s)
x := dfs(i+1, a, int(s[m-1]-'a'))
y := dfs(i+1, int(s[0]-'a'), b)
if int(s[0]-'a') == b {
x--
}
if int(s[m-1]-'a') == a {
y--
}
f[i][a][b] = m + min(x, y)
return f[i][a][b]
}
return len(words[0]) + dfs(1, int(words[0][0]-'a'), int(words[0][len(words[0])-1]-'a'))
}
|
2,746
|
Decremental String Concatenation
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> containing <code>n</code> strings.</p>
<p>Let's define a <strong>join</strong> operation <code>join(x, y)</code> between two strings <code>x</code> and <code>y</code> as concatenating them into <code>xy</code>. However, if the last character of <code>x</code> is equal to the first character of <code>y</code>, one of them is <strong>deleted</strong>.</p>
<p>For example <code>join("ab", "ba") = "aba"</code> and <code>join("ab", "cde") = "abcde"</code>.</p>
<p>You are to perform <code>n - 1</code> <strong>join</strong> operations. Let <code>str<sub>0</sub> = words[0]</code>. Starting from <code>i = 1</code> up to <code>i = n - 1</code>, for the <code>i<sup>th</sup></code> operation, you can do one of the following:</p>
<ul>
<li>Make <code>str<sub>i</sub> = join(str<sub>i - 1</sub>, words[i])</code></li>
<li>Make <code>str<sub>i</sub> = join(words[i], str<sub>i - 1</sub>)</code></li>
</ul>
<p>Your task is to <strong>minimize</strong> the length of <code>str<sub>n - 1</sub></code>.</p>
<p>Return <em>an integer denoting the minimum possible length of</em> <code>str<sub>n - 1</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab","bc"]
<strong>Output:</strong> 4
<strong>Explanation: </strong>In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aa"
str<sub>1</sub> = join(str<sub>0</sub>, "ab") = "aab"
str<sub>2</sub> = join(str<sub>1</sub>, "bc") = "aabc"
It can be shown that the minimum possible length of str<sub>2</sub> is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","b"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, str<sub>0</sub> = "ab", there are two ways to get str<sub>1</sub>:
join(str<sub>0</sub>, "b") = "ab" or join("b", str<sub>0</sub>) = "bab".
The first string, "ab", has the minimum length. Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aaa","c","aba"]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aaa"
str<sub>1</sub> = join(str<sub>0</sub>, "c") = "aaac"
str<sub>2</sub> = join("aba", str<sub>1</sub>) = "abaaac"
It can be shown that the minimum possible length of str<sub>2</sub> is 6.
</pre>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li>Each character in <code>words[i]</code> is an English lowercase letter</li>
</ul>
|
Array; String; Dynamic Programming
|
Java
|
class Solution {
private Integer[][][] f;
private String[] words;
private int n;
public int minimizeConcatenatedLength(String[] words) {
n = words.length;
this.words = words;
f = new Integer[n][26][26];
return words[0].length()
+ dfs(1, words[0].charAt(0) - 'a', words[0].charAt(words[0].length() - 1) - 'a');
}
private int dfs(int i, int a, int b) {
if (i >= n) {
return 0;
}
if (f[i][a][b] != null) {
return f[i][a][b];
}
String s = words[i];
int m = s.length();
int x = dfs(i + 1, a, s.charAt(m - 1) - 'a') - (s.charAt(0) - 'a' == b ? 1 : 0);
int y = dfs(i + 1, s.charAt(0) - 'a', b) - (s.charAt(m - 1) - 'a' == a ? 1 : 0);
return f[i][a][b] = m + Math.min(x, y);
}
}
|
2,746
|
Decremental String Concatenation
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> containing <code>n</code> strings.</p>
<p>Let's define a <strong>join</strong> operation <code>join(x, y)</code> between two strings <code>x</code> and <code>y</code> as concatenating them into <code>xy</code>. However, if the last character of <code>x</code> is equal to the first character of <code>y</code>, one of them is <strong>deleted</strong>.</p>
<p>For example <code>join("ab", "ba") = "aba"</code> and <code>join("ab", "cde") = "abcde"</code>.</p>
<p>You are to perform <code>n - 1</code> <strong>join</strong> operations. Let <code>str<sub>0</sub> = words[0]</code>. Starting from <code>i = 1</code> up to <code>i = n - 1</code>, for the <code>i<sup>th</sup></code> operation, you can do one of the following:</p>
<ul>
<li>Make <code>str<sub>i</sub> = join(str<sub>i - 1</sub>, words[i])</code></li>
<li>Make <code>str<sub>i</sub> = join(words[i], str<sub>i - 1</sub>)</code></li>
</ul>
<p>Your task is to <strong>minimize</strong> the length of <code>str<sub>n - 1</sub></code>.</p>
<p>Return <em>an integer denoting the minimum possible length of</em> <code>str<sub>n - 1</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab","bc"]
<strong>Output:</strong> 4
<strong>Explanation: </strong>In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aa"
str<sub>1</sub> = join(str<sub>0</sub>, "ab") = "aab"
str<sub>2</sub> = join(str<sub>1</sub>, "bc") = "aabc"
It can be shown that the minimum possible length of str<sub>2</sub> is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","b"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, str<sub>0</sub> = "ab", there are two ways to get str<sub>1</sub>:
join(str<sub>0</sub>, "b") = "ab" or join("b", str<sub>0</sub>) = "bab".
The first string, "ab", has the minimum length. Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aaa","c","aba"]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aaa"
str<sub>1</sub> = join(str<sub>0</sub>, "c") = "aaac"
str<sub>2</sub> = join("aba", str<sub>1</sub>) = "abaaac"
It can be shown that the minimum possible length of str<sub>2</sub> is 6.
</pre>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li>Each character in <code>words[i]</code> is an English lowercase letter</li>
</ul>
|
Array; String; Dynamic Programming
|
Python
|
class Solution:
def minimizeConcatenatedLength(self, words: List[str]) -> int:
@cache
def dfs(i: int, a: str, b: str) -> int:
if i >= len(words):
return 0
s = words[i]
x = dfs(i + 1, a, s[-1]) - int(s[0] == b)
y = dfs(i + 1, s[0], b) - int(s[-1] == a)
return len(s) + min(x, y)
return len(words[0]) + dfs(1, words[0][0], words[0][-1])
|
2,746
|
Decremental String Concatenation
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>words</code> containing <code>n</code> strings.</p>
<p>Let's define a <strong>join</strong> operation <code>join(x, y)</code> between two strings <code>x</code> and <code>y</code> as concatenating them into <code>xy</code>. However, if the last character of <code>x</code> is equal to the first character of <code>y</code>, one of them is <strong>deleted</strong>.</p>
<p>For example <code>join("ab", "ba") = "aba"</code> and <code>join("ab", "cde") = "abcde"</code>.</p>
<p>You are to perform <code>n - 1</code> <strong>join</strong> operations. Let <code>str<sub>0</sub> = words[0]</code>. Starting from <code>i = 1</code> up to <code>i = n - 1</code>, for the <code>i<sup>th</sup></code> operation, you can do one of the following:</p>
<ul>
<li>Make <code>str<sub>i</sub> = join(str<sub>i - 1</sub>, words[i])</code></li>
<li>Make <code>str<sub>i</sub> = join(words[i], str<sub>i - 1</sub>)</code></li>
</ul>
<p>Your task is to <strong>minimize</strong> the length of <code>str<sub>n - 1</sub></code>.</p>
<p>Return <em>an integer denoting the minimum possible length of</em> <code>str<sub>n - 1</sub></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["aa","ab","bc"]
<strong>Output:</strong> 4
<strong>Explanation: </strong>In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aa"
str<sub>1</sub> = join(str<sub>0</sub>, "ab") = "aab"
str<sub>2</sub> = join(str<sub>1</sub>, "bc") = "aabc"
It can be shown that the minimum possible length of str<sub>2</sub> is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["ab","b"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, str<sub>0</sub> = "ab", there are two ways to get str<sub>1</sub>:
join(str<sub>0</sub>, "b") = "ab" or join("b", str<sub>0</sub>) = "bab".
The first string, "ab", has the minimum length. Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["aaa","c","aba"]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we can perform join operations in the following order to minimize the length of str<sub>2</sub>:
str<sub>0</sub> = "aaa"
str<sub>1</sub> = join(str<sub>0</sub>, "c") = "aaac"
str<sub>2</sub> = join("aba", str<sub>1</sub>) = "abaaac"
It can be shown that the minimum possible length of str<sub>2</sub> is 6.
</pre>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li>Each character in <code>words[i]</code> is an English lowercase letter</li>
</ul>
|
Array; String; Dynamic Programming
|
TypeScript
|
function minimizeConcatenatedLength(words: string[]): number {
const n = words.length;
const f: number[][][] = Array(n)
.fill(0)
.map(() =>
Array(26)
.fill(0)
.map(() => Array(26).fill(0)),
);
const dfs = (i: number, a: number, b: number): number => {
if (i >= n) {
return 0;
}
if (f[i][a][b] > 0) {
return f[i][a][b];
}
const s = words[i];
const m = s.length;
const x =
dfs(i + 1, a, s[m - 1].charCodeAt(0) - 97) - (s[0].charCodeAt(0) - 97 === b ? 1 : 0);
const y =
dfs(i + 1, s[0].charCodeAt(0) - 97, b) - (s[m - 1].charCodeAt(0) - 97 === a ? 1 : 0);
return (f[i][a][b] = Math.min(x + m, y + m));
};
return (
words[0].length +
dfs(1, words[0][0].charCodeAt(0) - 97, words[0][words[0].length - 1].charCodeAt(0) - 97)
);
}
|
2,747
|
Count Zero Request Servers
|
Medium
|
<p>You are given an integer <code>n</code> denoting the total number of servers and a <strong>2D</strong> <strong>0-indexed </strong>integer array <code>logs</code>, where <code>logs[i] = [server_id, time]</code> denotes that the server with id <code>server_id</code> received a request at time <code>time</code>.</p>
<p>You are also given an integer <code>x</code> and a <strong>0-indexed</strong> integer array <code>queries</code>.</p>
<p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of length</em> <code>queries.length</code> <em>where</em> <code>arr[i]</code> <em>represents the number of servers that <strong>did not receive</strong> any requests during the time interval</em> <code>[queries[i] - x, queries[i]]</code>.</p>
<p>Note that the time intervals are inclusive.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.
For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong>
For queries[0]: All servers get at least one request in the duration of [1, 3].
For queries[1]: Only server with id 3 gets no request in the duration [2,4].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= logs.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">logs[i].length == 2</font></code></li>
<li><code>1 <= logs[i][0] <= n</code></li>
<li><code>1 <= logs[i][1] <= 10<sup>6</sup></code></li>
<li><code>1 <= x <= 10<sup>5</sup></code></li>
<li><code>x < queries[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Sliding Window
|
C++
|
class Solution {
public:
vector<int> countServers(int n, vector<vector<int>>& logs, int x, vector<int>& queries) {
sort(logs.begin(), logs.end(), [](const auto& a, const auto& b) {
return a[1] < b[1];
});
int m = queries.size();
vector<pair<int, int>> qs(m);
for (int i = 0; i < m; ++i) {
qs[i] = {queries[i], i};
}
sort(qs.begin(), qs.end());
unordered_map<int, int> cnt;
vector<int> ans(m);
int j = 0, k = 0;
for (auto& [r, i] : qs) {
int l = r - x;
while (k < logs.size() && logs[k][1] <= r) {
++cnt[logs[k++][0]];
}
while (j < logs.size() && logs[j][1] < l) {
if (--cnt[logs[j][0]] == 0) {
cnt.erase(logs[j][0]);
}
++j;
}
ans[i] = n - cnt.size();
}
return ans;
}
};
|
2,747
|
Count Zero Request Servers
|
Medium
|
<p>You are given an integer <code>n</code> denoting the total number of servers and a <strong>2D</strong> <strong>0-indexed </strong>integer array <code>logs</code>, where <code>logs[i] = [server_id, time]</code> denotes that the server with id <code>server_id</code> received a request at time <code>time</code>.</p>
<p>You are also given an integer <code>x</code> and a <strong>0-indexed</strong> integer array <code>queries</code>.</p>
<p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of length</em> <code>queries.length</code> <em>where</em> <code>arr[i]</code> <em>represents the number of servers that <strong>did not receive</strong> any requests during the time interval</em> <code>[queries[i] - x, queries[i]]</code>.</p>
<p>Note that the time intervals are inclusive.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.
For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong>
For queries[0]: All servers get at least one request in the duration of [1, 3].
For queries[1]: Only server with id 3 gets no request in the duration [2,4].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= logs.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">logs[i].length == 2</font></code></li>
<li><code>1 <= logs[i][0] <= n</code></li>
<li><code>1 <= logs[i][1] <= 10<sup>6</sup></code></li>
<li><code>1 <= x <= 10<sup>5</sup></code></li>
<li><code>x < queries[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Sliding Window
|
Go
|
func countServers(n int, logs [][]int, x int, queries []int) []int {
sort.Slice(logs, func(i, j int) bool { return logs[i][1] < logs[j][1] })
m := len(queries)
qs := make([][2]int, m)
for i, q := range queries {
qs[i] = [2]int{q, i}
}
sort.Slice(qs, func(i, j int) bool { return qs[i][0] < qs[j][0] })
cnt := map[int]int{}
ans := make([]int, m)
j, k := 0, 0
for _, q := range qs {
r, i := q[0], q[1]
l := r - x
for k < len(logs) && logs[k][1] <= r {
cnt[logs[k][0]]++
k++
}
for j < len(logs) && logs[j][1] < l {
cnt[logs[j][0]]--
if cnt[logs[j][0]] == 0 {
delete(cnt, logs[j][0])
}
j++
}
ans[i] = n - len(cnt)
}
return ans
}
|
2,747
|
Count Zero Request Servers
|
Medium
|
<p>You are given an integer <code>n</code> denoting the total number of servers and a <strong>2D</strong> <strong>0-indexed </strong>integer array <code>logs</code>, where <code>logs[i] = [server_id, time]</code> denotes that the server with id <code>server_id</code> received a request at time <code>time</code>.</p>
<p>You are also given an integer <code>x</code> and a <strong>0-indexed</strong> integer array <code>queries</code>.</p>
<p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of length</em> <code>queries.length</code> <em>where</em> <code>arr[i]</code> <em>represents the number of servers that <strong>did not receive</strong> any requests during the time interval</em> <code>[queries[i] - x, queries[i]]</code>.</p>
<p>Note that the time intervals are inclusive.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.
For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong>
For queries[0]: All servers get at least one request in the duration of [1, 3].
For queries[1]: Only server with id 3 gets no request in the duration [2,4].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= logs.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">logs[i].length == 2</font></code></li>
<li><code>1 <= logs[i][0] <= n</code></li>
<li><code>1 <= logs[i][1] <= 10<sup>6</sup></code></li>
<li><code>1 <= x <= 10<sup>5</sup></code></li>
<li><code>x < queries[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Sliding Window
|
Java
|
class Solution {
public int[] countServers(int n, int[][] logs, int x, int[] queries) {
Arrays.sort(logs, (a, b) -> a[1] - b[1]);
int m = queries.length;
int[][] qs = new int[m][0];
for (int i = 0; i < m; ++i) {
qs[i] = new int[] {queries[i], i};
}
Arrays.sort(qs, (a, b) -> a[0] - b[0]);
Map<Integer, Integer> cnt = new HashMap<>();
int[] ans = new int[m];
int j = 0, k = 0;
for (var q : qs) {
int r = q[0], i = q[1];
int l = r - x;
while (k < logs.length && logs[k][1] <= r) {
cnt.merge(logs[k++][0], 1, Integer::sum);
}
while (j < logs.length && logs[j][1] < l) {
if (cnt.merge(logs[j][0], -1, Integer::sum) == 0) {
cnt.remove(logs[j][0]);
}
j++;
}
ans[i] = n - cnt.size();
}
return ans;
}
}
|
2,747
|
Count Zero Request Servers
|
Medium
|
<p>You are given an integer <code>n</code> denoting the total number of servers and a <strong>2D</strong> <strong>0-indexed </strong>integer array <code>logs</code>, where <code>logs[i] = [server_id, time]</code> denotes that the server with id <code>server_id</code> received a request at time <code>time</code>.</p>
<p>You are also given an integer <code>x</code> and a <strong>0-indexed</strong> integer array <code>queries</code>.</p>
<p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of length</em> <code>queries.length</code> <em>where</em> <code>arr[i]</code> <em>represents the number of servers that <strong>did not receive</strong> any requests during the time interval</em> <code>[queries[i] - x, queries[i]]</code>.</p>
<p>Note that the time intervals are inclusive.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.
For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong>
For queries[0]: All servers get at least one request in the duration of [1, 3].
For queries[1]: Only server with id 3 gets no request in the duration [2,4].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= logs.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">logs[i].length == 2</font></code></li>
<li><code>1 <= logs[i][0] <= n</code></li>
<li><code>1 <= logs[i][1] <= 10<sup>6</sup></code></li>
<li><code>1 <= x <= 10<sup>5</sup></code></li>
<li><code>x < queries[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Sliding Window
|
Python
|
class Solution:
def countServers(
self, n: int, logs: List[List[int]], x: int, queries: List[int]
) -> List[int]:
cnt = Counter()
logs.sort(key=lambda x: x[1])
ans = [0] * len(queries)
j = k = 0
for r, i in sorted(zip(queries, count())):
l = r - x
while k < len(logs) and logs[k][1] <= r:
cnt[logs[k][0]] += 1
k += 1
while j < len(logs) and logs[j][1] < l:
cnt[logs[j][0]] -= 1
if cnt[logs[j][0]] == 0:
cnt.pop(logs[j][0])
j += 1
ans[i] = n - len(cnt)
return ans
|
2,747
|
Count Zero Request Servers
|
Medium
|
<p>You are given an integer <code>n</code> denoting the total number of servers and a <strong>2D</strong> <strong>0-indexed </strong>integer array <code>logs</code>, where <code>logs[i] = [server_id, time]</code> denotes that the server with id <code>server_id</code> received a request at time <code>time</code>.</p>
<p>You are also given an integer <code>x</code> and a <strong>0-indexed</strong> integer array <code>queries</code>.</p>
<p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of length</em> <code>queries.length</code> <em>where</em> <code>arr[i]</code> <em>represents the number of servers that <strong>did not receive</strong> any requests during the time interval</em> <code>[queries[i] - x, queries[i]]</code>.</p>
<p>Note that the time intervals are inclusive.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong>
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.
For queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong>
For queries[0]: All servers get at least one request in the duration of [1, 3].
For queries[1]: Only server with id 3 gets no request in the duration [2,4].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= logs.length <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">logs[i].length == 2</font></code></li>
<li><code>1 <= logs[i][0] <= n</code></li>
<li><code>1 <= logs[i][1] <= 10<sup>6</sup></code></li>
<li><code>1 <= x <= 10<sup>5</sup></code></li>
<li><code>x < queries[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Sliding Window
|
TypeScript
|
function countServers(n: number, logs: number[][], x: number, queries: number[]): number[] {
logs.sort((a, b) => a[1] - b[1]);
const m = queries.length;
const qs: number[][] = [];
for (let i = 0; i < m; ++i) {
qs.push([queries[i], i]);
}
qs.sort((a, b) => a[0] - b[0]);
const cnt: Map<number, number> = new Map();
const ans: number[] = new Array(m);
let j = 0;
let k = 0;
for (const [r, i] of qs) {
const l = r - x;
while (k < logs.length && logs[k][1] <= r) {
cnt.set(logs[k][0], (cnt.get(logs[k][0]) || 0) + 1);
++k;
}
while (j < logs.length && logs[j][1] < l) {
cnt.set(logs[j][0], (cnt.get(logs[j][0]) || 0) - 1);
if (cnt.get(logs[j][0]) === 0) {
cnt.delete(logs[j][0]);
}
++j;
}
ans[i] = n - cnt.size;
}
return ans;
}
|
2,748
|
Number of Beautiful Pairs
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>. A pair of indices <code>i</code>, <code>j</code> where <code>0 <= i < j < nums.length</code> is called beautiful if the <strong>first digit</strong> of <code>nums[i]</code> and the <strong>last digit</strong> of <code>nums[j]</code> are <strong>coprime</strong>.</p>
<p>Return <em>the total number of beautiful pairs in </em><code>nums</code>.</p>
<p>Two integers <code>x</code> and <code>y</code> are <strong>coprime</strong> if there is no integer greater than 1 that divides both of them. In other words, <code>x</code> and <code>y</code> are coprime if <code>gcd(x, y) == 1</code>, where <code>gcd(x, y)</code> is the <strong>greatest common divisor</strong> of <code>x</code> and <code>y</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,5,1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [11,21,12]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 9999</code></li>
<li><code>nums[i] % 10 != 0</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Number Theory
|
C++
|
class Solution {
public:
int countBeautifulPairs(vector<int>& nums) {
int cnt[10]{};
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
};
|
2,748
|
Number of Beautiful Pairs
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>. A pair of indices <code>i</code>, <code>j</code> where <code>0 <= i < j < nums.length</code> is called beautiful if the <strong>first digit</strong> of <code>nums[i]</code> and the <strong>last digit</strong> of <code>nums[j]</code> are <strong>coprime</strong>.</p>
<p>Return <em>the total number of beautiful pairs in </em><code>nums</code>.</p>
<p>Two integers <code>x</code> and <code>y</code> are <strong>coprime</strong> if there is no integer greater than 1 that divides both of them. In other words, <code>x</code> and <code>y</code> are coprime if <code>gcd(x, y) == 1</code>, where <code>gcd(x, y)</code> is the <strong>greatest common divisor</strong> of <code>x</code> and <code>y</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,5,1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [11,21,12]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 9999</code></li>
<li><code>nums[i] % 10 != 0</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Number Theory
|
Go
|
func countBeautifulPairs(nums []int) (ans int) {
cnt := [10]int{}
for _, x := range nums {
for y := 0; y < 10; y++ {
if cnt[y] > 0 && gcd(x%10, y) == 1 {
ans += cnt[y]
}
}
for x > 9 {
x /= 10
}
cnt[x]++
}
return
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
2,748
|
Number of Beautiful Pairs
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>. A pair of indices <code>i</code>, <code>j</code> where <code>0 <= i < j < nums.length</code> is called beautiful if the <strong>first digit</strong> of <code>nums[i]</code> and the <strong>last digit</strong> of <code>nums[j]</code> are <strong>coprime</strong>.</p>
<p>Return <em>the total number of beautiful pairs in </em><code>nums</code>.</p>
<p>Two integers <code>x</code> and <code>y</code> are <strong>coprime</strong> if there is no integer greater than 1 that divides both of them. In other words, <code>x</code> and <code>y</code> are coprime if <code>gcd(x, y) == 1</code>, where <code>gcd(x, y)</code> is the <strong>greatest common divisor</strong> of <code>x</code> and <code>y</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,5,1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [11,21,12]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 9999</code></li>
<li><code>nums[i] % 10 != 0</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Number Theory
|
Java
|
class Solution {
public int countBeautifulPairs(int[] nums) {
int[] cnt = new int[10];
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
2,748
|
Number of Beautiful Pairs
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>. A pair of indices <code>i</code>, <code>j</code> where <code>0 <= i < j < nums.length</code> is called beautiful if the <strong>first digit</strong> of <code>nums[i]</code> and the <strong>last digit</strong> of <code>nums[j]</code> are <strong>coprime</strong>.</p>
<p>Return <em>the total number of beautiful pairs in </em><code>nums</code>.</p>
<p>Two integers <code>x</code> and <code>y</code> are <strong>coprime</strong> if there is no integer greater than 1 that divides both of them. In other words, <code>x</code> and <code>y</code> are coprime if <code>gcd(x, y) == 1</code>, where <code>gcd(x, y)</code> is the <strong>greatest common divisor</strong> of <code>x</code> and <code>y</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,5,1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [11,21,12]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 9999</code></li>
<li><code>nums[i] % 10 != 0</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Number Theory
|
Python
|
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
cnt = [0] * 10
ans = 0
for x in nums:
for y in range(10):
if cnt[y] and gcd(x % 10, y) == 1:
ans += cnt[y]
cnt[int(str(x)[0])] += 1
return ans
|
2,748
|
Number of Beautiful Pairs
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>. A pair of indices <code>i</code>, <code>j</code> where <code>0 <= i < j < nums.length</code> is called beautiful if the <strong>first digit</strong> of <code>nums[i]</code> and the <strong>last digit</strong> of <code>nums[j]</code> are <strong>coprime</strong>.</p>
<p>Return <em>the total number of beautiful pairs in </em><code>nums</code>.</p>
<p>Two integers <code>x</code> and <code>y</code> are <strong>coprime</strong> if there is no integer greater than 1 that divides both of them. In other words, <code>x</code> and <code>y</code> are coprime if <code>gcd(x, y) == 1</code>, where <code>gcd(x, y)</code> is the <strong>greatest common divisor</strong> of <code>x</code> and <code>y</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,5,1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 beautiful pairs in nums:
When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.
When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.
When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.
When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.
Thus, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [11,21,12]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful pairs:
When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.
When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.
Thus, we return 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 9999</code></li>
<li><code>nums[i] % 10 != 0</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Number Theory
|
TypeScript
|
function countBeautifulPairs(nums: number[]): number {
const cnt: number[] = Array(10).fill(0);
let ans = 0;
for (let x of nums) {
for (let y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) === 1) {
ans += cnt[y];
}
}
while (x > 9) {
x = Math.floor(x / 10);
}
++cnt[x];
}
return ans;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
C++
|
class Solution {
public:
int makeTheIntegerZero(int num1, int num2) {
using ll = long long;
for (ll k = 1;; ++k) {
ll x = num1 - k * num2;
if (x < 0) {
break;
}
if (__builtin_popcountll(x) <= k && k <= x) {
return k;
}
}
return -1;
}
};
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
C#
|
public class Solution {
public int MakeTheIntegerZero(int num1, int num2) {
long a = num1, b = num2;
for (long k = 1; ; ++k) {
long x = a - k * b;
if (x < 0) {
break;
}
if (BitOperations.PopCount((ulong)x) <= k && k <= x) {
return (int)k;
}
}
return -1;
}
}
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
Go
|
func makeTheIntegerZero(num1 int, num2 int) int {
for k := 1; ; k++ {
x := num1 - k*num2
if x < 0 {
break
}
if bits.OnesCount(uint(x)) <= k && k <= x {
return k
}
}
return -1
}
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
Java
|
class Solution {
public int makeTheIntegerZero(int num1, int num2) {
for (long k = 1;; ++k) {
long x = num1 - k * num2;
if (x < 0) {
break;
}
if (Long.bitCount(x) <= k && k <= x) {
return (int) k;
}
}
return -1;
}
}
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
Python
|
class Solution:
def makeTheIntegerZero(self, num1: int, num2: int) -> int:
for k in count(1):
x = num1 - k * num2
if x < 0:
break
if x.bit_count() <= k <= x:
return k
return -1
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
Rust
|
impl Solution {
pub fn make_the_integer_zero(num1: i32, num2: i32) -> i32 {
let num1 = num1 as i64;
let num2 = num2 as i64;
for k in 1.. {
let x = num1 - k * num2;
if x < 0 {
break;
}
if (x.count_ones() as i64) <= k && k <= x {
return k as i32;
}
}
-1
}
}
|
2,749
|
Minimum Operations to Make the Integer Zero
|
Medium
|
<p>You are given two integers <code>num1</code> and <code>num2</code>.</p>
<p>In one operation, you can choose integer <code>i</code> in the range <code>[0, 60]</code> and subtract <code>2<sup>i</sup> + num2</code> from <code>num1</code>.</p>
<p>Return <em>the integer denoting the <strong>minimum</strong> number of operations needed to make</em> <code>num1</code> <em>equal to</em> <code>0</code>.</p>
<p>If it is impossible to make <code>num1</code> equal to <code>0</code>, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num1 = 3, num2 = -2
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can make 3 equal to 0 with the following operations:
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and subtract 2<sup>2</sup> + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and subtract 2<sup>0</sup> + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num1 = 5, num2 = 7
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proven, that it is impossible to make 5 equal to 0 with the given operation.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1 <= 10<sup>9</sup></code></li>
<li><code><font face="monospace">-10<sup>9</sup> <= num2 <= 10<sup>9</sup></font></code></li>
</ul>
|
Bit Manipulation; Brainteaser; Enumeration
|
TypeScript
|
function makeTheIntegerZero(num1: number, num2: number): number {
for (let k = 1; ; ++k) {
let x = num1 - k * num2;
if (x < 0) {
break;
}
if (x.toString(2).replace(/0/g, '').length <= k && k <= x) {
return k;
}
}
return -1;
}
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
C++
|
class Solution {
public:
int numberOfGoodSubarraySplits(vector<int>& nums) {
const int mod = 1e9 + 7;
int ans = 1, j = -1;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == 0) {
continue;
}
if (j > -1) {
ans = 1LL * ans * (i - j) % mod;
}
j = i;
}
return j == -1 ? 0 : ans;
}
};
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
C#
|
public class Solution {
public int NumberOfGoodSubarraySplits(int[] nums) {
long ans = 1, j = -1;
int mod = 1000000007;
int n = nums.Length;
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) {
continue;
}
if (j > -1) {
ans = ans * (i - j) % mod;
}
j = i;
}
return j == -1 ? 0 : (int) ans;
}
}
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
Go
|
func numberOfGoodSubarraySplits(nums []int) int {
const mod int = 1e9 + 7
ans, j := 1, -1
for i, x := range nums {
if x == 0 {
continue
}
if j > -1 {
ans = ans * (i - j) % mod
}
j = i
}
if j == -1 {
return 0
}
return ans
}
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
Java
|
class Solution {
public int numberOfGoodSubarraySplits(int[] nums) {
final int mod = (int) 1e9 + 7;
int ans = 1, j = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == 0) {
continue;
}
if (j > -1) {
ans = (int) ((long) ans * (i - j) % mod);
}
j = i;
}
return j == -1 ? 0 : ans;
}
}
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
Python
|
class Solution:
def numberOfGoodSubarraySplits(self, nums: List[int]) -> int:
mod = 10**9 + 7
ans, j = 1, -1
for i, x in enumerate(nums):
if x == 0:
continue
if j > -1:
ans = ans * (i - j) % mod
j = i
return 0 if j == -1 else ans
|
2,750
|
Ways to Split Array Into Good Subarrays
|
Medium
|
<p>You are given a binary array <code>nums</code>.</p>
<p>A subarray of an array is <strong>good</strong> if it contains <strong>exactly</strong> <strong>one</strong> element with the value <code>1</code>.</p>
<p>Return <em>an integer denoting the number of ways to split the array </em><code>nums</code><em> into <strong>good</strong> subarrays</em>. As the number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to split nums into good subarrays:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 way to split nums into good subarrays:
- [0,1,0]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
</ul>
|
Array; Math; Dynamic Programming
|
TypeScript
|
function numberOfGoodSubarraySplits(nums: number[]): number {
let ans = 1;
let j = -1;
const mod = 10 ** 9 + 7;
const n = nums.length;
for (let i = 0; i < n; ++i) {
if (nums[i] === 0) {
continue;
}
if (j > -1) {
ans = (ans * (i - j)) % mod;
}
j = i;
}
return j === -1 ? 0 : ans;
}
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
C++
|
class Solution {
public:
vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
int n = positions.size();
vector<int> indices(n);
iota(indices.begin(), indices.end(), 0);
stack<int> st;
auto lambda = [&](int i, int j) { return positions[i] < positions[j]; };
sort(begin(indices), end(indices), lambda);
vector<int> result;
for (int currentIndex : indices) {
if (directions[currentIndex] == 'R') {
st.push(currentIndex);
} else {
while (!st.empty() && healths[currentIndex] > 0) {
int topIndex = st.top();
st.pop();
if (healths[topIndex] > healths[currentIndex]) {
healths[topIndex] -= 1;
healths[currentIndex] = 0;
st.push(topIndex);
} else if (healths[topIndex] < healths[currentIndex]) {
healths[currentIndex] -= 1;
healths[topIndex] = 0;
} else {
healths[currentIndex] = 0;
healths[topIndex] = 0;
}
}
}
}
for (int i = 0; i < n; ++i) {
if (healths[i] > 0) {
result.push_back(healths[i]);
}
}
return result;
}
};
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
Go
|
func survivedRobotsHealths(positions []int, healths []int, directions string) []int {
n := len(positions)
indices := make([]int, n)
for i := range indices {
indices[i] = i
}
sort.Slice(indices, func(i, j int) bool {
return positions[indices[i]] < positions[indices[j]]
})
stack := []int{}
for _, currentIndex := range indices {
if directions[currentIndex] == 'R' {
stack = append(stack, currentIndex)
} else {
for len(stack) > 0 && healths[currentIndex] > 0 {
topIndex := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if healths[topIndex] > healths[currentIndex] {
healths[topIndex] -= 1
healths[currentIndex] = 0
stack = append(stack, topIndex)
} else if healths[topIndex] < healths[currentIndex] {
healths[currentIndex] -= 1
healths[topIndex] = 0
} else {
healths[currentIndex] = 0
healths[topIndex] = 0
}
}
}
}
result := []int{}
for _, health := range healths {
if health > 0 {
result = append(result, health)
}
}
return result
}
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
Java
|
class Solution {
public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
int n = positions.length;
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
Arrays.sort(indices, (i, j) -> Integer.compare(positions[i], positions[j]));
Stack<Integer> stack = new Stack<>();
for (int currentIndex : indices) {
if (directions.charAt(currentIndex) == 'R') {
stack.push(currentIndex);
} else {
while (!stack.isEmpty() && healths[currentIndex] > 0) {
int topIndex = stack.pop();
if (healths[topIndex] > healths[currentIndex]) {
healths[topIndex] -= 1;
healths[currentIndex] = 0;
stack.push(topIndex);
} else if (healths[topIndex] < healths[currentIndex]) {
healths[currentIndex] -= 1;
healths[topIndex] = 0;
} else {
healths[currentIndex] = 0;
healths[topIndex] = 0;
}
}
}
}
List<Integer> result = new ArrayList<>();
for (int health : healths) {
if (health > 0) {
result.add(health);
}
}
return result;
}
}
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
JavaScript
|
/**
* @param {number[]} positions
* @param {number[]} healths
* @param {string} directions
* @return {number[]}
*/
var survivedRobotsHealths = function (positions, healths, directions) {
const idx = Array.from({ length: positions.length }, (_, i) => i);
const stk = [];
idx.sort((a, b) => positions[a] - positions[b]);
for (let iRight of idx) {
while (stk.length) {
const iLeft = stk.at(-1);
const havePair = directions[iLeft] === 'R' && directions[iRight] === 'L';
if (!havePair) break;
if (healths[iLeft] === healths[iRight]) {
healths[iLeft] = healths[iRight] = iRight = -1;
stk.pop();
break;
}
if (healths[iLeft] < healths[iRight]) {
healths[iLeft] = -1;
healths[iRight]--;
stk.pop();
} else {
healths[iRight] = iRight = -1;
healths[iLeft]--;
break;
}
}
if (iRight !== -1) stk.push(iRight);
}
return healths.filter(i => ~i);
};
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
Python
|
class Solution:
def survivedRobotsHealths(
self, positions: List[int], healths: List[int], directions: str
) -> List[int]:
n = len(positions)
indices = list(range(n))
stack = []
indices.sort(key=lambda i: positions[i])
for currentIndex in indices:
if directions[currentIndex] == "R":
stack.append(currentIndex)
else:
while stack and healths[currentIndex] > 0:
topIndex = stack.pop()
if healths[topIndex] > healths[currentIndex]:
healths[topIndex] -= 1
healths[currentIndex] = 0
stack.append(topIndex)
elif healths[topIndex] < healths[currentIndex]:
healths[currentIndex] -= 1
healths[topIndex] = 0
else:
healths[currentIndex] = 0
healths[topIndex] = 0
result = [health for health in healths if health > 0]
return result
|
2,751
|
Robot Collisions
|
Hard
|
<p>There are <code>n</code> <strong>1-indexed</strong> robots, each having a position on a line, health, and movement direction.</p>
<p>You are given <strong>0-indexed</strong> integer arrays <code>positions</code>, <code>healths</code>, and a string <code>directions</code> (<code>directions[i]</code> is either <strong>'L'</strong> for <strong>left</strong> or <strong>'R'</strong> for <strong>right</strong>). All integers in <code>positions</code> are <strong>unique</strong>.</p>
<p>All robots start moving on the line<strong> simultaneously</strong> at the <strong>same speed </strong>in their given directions. If two robots ever share the same position while moving, they will <strong>collide</strong>.</p>
<p>If two robots collide, the robot with <strong>lower health</strong> is <strong>removed</strong> from the line, and the health of the other robot <strong>decreases</strong> <strong>by one</strong>. The surviving robot continues in the <strong>same</strong> direction it was going. If both robots have the <strong>same</strong> health, they are both<strong> </strong>removed from the line.</p>
<p>Your task is to determine the <strong>health</strong> of the robots that survive the collisions, in the same <strong>order </strong>that the robots were given,<strong> </strong>i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.</p>
<p>Return <em>an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.</em></p>
<p><strong>Note:</strong> The positions may be unsorted.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="169" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516011718-12.png" width="808" /></p>
<pre>
<strong>Input:</strong> positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"
<strong>Output:</strong> [2,17,9,15,10]
<strong>Explanation:</strong> No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="176" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516004433-7.png" width="717" /></p>
<pre>
<strong>Input:</strong> positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"
<strong>Output:</strong> [14]
<strong>Explanation:</strong> There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].
</pre>
<p><strong class="example">Example 3:</strong></p>
<p><img height="172" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2751.Robot%20Collisions/images/image-20230516005114-9.png" width="732" /></p>
<pre>
<strong>Input:</strong> positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"
<strong>Output:</strong> []
<strong>Explanation:</strong> Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= positions.length == healths.length == directions.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= positions[i], healths[i] <= 10<sup>9</sup></code></li>
<li><code>directions[i] == 'L'</code> or <code>directions[i] == 'R'</code></li>
<li>All values in <code>positions</code> are distinct</li>
</ul>
|
Stack; Array; Sorting; Simulation
|
TypeScript
|
function survivedRobotsHealths(
positions: number[],
healths: number[],
directions: string,
): number[] {
const idx = Array.from({ length: positions.length }, (_, i) => i);
const stk: number[] = [];
idx.sort((a, b) => positions[a] - positions[b]);
for (let iRight of idx) {
while (stk.length) {
const iLeft = stk.at(-1)!;
const havePair = directions[iLeft] === 'R' && directions[iRight] === 'L';
if (!havePair) break;
if (healths[iLeft] === healths[iRight]) {
healths[iLeft] = healths[iRight] = iRight = -1;
stk.pop();
break;
}
if (healths[iLeft] < healths[iRight]) {
healths[iLeft] = -1;
healths[iRight]--;
stk.pop();
} else {
healths[iRight] = iRight = -1;
healths[iLeft]--;
break;
}
}
if (iRight !== -1) stk.push(iRight);
}
return healths.filter(i => ~i);
}
|
2,752
|
Customers with Maximum Number of Transactions on Consecutive Days
|
Hard
|
<p>Table: <code>Transactions</code></p>
<pre>
+------------------+------+
| Column Name | Type |
+------------------+------+
| transaction_id | int |
| customer_id | int |
| transaction_date | date |
| amount | int |
+------------------+------+
transaction_id is the column with unique values of this table.
Each row contains information about transactions that includes unique (customer_id, transaction_date) along with the corresponding customer_id and amount.
</pre>
<p>Write a solution to find all <code>customer_id</code> who made the maximum number of transactions on consecutive days.</p>
<p>Return all <code>customer_id</code> with the maximum number of consecutive transactions. Order the result table by <code>customer_id</code> in <strong>ascending</strong> order.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Transactions table:
+----------------+-------------+------------------+--------+
| transaction_id | customer_id | transaction_date | amount |
+----------------+-------------+------------------+--------+
| 1 | 101 | 2023-05-01 | 100 |
| 2 | 101 | 2023-05-02 | 150 |
| 3 | 101 | 2023-05-03 | 200 |
| 4 | 102 | 2023-05-01 | 50 |
| 5 | 102 | 2023-05-03 | 100 |
| 6 | 102 | 2023-05-04 | 200 |
| 7 | 105 | 2023-05-01 | 100 |
| 8 | 105 | 2023-05-02 | 150 |
| 9 | 105 | 2023-05-03 | 200 |
+----------------+-------------+------------------+--------+
<strong>Output:</strong>
+-------------+
| customer_id |
+-------------+
| 101 |
| 105 |
+-------------+
<strong>Explanation:</strong>
- customer_id 101 has a total of 3 transactions, and all of them are consecutive.
- customer_id 102 has a total of 3 transactions, but only 2 of them are consecutive.
- customer_id 105 has a total of 3 transactions, and all of them are consecutive.
In total, the highest number of consecutive transactions is 3, achieved by customer_id 101 and 105. The customer_id are sorted in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
s AS (
SELECT
customer_id,
DATE_SUB(
transaction_date,
INTERVAL ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY transaction_date
) DAY
) AS transaction_date
FROM Transactions
),
t AS (
SELECT customer_id, transaction_date, COUNT(1) AS cnt
FROM s
GROUP BY 1, 2
)
SELECT customer_id
FROM t
WHERE cnt = (SELECT MAX(cnt) FROM t)
ORDER BY customer_id;
|
2,753
|
Count Houses in a Circular Street II
|
Hard
|
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a <strong>circular</strong> street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses' doors could be open or closed initially (at least one is open).</p>
<p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p>
<p>The class <code>Street</code> contains the following functions which may help you:</p>
<ul>
<li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li>
<li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li>
<li><code>void moveRight()</code>: Move to the right house.</li>
</ul>
<p><strong>Note</strong> that by <strong>circular</strong> street, we mean if you number the houses from <code>1</code> to <code>n</code>, then the right house of <code>house<sub>i</sub></code> is <code>house<sub>i+1</sub></code> for <code>i < n</code>, and the right house of <code>house<sub>n</sub></code> is <code>house<sub>1</sub></code>.</p>
<p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> street = [1,1,1,1], k = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 houses, and all their doors are open.
The number of houses is less than k, which is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> street = [1,0,1,1,0], k = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == number of houses</code></li>
<li><code>1 <= n <= k <= 10<sup>5</sup></code></li>
<li><code>street</code> is circular by definition provided in the statement.</li>
<li>The input is generated such that at least one of the doors is open.</li>
</ul>
|
C++
|
/**
* Definition for a street.
* class Street {
* public:
* Street(vector<int> doors);
* void closeDoor();
* bool isDoorOpen();
* void moveRight();
* };
*/
class Solution {
public:
int houseCount(Street* street, int k) {
while (!street->isDoorOpen()) {
street->moveRight();
}
int ans = 0;
for (int i = 1; i <= k; ++i) {
street->moveRight();
if (street->isDoorOpen()) {
ans = i;
street->closeDoor();
}
}
return ans;
}
};
|
|
2,753
|
Count Houses in a Circular Street II
|
Hard
|
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a <strong>circular</strong> street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses' doors could be open or closed initially (at least one is open).</p>
<p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p>
<p>The class <code>Street</code> contains the following functions which may help you:</p>
<ul>
<li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li>
<li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li>
<li><code>void moveRight()</code>: Move to the right house.</li>
</ul>
<p><strong>Note</strong> that by <strong>circular</strong> street, we mean if you number the houses from <code>1</code> to <code>n</code>, then the right house of <code>house<sub>i</sub></code> is <code>house<sub>i+1</sub></code> for <code>i < n</code>, and the right house of <code>house<sub>n</sub></code> is <code>house<sub>1</sub></code>.</p>
<p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> street = [1,1,1,1], k = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 houses, and all their doors are open.
The number of houses is less than k, which is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> street = [1,0,1,1,0], k = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == number of houses</code></li>
<li><code>1 <= n <= k <= 10<sup>5</sup></code></li>
<li><code>street</code> is circular by definition provided in the statement.</li>
<li>The input is generated such that at least one of the doors is open.</li>
</ul>
|
Go
|
/**
* Definition for a street.
* type Street interface {
* CloseDoor()
* IsDoorOpen() bool
* MoveRight()
* }
*/
func houseCount(street Street, k int) (ans int) {
for !street.IsDoorOpen() {
street.MoveRight()
}
for i := 1; i <= k; i++ {
street.MoveRight()
if street.IsDoorOpen() {
ans = i
street.CloseDoor()
}
}
return
}
|
|
2,753
|
Count Houses in a Circular Street II
|
Hard
|
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a <strong>circular</strong> street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses' doors could be open or closed initially (at least one is open).</p>
<p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p>
<p>The class <code>Street</code> contains the following functions which may help you:</p>
<ul>
<li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li>
<li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li>
<li><code>void moveRight()</code>: Move to the right house.</li>
</ul>
<p><strong>Note</strong> that by <strong>circular</strong> street, we mean if you number the houses from <code>1</code> to <code>n</code>, then the right house of <code>house<sub>i</sub></code> is <code>house<sub>i+1</sub></code> for <code>i < n</code>, and the right house of <code>house<sub>n</sub></code> is <code>house<sub>1</sub></code>.</p>
<p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> street = [1,1,1,1], k = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 houses, and all their doors are open.
The number of houses is less than k, which is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> street = [1,0,1,1,0], k = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == number of houses</code></li>
<li><code>1 <= n <= k <= 10<sup>5</sup></code></li>
<li><code>street</code> is circular by definition provided in the statement.</li>
<li>The input is generated such that at least one of the doors is open.</li>
</ul>
|
Java
|
/**
* Definition for a street.
* class Street {
* public Street(int[] doors);
* public void closeDoor();
* public boolean isDoorOpen();
* public void moveRight();
* }
*/
class Solution {
public int houseCount(Street street, int k) {
while (!street.isDoorOpen()) {
street.moveRight();
}
int ans = 0;
for (int i = 1; i <= k; ++i) {
street.moveRight();
if (street.isDoorOpen()) {
ans = i;
street.closeDoor();
}
}
return ans;
}
}
|
|
2,753
|
Count Houses in a Circular Street II
|
Hard
|
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a <strong>circular</strong> street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses' doors could be open or closed initially (at least one is open).</p>
<p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p>
<p>The class <code>Street</code> contains the following functions which may help you:</p>
<ul>
<li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li>
<li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li>
<li><code>void moveRight()</code>: Move to the right house.</li>
</ul>
<p><strong>Note</strong> that by <strong>circular</strong> street, we mean if you number the houses from <code>1</code> to <code>n</code>, then the right house of <code>house<sub>i</sub></code> is <code>house<sub>i+1</sub></code> for <code>i < n</code>, and the right house of <code>house<sub>n</sub></code> is <code>house<sub>1</sub></code>.</p>
<p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> street = [1,1,1,1], k = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 houses, and all their doors are open.
The number of houses is less than k, which is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> street = [1,0,1,1,0], k = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == number of houses</code></li>
<li><code>1 <= n <= k <= 10<sup>5</sup></code></li>
<li><code>street</code> is circular by definition provided in the statement.</li>
<li>The input is generated such that at least one of the doors is open.</li>
</ul>
|
Python
|
# Definition for a street.
# class Street:
# def closeDoor(self):
# pass
# def isDoorOpen(self):
# pass
# def moveRight(self):
# pass
class Solution:
def houseCount(self, street: Optional["Street"], k: int) -> int:
while not street.isDoorOpen():
street.moveRight()
for i in range(1, k + 1):
street.moveRight()
if street.isDoorOpen():
ans = i
street.closeDoor()
return ans
|
|
2,753
|
Count Houses in a Circular Street II
|
Hard
|
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a <strong>circular</strong> street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses' doors could be open or closed initially (at least one is open).</p>
<p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p>
<p>The class <code>Street</code> contains the following functions which may help you:</p>
<ul>
<li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li>
<li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li>
<li><code>void moveRight()</code>: Move to the right house.</li>
</ul>
<p><strong>Note</strong> that by <strong>circular</strong> street, we mean if you number the houses from <code>1</code> to <code>n</code>, then the right house of <code>house<sub>i</sub></code> is <code>house<sub>i+1</sub></code> for <code>i < n</code>, and the right house of <code>house<sub>n</sub></code> is <code>house<sub>1</sub></code>.</p>
<p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> street = [1,1,1,1], k = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 houses, and all their doors are open.
The number of houses is less than k, which is 10.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> street = [1,0,1,1,0], k = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == number of houses</code></li>
<li><code>1 <= n <= k <= 10<sup>5</sup></code></li>
<li><code>street</code> is circular by definition provided in the statement.</li>
<li>The input is generated such that at least one of the doors is open.</li>
</ul>
|
TypeScript
|
/**
* Definition for a street.
* class Street {
* constructor(doors: number[]);
* public closeDoor(): void;
* public isDoorOpen(): boolean;
* public moveRight(): void;
* }
*/
function houseCount(street: Street | null, k: number): number {
while (!street.isDoorOpen()) {
street.moveRight();
}
let ans = 0;
for (let i = 1; i <= k; ++i) {
street.moveRight();
if (street.isDoorOpen()) {
ans = i;
street.closeDoor();
}
}
return ans;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.