id
int64 1
3.65k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,133 |
Minimum Array End
|
Medium
|
<p>You are given two integers <code>n</code> and <code>x</code>. You have to construct an array of <strong>positive</strong> integers <code>nums</code> of size <code>n</code> where for every <code>0 <= i < n - 1</code>, <code>nums[i + 1]</code> is <strong>greater than</strong> <code>nums[i]</code>, and the result of the bitwise <code>AND</code> operation between all elements of <code>nums</code> is <code>x</code>.</p>
<p>Return the <strong>minimum</strong> possible value of <code>nums[n - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[4,5,6]</code> and its last element is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, x = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[7,15]</code> and its last element is 15.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation
|
C++
|
class Solution {
public:
long long minEnd(int n, int x) {
--n;
long long ans = x;
for (int i = 0; i < 31; ++i) {
if (x >> i & 1 ^ 1) {
ans |= (n & 1) << i;
n >>= 1;
}
}
ans |= (1LL * n) << 31;
return ans;
}
};
|
3,133 |
Minimum Array End
|
Medium
|
<p>You are given two integers <code>n</code> and <code>x</code>. You have to construct an array of <strong>positive</strong> integers <code>nums</code> of size <code>n</code> where for every <code>0 <= i < n - 1</code>, <code>nums[i + 1]</code> is <strong>greater than</strong> <code>nums[i]</code>, and the result of the bitwise <code>AND</code> operation between all elements of <code>nums</code> is <code>x</code>.</p>
<p>Return the <strong>minimum</strong> possible value of <code>nums[n - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[4,5,6]</code> and its last element is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, x = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[7,15]</code> and its last element is 15.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation
|
Go
|
func minEnd(n int, x int) (ans int64) {
n--
ans = int64(x)
for i := 0; i < 31; i++ {
if x>>i&1 == 0 {
ans |= int64((n & 1) << i)
n >>= 1
}
}
ans |= int64(n) << 31
return
}
|
3,133 |
Minimum Array End
|
Medium
|
<p>You are given two integers <code>n</code> and <code>x</code>. You have to construct an array of <strong>positive</strong> integers <code>nums</code> of size <code>n</code> where for every <code>0 <= i < n - 1</code>, <code>nums[i + 1]</code> is <strong>greater than</strong> <code>nums[i]</code>, and the result of the bitwise <code>AND</code> operation between all elements of <code>nums</code> is <code>x</code>.</p>
<p>Return the <strong>minimum</strong> possible value of <code>nums[n - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[4,5,6]</code> and its last element is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, x = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[7,15]</code> and its last element is 15.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation
|
Java
|
class Solution {
public long minEnd(int n, int x) {
--n;
long ans = x;
for (int i = 0; i < 31; ++i) {
if ((x >> i & 1) == 0) {
ans |= (n & 1) << i;
n >>= 1;
}
}
ans |= (long) n << 31;
return ans;
}
}
|
3,133 |
Minimum Array End
|
Medium
|
<p>You are given two integers <code>n</code> and <code>x</code>. You have to construct an array of <strong>positive</strong> integers <code>nums</code> of size <code>n</code> where for every <code>0 <= i < n - 1</code>, <code>nums[i + 1]</code> is <strong>greater than</strong> <code>nums[i]</code>, and the result of the bitwise <code>AND</code> operation between all elements of <code>nums</code> is <code>x</code>.</p>
<p>Return the <strong>minimum</strong> possible value of <code>nums[n - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[4,5,6]</code> and its last element is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, x = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[7,15]</code> and its last element is 15.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation
|
Python
|
class Solution:
def minEnd(self, n: int, x: int) -> int:
n -= 1
ans = x
for i in range(31):
if x >> i & 1 ^ 1:
ans |= (n & 1) << i
n >>= 1
ans |= n << 31
return ans
|
3,133 |
Minimum Array End
|
Medium
|
<p>You are given two integers <code>n</code> and <code>x</code>. You have to construct an array of <strong>positive</strong> integers <code>nums</code> of size <code>n</code> where for every <code>0 <= i < n - 1</code>, <code>nums[i + 1]</code> is <strong>greater than</strong> <code>nums[i]</code>, and the result of the bitwise <code>AND</code> operation between all elements of <code>nums</code> is <code>x</code>.</p>
<p>Return the <strong>minimum</strong> possible value of <code>nums[n - 1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, x = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[4,5,6]</code> and its last element is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, x = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> can be <code>[7,15]</code> and its last element is 15.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, x <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation
|
TypeScript
|
function minEnd(n: number, x: number): number {
--n;
let ans: bigint = BigInt(x);
for (let i = 0; i < 31; ++i) {
if (((x >> i) & 1) ^ 1) {
ans |= BigInt(n & 1) << BigInt(i);
n >>= 1;
}
}
ans |= BigInt(n) << BigInt(31);
return Number(ans);
}
|
3,134 |
Find the Median of the Uniqueness Array
|
Hard
|
<p>You are given an integer array <code>nums</code>. The <strong>uniqueness array</strong> of <code>nums</code> is the sorted array that contains the number of distinct elements of all the <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>. In other words, it is a sorted array consisting of <code>distinct(nums[i..j])</code>, for all <code>0 <= i <= j < nums.length</code>.</p>
<p>Here, <code>distinct(nums[i..j])</code> denotes the number of distinct elements in the subarray that starts at index <code>i</code> and ends at index <code>j</code>.</p>
<p>Return the <strong>median</strong> of the <strong>uniqueness array</strong> of <code>nums</code>.</p>
<p><strong>Note</strong> that the <strong>median</strong> of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the <strong>smaller</strong> of the two values is taken.<!-- notionvc: 7e0f5178-4273-4a82-95ce-3395297921dc --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]</code> which is equal to <code>[1, 1, 1, 2, 2, 3]</code>. The uniqueness array has a median of 1. Therefore, the answer is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Binary Search; Sliding Window
|
C++
|
class Solution {
public:
int medianOfUniquenessArray(vector<int>& nums) {
int n = nums.size();
using ll = long long;
ll m = (1LL + n) * n / 2;
int l = 0, r = n;
auto check = [&](int mx) -> bool {
unordered_map<int, int> cnt;
ll k = 0;
for (int l = 0, r = 0; r < n; ++r) {
int x = nums[r];
++cnt[x];
while (cnt.size() > mx) {
int y = nums[l++];
if (--cnt[y] == 0) {
cnt.erase(y);
}
}
k += r - l + 1;
if (k >= (m + 1) / 2) {
return true;
}
}
return false;
};
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
};
|
3,134 |
Find the Median of the Uniqueness Array
|
Hard
|
<p>You are given an integer array <code>nums</code>. The <strong>uniqueness array</strong> of <code>nums</code> is the sorted array that contains the number of distinct elements of all the <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>. In other words, it is a sorted array consisting of <code>distinct(nums[i..j])</code>, for all <code>0 <= i <= j < nums.length</code>.</p>
<p>Here, <code>distinct(nums[i..j])</code> denotes the number of distinct elements in the subarray that starts at index <code>i</code> and ends at index <code>j</code>.</p>
<p>Return the <strong>median</strong> of the <strong>uniqueness array</strong> of <code>nums</code>.</p>
<p><strong>Note</strong> that the <strong>median</strong> of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the <strong>smaller</strong> of the two values is taken.<!-- notionvc: 7e0f5178-4273-4a82-95ce-3395297921dc --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]</code> which is equal to <code>[1, 1, 1, 2, 2, 3]</code>. The uniqueness array has a median of 1. Therefore, the answer is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Binary Search; Sliding Window
|
Go
|
func medianOfUniquenessArray(nums []int) int {
n := len(nums)
m := (1 + n) * n / 2
return sort.Search(n, func(mx int) bool {
cnt := map[int]int{}
l, k := 0, 0
for r, x := range nums {
cnt[x]++
for len(cnt) > mx {
y := nums[l]
cnt[y]--
if cnt[y] == 0 {
delete(cnt, y)
}
l++
}
k += r - l + 1
if k >= (m+1)/2 {
return true
}
}
return false
})
}
|
3,134 |
Find the Median of the Uniqueness Array
|
Hard
|
<p>You are given an integer array <code>nums</code>. The <strong>uniqueness array</strong> of <code>nums</code> is the sorted array that contains the number of distinct elements of all the <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>. In other words, it is a sorted array consisting of <code>distinct(nums[i..j])</code>, for all <code>0 <= i <= j < nums.length</code>.</p>
<p>Here, <code>distinct(nums[i..j])</code> denotes the number of distinct elements in the subarray that starts at index <code>i</code> and ends at index <code>j</code>.</p>
<p>Return the <strong>median</strong> of the <strong>uniqueness array</strong> of <code>nums</code>.</p>
<p><strong>Note</strong> that the <strong>median</strong> of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the <strong>smaller</strong> of the two values is taken.<!-- notionvc: 7e0f5178-4273-4a82-95ce-3395297921dc --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]</code> which is equal to <code>[1, 1, 1, 2, 2, 3]</code>. The uniqueness array has a median of 1. Therefore, the answer is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Binary Search; Sliding Window
|
Java
|
class Solution {
private long m;
private int[] nums;
public int medianOfUniquenessArray(int[] nums) {
int n = nums.length;
this.nums = nums;
m = (1L + n) * n / 2;
int l = 0, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
private boolean check(int mx) {
Map<Integer, Integer> cnt = new HashMap<>();
long k = 0;
for (int l = 0, r = 0; r < nums.length; ++r) {
int x = nums[r];
cnt.merge(x, 1, Integer::sum);
while (cnt.size() > mx) {
int y = nums[l++];
if (cnt.merge(y, -1, Integer::sum) == 0) {
cnt.remove(y);
}
}
k += r - l + 1;
if (k >= (m + 1) / 2) {
return true;
}
}
return false;
}
}
|
3,134 |
Find the Median of the Uniqueness Array
|
Hard
|
<p>You are given an integer array <code>nums</code>. The <strong>uniqueness array</strong> of <code>nums</code> is the sorted array that contains the number of distinct elements of all the <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>. In other words, it is a sorted array consisting of <code>distinct(nums[i..j])</code>, for all <code>0 <= i <= j < nums.length</code>.</p>
<p>Here, <code>distinct(nums[i..j])</code> denotes the number of distinct elements in the subarray that starts at index <code>i</code> and ends at index <code>j</code>.</p>
<p>Return the <strong>median</strong> of the <strong>uniqueness array</strong> of <code>nums</code>.</p>
<p><strong>Note</strong> that the <strong>median</strong> of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the <strong>smaller</strong> of the two values is taken.<!-- notionvc: 7e0f5178-4273-4a82-95ce-3395297921dc --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]</code> which is equal to <code>[1, 1, 1, 2, 2, 3]</code>. The uniqueness array has a median of 1. Therefore, the answer is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Binary Search; Sliding Window
|
Python
|
class Solution:
def medianOfUniquenessArray(self, nums: List[int]) -> int:
def check(mx: int) -> bool:
cnt = defaultdict(int)
k = l = 0
for r, x in enumerate(nums):
cnt[x] += 1
while len(cnt) > mx:
y = nums[l]
cnt[y] -= 1
if cnt[y] == 0:
cnt.pop(y)
l += 1
k += r - l + 1
if k >= (m + 1) // 2:
return True
return False
n = len(nums)
m = (1 + n) * n // 2
return bisect_left(range(n), True, key=check)
|
3,134 |
Find the Median of the Uniqueness Array
|
Hard
|
<p>You are given an integer array <code>nums</code>. The <strong>uniqueness array</strong> of <code>nums</code> is the sorted array that contains the number of distinct elements of all the <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>. In other words, it is a sorted array consisting of <code>distinct(nums[i..j])</code>, for all <code>0 <= i <= j < nums.length</code>.</p>
<p>Here, <code>distinct(nums[i..j])</code> denotes the number of distinct elements in the subarray that starts at index <code>i</code> and ends at index <code>j</code>.</p>
<p>Return the <strong>median</strong> of the <strong>uniqueness array</strong> of <code>nums</code>.</p>
<p><strong>Note</strong> that the <strong>median</strong> of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the <strong>smaller</strong> of the two values is taken.<!-- notionvc: 7e0f5178-4273-4a82-95ce-3395297921dc --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]</code> which is equal to <code>[1, 1, 1, 2, 2, 3]</code>. The uniqueness array has a median of 1. Therefore, the answer is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The uniqueness array of <code>nums</code> is <code>[1, 1, 1, 1, 2, 2, 2, 3, 3, 3]</code>. The uniqueness array has a median of 2. Therefore, the answer is 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Binary Search; Sliding Window
|
TypeScript
|
function medianOfUniquenessArray(nums: number[]): number {
const n = nums.length;
const m = Math.floor(((1 + n) * n) / 2);
let [l, r] = [0, n];
const check = (mx: number): boolean => {
const cnt = new Map<number, number>();
let [l, k] = [0, 0];
for (let r = 0; r < n; ++r) {
const x = nums[r];
cnt.set(x, (cnt.get(x) || 0) + 1);
while (cnt.size > mx) {
const y = nums[l++];
cnt.set(y, cnt.get(y)! - 1);
if (cnt.get(y) === 0) {
cnt.delete(y);
}
}
k += r - l + 1;
if (k >= Math.floor((m + 1) / 2)) {
return true;
}
}
return false;
};
while (l < r) {
const mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
|
3,135 |
Equalize Strings by Adding or Removing Characters at Ends
|
Medium
|
<p>Given two strings <code>initial</code> and <code>target</code>, your task is to modify <code>initial</code> by performing a series of operations to make it equal to <code>target</code>.</p>
<p>In one operation, you can add or remove <strong>one character</strong> only at the <em>beginning</em> or the <em>end</em> of the string <code>initial</code>.</p>
<p>Return the <strong>minimum</strong> number of operations required to <em>transform</em> <code>initial</code> into <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "abcde", target = "cdef"</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>Remove <code>'a'</code> and <code>'b'</code> from the beginning of <code>initial</code>, then add <code>'f'</code> to the end.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "axxy", target = "yabx"</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<table border="1">
<tbody>
<tr>
<th>Operation</th>
<th>Resulting String</th>
</tr>
<tr>
<td>Add <code>'y'</code> to the beginning</td>
<td><code>"yaxxy"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yaxx"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yax"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"ya"</code></td>
</tr>
<tr>
<td>Add <code>'b'</code> to the end</td>
<td><code>"yab"</code></td>
</tr>
<tr>
<td>Add <code>'x'</code> to the end</td>
<td><code>"yabx"</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "xyz", target = "xyz"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No operations are needed as the strings are already equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initial.length, target.length <= 1000</code></li>
<li><code>initial</code> and <code>target</code> consist only of lowercase English letters.</li>
</ul>
|
String; Binary Search; Dynamic Programming; Sliding Window; Hash Function
|
C++
|
class Solution {
public:
int minOperations(string initial, string target) {
int m = initial.size(), n = target.size();
int f[m + 1][n + 1];
memset(f, 0, sizeof(f));
int mx = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (initial[i - 1] == target[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
mx = max(mx, f[i][j]);
}
}
}
return m + n - 2 * mx;
}
};
|
3,135 |
Equalize Strings by Adding or Removing Characters at Ends
|
Medium
|
<p>Given two strings <code>initial</code> and <code>target</code>, your task is to modify <code>initial</code> by performing a series of operations to make it equal to <code>target</code>.</p>
<p>In one operation, you can add or remove <strong>one character</strong> only at the <em>beginning</em> or the <em>end</em> of the string <code>initial</code>.</p>
<p>Return the <strong>minimum</strong> number of operations required to <em>transform</em> <code>initial</code> into <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "abcde", target = "cdef"</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>Remove <code>'a'</code> and <code>'b'</code> from the beginning of <code>initial</code>, then add <code>'f'</code> to the end.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "axxy", target = "yabx"</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<table border="1">
<tbody>
<tr>
<th>Operation</th>
<th>Resulting String</th>
</tr>
<tr>
<td>Add <code>'y'</code> to the beginning</td>
<td><code>"yaxxy"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yaxx"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yax"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"ya"</code></td>
</tr>
<tr>
<td>Add <code>'b'</code> to the end</td>
<td><code>"yab"</code></td>
</tr>
<tr>
<td>Add <code>'x'</code> to the end</td>
<td><code>"yabx"</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "xyz", target = "xyz"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No operations are needed as the strings are already equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initial.length, target.length <= 1000</code></li>
<li><code>initial</code> and <code>target</code> consist only of lowercase English letters.</li>
</ul>
|
String; Binary Search; Dynamic Programming; Sliding Window; Hash Function
|
Go
|
func minOperations(initial string, target string) int {
m, n := len(initial), len(target)
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
mx := 0
for i, a := range initial {
for j, b := range target {
if a == b {
f[i+1][j+1] = f[i][j] + 1
mx = max(mx, f[i+1][j+1])
}
}
}
return m + n - 2*mx
}
|
3,135 |
Equalize Strings by Adding or Removing Characters at Ends
|
Medium
|
<p>Given two strings <code>initial</code> and <code>target</code>, your task is to modify <code>initial</code> by performing a series of operations to make it equal to <code>target</code>.</p>
<p>In one operation, you can add or remove <strong>one character</strong> only at the <em>beginning</em> or the <em>end</em> of the string <code>initial</code>.</p>
<p>Return the <strong>minimum</strong> number of operations required to <em>transform</em> <code>initial</code> into <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "abcde", target = "cdef"</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>Remove <code>'a'</code> and <code>'b'</code> from the beginning of <code>initial</code>, then add <code>'f'</code> to the end.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "axxy", target = "yabx"</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<table border="1">
<tbody>
<tr>
<th>Operation</th>
<th>Resulting String</th>
</tr>
<tr>
<td>Add <code>'y'</code> to the beginning</td>
<td><code>"yaxxy"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yaxx"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yax"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"ya"</code></td>
</tr>
<tr>
<td>Add <code>'b'</code> to the end</td>
<td><code>"yab"</code></td>
</tr>
<tr>
<td>Add <code>'x'</code> to the end</td>
<td><code>"yabx"</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "xyz", target = "xyz"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No operations are needed as the strings are already equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initial.length, target.length <= 1000</code></li>
<li><code>initial</code> and <code>target</code> consist only of lowercase English letters.</li>
</ul>
|
String; Binary Search; Dynamic Programming; Sliding Window; Hash Function
|
Java
|
class Solution {
public int minOperations(String initial, String target) {
int m = initial.length(), n = target.length();
int[][] f = new int[m + 1][n + 1];
int mx = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (initial.charAt(i - 1) == target.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1] + 1;
mx = Math.max(mx, f[i][j]);
}
}
}
return m + n - 2 * mx;
}
}
|
3,135 |
Equalize Strings by Adding or Removing Characters at Ends
|
Medium
|
<p>Given two strings <code>initial</code> and <code>target</code>, your task is to modify <code>initial</code> by performing a series of operations to make it equal to <code>target</code>.</p>
<p>In one operation, you can add or remove <strong>one character</strong> only at the <em>beginning</em> or the <em>end</em> of the string <code>initial</code>.</p>
<p>Return the <strong>minimum</strong> number of operations required to <em>transform</em> <code>initial</code> into <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "abcde", target = "cdef"</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>Remove <code>'a'</code> and <code>'b'</code> from the beginning of <code>initial</code>, then add <code>'f'</code> to the end.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "axxy", target = "yabx"</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<table border="1">
<tbody>
<tr>
<th>Operation</th>
<th>Resulting String</th>
</tr>
<tr>
<td>Add <code>'y'</code> to the beginning</td>
<td><code>"yaxxy"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yaxx"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yax"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"ya"</code></td>
</tr>
<tr>
<td>Add <code>'b'</code> to the end</td>
<td><code>"yab"</code></td>
</tr>
<tr>
<td>Add <code>'x'</code> to the end</td>
<td><code>"yabx"</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "xyz", target = "xyz"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No operations are needed as the strings are already equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initial.length, target.length <= 1000</code></li>
<li><code>initial</code> and <code>target</code> consist only of lowercase English letters.</li>
</ul>
|
String; Binary Search; Dynamic Programming; Sliding Window; Hash Function
|
Python
|
class Solution:
def minOperations(self, initial: str, target: str) -> int:
m, n = len(initial), len(target)
f = [[0] * (n + 1) for _ in range(m + 1)]
mx = 0
for i, a in enumerate(initial, 1):
for j, b in enumerate(target, 1):
if a == b:
f[i][j] = f[i - 1][j - 1] + 1
mx = max(mx, f[i][j])
return m + n - mx * 2
|
3,135 |
Equalize Strings by Adding or Removing Characters at Ends
|
Medium
|
<p>Given two strings <code>initial</code> and <code>target</code>, your task is to modify <code>initial</code> by performing a series of operations to make it equal to <code>target</code>.</p>
<p>In one operation, you can add or remove <strong>one character</strong> only at the <em>beginning</em> or the <em>end</em> of the string <code>initial</code>.</p>
<p>Return the <strong>minimum</strong> number of operations required to <em>transform</em> <code>initial</code> into <code>target</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "abcde", target = "cdef"</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>Remove <code>'a'</code> and <code>'b'</code> from the beginning of <code>initial</code>, then add <code>'f'</code> to the end.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "axxy", target = "yabx"</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<table border="1">
<tbody>
<tr>
<th>Operation</th>
<th>Resulting String</th>
</tr>
<tr>
<td>Add <code>'y'</code> to the beginning</td>
<td><code>"yaxxy"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yaxx"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"yax"</code></td>
</tr>
<tr>
<td>Remove from end</td>
<td><code>"ya"</code></td>
</tr>
<tr>
<td>Add <code>'b'</code> to the end</td>
<td><code>"yab"</code></td>
</tr>
<tr>
<td>Add <code>'x'</code> to the end</td>
<td><code>"yabx"</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initial = "xyz", target = "xyz"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No operations are needed as the strings are already equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initial.length, target.length <= 1000</code></li>
<li><code>initial</code> and <code>target</code> consist only of lowercase English letters.</li>
</ul>
|
String; Binary Search; Dynamic Programming; Sliding Window; Hash Function
|
TypeScript
|
function minOperations(initial: string, target: string): number {
const m = initial.length;
const n = target.length;
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
let mx: number = 0;
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
if (initial[i - 1] === target[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
mx = Math.max(mx, f[i][j]);
}
}
}
return m + n - 2 * mx;
}
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
bool isValid(string word) {
if (word.size() < 3) {
return false;
}
bool has_vowel = false, has_consonant = false;
bool vs[26]{};
string vowels = "aeiou";
for (char c : vowels) {
vs[c - 'a'] = true;
}
for (char c : word) {
if (isalpha(c)) {
if (vs[tolower(c) - 'a']) {
has_vowel = true;
} else {
has_consonant = true;
}
} else if (!isdigit(c)) {
return false;
}
}
return has_vowel && has_consonant;
}
};
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
C#
|
public class Solution {
public bool IsValid(string word) {
if (word.Length < 3) {
return false;
}
bool hasVowel = false, hasConsonant = false;
bool[] vs = new bool[26];
foreach (char c in "aeiou") {
vs[c - 'a'] = true;
}
foreach (char c in word) {
if (char.IsLetter(c)) {
char lower = char.ToLower(c);
if (vs[lower - 'a']) {
hasVowel = true;
} else {
hasConsonant = true;
}
} else if (!char.IsDigit(c)) {
return false;
}
}
return hasVowel && hasConsonant;
}
}
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
Go
|
func isValid(word string) bool {
if len(word) < 3 {
return false
}
hasVowel := false
hasConsonant := false
vs := make([]bool, 26)
for _, c := range "aeiou" {
vs[c-'a'] = true
}
for _, c := range word {
if unicode.IsLetter(c) {
if vs[unicode.ToLower(c)-'a'] {
hasVowel = true
} else {
hasConsonant = true
}
} else if !unicode.IsDigit(c) {
return false
}
}
return hasVowel && hasConsonant
}
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
Java
|
class Solution {
public boolean isValid(String word) {
if (word.length() < 3) {
return false;
}
boolean hasVowel = false, hasConsonant = false;
boolean[] vs = new boolean[26];
for (char c : "aeiou".toCharArray()) {
vs[c - 'a'] = true;
}
for (char c : word.toCharArray()) {
if (Character.isAlphabetic(c)) {
if (vs[Character.toLowerCase(c) - 'a']) {
hasVowel = true;
} else {
hasConsonant = true;
}
} else if (!Character.isDigit(c)) {
return false;
}
}
return hasVowel && hasConsonant;
}
}
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
Python
|
class Solution:
def isValid(self, word: str) -> bool:
if len(word) < 3:
return False
has_vowel = has_consonant = False
vs = set("aeiouAEIOU")
for c in word:
if not c.isalnum():
return False
if c.isalpha():
if c in vs:
has_vowel = True
else:
has_consonant = True
return has_vowel and has_consonant
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
Rust
|
impl Solution {
pub fn is_valid(word: String) -> bool {
if word.len() < 3 {
return false;
}
let mut has_vowel = false;
let mut has_consonant = false;
let vowels = ['a', 'e', 'i', 'o', 'u'];
for c in word.chars() {
if !c.is_alphanumeric() {
return false;
}
if c.is_alphabetic() {
let lower_c = c.to_ascii_lowercase();
if vowels.contains(&lower_c) {
has_vowel = true;
} else {
has_consonant = true;
}
}
}
has_vowel && has_consonant
}
}
|
3,136 |
Valid Word
|
Easy
|
<p>A word is considered <strong>valid</strong> if:</p>
<ul>
<li>It contains a <strong>minimum</strong> of 3 characters.</li>
<li>It contains only digits (0-9), and English letters (uppercase and lowercase).</li>
<li>It includes <strong>at least</strong> one <strong>vowel</strong>.</li>
<li>It includes <strong>at least</strong> one <strong>consonant</strong>.</li>
</ul>
<p>You are given a string <code>word</code>.</p>
<p>Return <code>true</code> if <code>word</code> is valid, otherwise, return <code>false</code>.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, <code>'u'</code>, and their uppercases are <strong>vowels</strong>.</li>
<li>A <strong>consonant</strong> is an English letter that is not a vowel.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "234Adas"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>This word satisfies the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "b3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The length of this word is fewer than 3, and does not have a vowel.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "a3$e"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>This word contains a <code>'$'</code> character and does not have a consonant.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 20</code></li>
<li><code>word</code> consists of English uppercase and lowercase letters, digits, <code>'@'</code>, <code>'#'</code>, and <code>'$'</code>.</li>
</ul>
|
String
|
TypeScript
|
function isValid(word: string): boolean {
if (word.length < 3) {
return false;
}
let hasVowel: boolean = false;
let hasConsonant: boolean = false;
const vowels: Set<string> = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
for (const c of word) {
if (!c.match(/[a-zA-Z0-9]/)) {
return false;
}
if (/[a-zA-Z]/.test(c)) {
if (vowels.has(c)) {
hasVowel = true;
} else {
hasConsonant = true;
}
}
}
return hasVowel && hasConsonant;
}
|
3,137 |
Minimum Number of Operations to Make Word K-Periodic
|
Medium
|
<p>You are given a string <code>word</code> of size <code>n</code>, and an integer <code>k</code> such that <code>k</code> divides <code>n</code>.</p>
<p>In one operation, you can pick any two indices <code>i</code> and <code>j</code>, that are divisible by <code>k</code>, then replace the <span data-keyword="substring">substring</span> of length <code>k</code> starting at <code>i</code> with the substring of length <code>k</code> starting at <code>j</code>. That is, replace the substring <code>word[i..i + k - 1]</code> with the substring <code>word[j..j + k - 1]</code>.<!-- notionvc: 49ac84f7-0724-452a-ab43-0c5e53f1db33 --></p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>word</code> <em><strong>k-periodic</strong></em>.</p>
<p>We say that <code>word</code> is <strong>k-periodic</strong> if there is some string <code>s</code> of length <code>k</code> such that <code>word</code> can be obtained by concatenating <code>s</code> an arbitrary number of times. For example, if <code>word == “ababab”</code>, then <code>word</code> is 2-periodic for <code>s = "ab"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "leetcodeleet", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">1</span></p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "</span>leetcoleet<span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">", k = 2</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 2-periodic string by applying the operations in the table below.</p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" height="146" style="border-collapse:collapse; text-align: center; vertical-align: middle;">
<tbody>
<tr>
<th>i</th>
<th>j</th>
<th>word</th>
</tr>
<tr>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">2</td>
<td style="padding: 5px 15px;">etetcoleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">4</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">6</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetetet</td>
</tr>
</tbody>
</table>
</div>
<div id="gtx-trans" style="position: absolute; left: 107px; top: 238.5px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == word.length <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>k</code> divides <code>word.length</code>.</li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
C++
|
class Solution {
public:
int minimumOperationsToMakeKPeriodic(string word, int k) {
unordered_map<string, int> cnt;
int n = word.size();
int mx = 0;
for (int i = 0; i < n; i += k) {
mx = max(mx, ++cnt[word.substr(i, k)]);
}
return n / k - mx;
}
};
|
3,137 |
Minimum Number of Operations to Make Word K-Periodic
|
Medium
|
<p>You are given a string <code>word</code> of size <code>n</code>, and an integer <code>k</code> such that <code>k</code> divides <code>n</code>.</p>
<p>In one operation, you can pick any two indices <code>i</code> and <code>j</code>, that are divisible by <code>k</code>, then replace the <span data-keyword="substring">substring</span> of length <code>k</code> starting at <code>i</code> with the substring of length <code>k</code> starting at <code>j</code>. That is, replace the substring <code>word[i..i + k - 1]</code> with the substring <code>word[j..j + k - 1]</code>.<!-- notionvc: 49ac84f7-0724-452a-ab43-0c5e53f1db33 --></p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>word</code> <em><strong>k-periodic</strong></em>.</p>
<p>We say that <code>word</code> is <strong>k-periodic</strong> if there is some string <code>s</code> of length <code>k</code> such that <code>word</code> can be obtained by concatenating <code>s</code> an arbitrary number of times. For example, if <code>word == “ababab”</code>, then <code>word</code> is 2-periodic for <code>s = "ab"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "leetcodeleet", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">1</span></p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "</span>leetcoleet<span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">", k = 2</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 2-periodic string by applying the operations in the table below.</p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" height="146" style="border-collapse:collapse; text-align: center; vertical-align: middle;">
<tbody>
<tr>
<th>i</th>
<th>j</th>
<th>word</th>
</tr>
<tr>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">2</td>
<td style="padding: 5px 15px;">etetcoleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">4</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">6</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetetet</td>
</tr>
</tbody>
</table>
</div>
<div id="gtx-trans" style="position: absolute; left: 107px; top: 238.5px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == word.length <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>k</code> divides <code>word.length</code>.</li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Go
|
func minimumOperationsToMakeKPeriodic(word string, k int) int {
cnt := map[string]int{}
n := len(word)
mx := 0
for i := 0; i < n; i += k {
s := word[i : i+k]
cnt[s]++
mx = max(mx, cnt[s])
}
return n/k - mx
}
|
3,137 |
Minimum Number of Operations to Make Word K-Periodic
|
Medium
|
<p>You are given a string <code>word</code> of size <code>n</code>, and an integer <code>k</code> such that <code>k</code> divides <code>n</code>.</p>
<p>In one operation, you can pick any two indices <code>i</code> and <code>j</code>, that are divisible by <code>k</code>, then replace the <span data-keyword="substring">substring</span> of length <code>k</code> starting at <code>i</code> with the substring of length <code>k</code> starting at <code>j</code>. That is, replace the substring <code>word[i..i + k - 1]</code> with the substring <code>word[j..j + k - 1]</code>.<!-- notionvc: 49ac84f7-0724-452a-ab43-0c5e53f1db33 --></p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>word</code> <em><strong>k-periodic</strong></em>.</p>
<p>We say that <code>word</code> is <strong>k-periodic</strong> if there is some string <code>s</code> of length <code>k</code> such that <code>word</code> can be obtained by concatenating <code>s</code> an arbitrary number of times. For example, if <code>word == “ababab”</code>, then <code>word</code> is 2-periodic for <code>s = "ab"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "leetcodeleet", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">1</span></p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "</span>leetcoleet<span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">", k = 2</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 2-periodic string by applying the operations in the table below.</p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" height="146" style="border-collapse:collapse; text-align: center; vertical-align: middle;">
<tbody>
<tr>
<th>i</th>
<th>j</th>
<th>word</th>
</tr>
<tr>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">2</td>
<td style="padding: 5px 15px;">etetcoleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">4</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">6</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetetet</td>
</tr>
</tbody>
</table>
</div>
<div id="gtx-trans" style="position: absolute; left: 107px; top: 238.5px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == word.length <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>k</code> divides <code>word.length</code>.</li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Java
|
class Solution {
public int minimumOperationsToMakeKPeriodic(String word, int k) {
Map<String, Integer> cnt = new HashMap<>();
int n = word.length();
int mx = 0;
for (int i = 0; i < n; i += k) {
mx = Math.max(mx, cnt.merge(word.substring(i, i + k), 1, Integer::sum));
}
return n / k - mx;
}
}
|
3,137 |
Minimum Number of Operations to Make Word K-Periodic
|
Medium
|
<p>You are given a string <code>word</code> of size <code>n</code>, and an integer <code>k</code> such that <code>k</code> divides <code>n</code>.</p>
<p>In one operation, you can pick any two indices <code>i</code> and <code>j</code>, that are divisible by <code>k</code>, then replace the <span data-keyword="substring">substring</span> of length <code>k</code> starting at <code>i</code> with the substring of length <code>k</code> starting at <code>j</code>. That is, replace the substring <code>word[i..i + k - 1]</code> with the substring <code>word[j..j + k - 1]</code>.<!-- notionvc: 49ac84f7-0724-452a-ab43-0c5e53f1db33 --></p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>word</code> <em><strong>k-periodic</strong></em>.</p>
<p>We say that <code>word</code> is <strong>k-periodic</strong> if there is some string <code>s</code> of length <code>k</code> such that <code>word</code> can be obtained by concatenating <code>s</code> an arbitrary number of times. For example, if <code>word == “ababab”</code>, then <code>word</code> is 2-periodic for <code>s = "ab"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "leetcodeleet", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">1</span></p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "</span>leetcoleet<span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">", k = 2</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 2-periodic string by applying the operations in the table below.</p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" height="146" style="border-collapse:collapse; text-align: center; vertical-align: middle;">
<tbody>
<tr>
<th>i</th>
<th>j</th>
<th>word</th>
</tr>
<tr>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">2</td>
<td style="padding: 5px 15px;">etetcoleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">4</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">6</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetetet</td>
</tr>
</tbody>
</table>
</div>
<div id="gtx-trans" style="position: absolute; left: 107px; top: 238.5px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == word.length <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>k</code> divides <code>word.length</code>.</li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Python
|
class Solution:
def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int:
n = len(word)
return n // k - max(Counter(word[i : i + k] for i in range(0, n, k)).values())
|
3,137 |
Minimum Number of Operations to Make Word K-Periodic
|
Medium
|
<p>You are given a string <code>word</code> of size <code>n</code>, and an integer <code>k</code> such that <code>k</code> divides <code>n</code>.</p>
<p>In one operation, you can pick any two indices <code>i</code> and <code>j</code>, that are divisible by <code>k</code>, then replace the <span data-keyword="substring">substring</span> of length <code>k</code> starting at <code>i</code> with the substring of length <code>k</code> starting at <code>j</code>. That is, replace the substring <code>word[i..i + k - 1]</code> with the substring <code>word[j..j + k - 1]</code>.<!-- notionvc: 49ac84f7-0724-452a-ab43-0c5e53f1db33 --></p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make</em> <code>word</code> <em><strong>k-periodic</strong></em>.</p>
<p>We say that <code>word</code> is <strong>k-periodic</strong> if there is some string <code>s</code> of length <code>k</code> such that <code>word</code> can be obtained by concatenating <code>s</code> an arbitrary number of times. For example, if <code>word == “ababab”</code>, then <code>word</code> is 2-periodic for <code>s = "ab"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "leetcodeleet", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">1</span></p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">word = "</span>leetcoleet<span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">", k = 2</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p>We can obtain a 2-periodic string by applying the operations in the table below.</p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" height="146" style="border-collapse:collapse; text-align: center; vertical-align: middle;">
<tbody>
<tr>
<th>i</th>
<th>j</th>
<th>word</th>
</tr>
<tr>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">2</td>
<td style="padding: 5px 15px;">etetcoleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">4</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetleet</td>
</tr>
<tr>
<td style="padding: 5px 15px;">6</td>
<td style="padding: 5px 15px;">0</td>
<td style="padding: 5px 15px;">etetetetet</td>
</tr>
</tbody>
</table>
</div>
<div id="gtx-trans" style="position: absolute; left: 107px; top: 238.5px;">
<div class="gtx-trans-icon"> </div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == word.length <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>k</code> divides <code>word.length</code>.</li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
TypeScript
|
function minimumOperationsToMakeKPeriodic(word: string, k: number): number {
const cnt: Map<string, number> = new Map();
const n: number = word.length;
let mx: number = 0;
for (let i = 0; i < n; i += k) {
const s = word.slice(i, i + k);
cnt.set(s, (cnt.get(s) || 0) + 1);
mx = Math.max(mx, cnt.get(s)!);
}
return Math.floor(n / k) - mx;
}
|
3,138 |
Minimum Length of Anagram Concatenation
|
Medium
|
<p>You are given a string <code>s</code>, which is known to be a concatenation of <strong>anagrams</strong> of some string <code>t</code>.</p>
<p>Return the <strong>minimum</strong> possible length of the string <code>t</code>.</p>
<p>An <strong>anagram</strong> is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cdef"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"cdef"</code>, notice that <code>t</code> can be equal to <code>s</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcbcacabbaccba"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consist only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
C++
|
class Solution {
public:
int minAnagramLength(string s) {
int n = s.size();
int cnt[26]{};
for (char c : s) {
cnt[c - 'a']++;
}
auto check = [&](int k) {
for (int i = 0; i < n; i += k) {
int cnt1[26]{};
for (int j = i; j < i + k; ++j) {
cnt1[s[j] - 'a']++;
}
for (int j = 0; j < 26; ++j) {
if (cnt1[j] * (n / k) != cnt[j]) {
return false;
}
}
}
return true;
};
for (int i = 1;; ++i) {
if (n % i == 0 && check(i)) {
return i;
}
}
}
};
|
3,138 |
Minimum Length of Anagram Concatenation
|
Medium
|
<p>You are given a string <code>s</code>, which is known to be a concatenation of <strong>anagrams</strong> of some string <code>t</code>.</p>
<p>Return the <strong>minimum</strong> possible length of the string <code>t</code>.</p>
<p>An <strong>anagram</strong> is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cdef"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"cdef"</code>, notice that <code>t</code> can be equal to <code>s</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcbcacabbaccba"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consist only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Go
|
func minAnagramLength(s string) int {
n := len(s)
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
check := func(k int) bool {
for i := 0; i < n; i += k {
cnt1 := [26]int{}
for j := i; j < i+k; j++ {
cnt1[s[j]-'a']++
}
for j, v := range cnt {
if cnt1[j]*(n/k) != v {
return false
}
}
}
return true
}
for i := 1; ; i++ {
if n%i == 0 && check(i) {
return i
}
}
}
|
3,138 |
Minimum Length of Anagram Concatenation
|
Medium
|
<p>You are given a string <code>s</code>, which is known to be a concatenation of <strong>anagrams</strong> of some string <code>t</code>.</p>
<p>Return the <strong>minimum</strong> possible length of the string <code>t</code>.</p>
<p>An <strong>anagram</strong> is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cdef"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"cdef"</code>, notice that <code>t</code> can be equal to <code>s</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcbcacabbaccba"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consist only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Java
|
class Solution {
private int n;
private char[] s;
private int[] cnt = new int[26];
public int minAnagramLength(String s) {
n = s.length();
this.s = s.toCharArray();
for (int i = 0; i < n; ++i) {
++cnt[this.s[i] - 'a'];
}
for (int i = 1;; ++i) {
if (n % i == 0 && check(i)) {
return i;
}
}
}
private boolean check(int k) {
for (int i = 0; i < n; i += k) {
int[] cnt1 = new int[26];
for (int j = i; j < i + k; ++j) {
++cnt1[s[j] - 'a'];
}
for (int j = 0; j < 26; ++j) {
if (cnt1[j] * (n / k) != cnt[j]) {
return false;
}
}
}
return true;
}
}
|
3,138 |
Minimum Length of Anagram Concatenation
|
Medium
|
<p>You are given a string <code>s</code>, which is known to be a concatenation of <strong>anagrams</strong> of some string <code>t</code>.</p>
<p>Return the <strong>minimum</strong> possible length of the string <code>t</code>.</p>
<p>An <strong>anagram</strong> is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cdef"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"cdef"</code>, notice that <code>t</code> can be equal to <code>s</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcbcacabbaccba"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consist only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Python
|
class Solution:
def minAnagramLength(self, s: str) -> int:
def check(k: int) -> bool:
for i in range(0, n, k):
cnt1 = Counter(s[i : i + k])
for c, v in cnt.items():
if cnt1[c] * (n // k) != v:
return False
return True
cnt = Counter(s)
n = len(s)
for i in range(1, n + 1):
if n % i == 0 and check(i):
return i
|
3,138 |
Minimum Length of Anagram Concatenation
|
Medium
|
<p>You are given a string <code>s</code>, which is known to be a concatenation of <strong>anagrams</strong> of some string <code>t</code>.</p>
<p>Return the <strong>minimum</strong> possible length of the string <code>t</code>.</p>
<p>An <strong>anagram</strong> is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cdef"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>One possible string <code>t</code> could be <code>"cdef"</code>, notice that <code>t</code> can be equal to <code>s</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcbcacabbaccba"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consist only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
TypeScript
|
function minAnagramLength(s: string): number {
const n = s.length;
const cnt: Record<string, number> = {};
for (let i = 0; i < n; i++) {
cnt[s[i]] = (cnt[s[i]] || 0) + 1;
}
const check = (k: number): boolean => {
for (let i = 0; i < n; i += k) {
const cnt1: Record<string, number> = {};
for (let j = i; j < i + k; j++) {
cnt1[s[j]] = (cnt1[s[j]] || 0) + 1;
}
for (const [c, v] of Object.entries(cnt)) {
if (cnt1[c] * ((n / k) | 0) !== v) {
return false;
}
}
}
return true;
};
for (let i = 1; ; ++i) {
if (n % i === 0 && check(i)) {
return i;
}
}
}
|
3,140 |
Consecutive Available Seats II
|
Medium
|
<p>Table: <code>Cinema</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id | int |
| free | bool |
+-------------+------+
seat_id is an auto-increment column for this table.
Each row of this table indicates whether the i<sup>th</sup> seat is free or not. 1 means free while 0 means occupied.
</pre>
<p>Write a solution to find the <strong>length</strong> of <strong>longest consecutive sequence</strong> of <strong>available</strong> seats in the cinema.</p>
<p>Note:</p>
<ul>
<li>There will always be <strong>at most</strong> <strong>one</strong> longest consecutive sequence.</li>
<li>If there are <strong>multiple</strong> consecutive sequences with the <strong>same length</strong>, include all of them in the output.</li>
</ul>
<p>Return <em>the result table <strong>ordered</strong> by</em> <code>first_seat_id</code> <em><strong>in ascending order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Cinema table:</p>
<pre class="example-io">
+---------+------+
| seat_id | free |
+---------+------+
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
+---------+------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------------+----------------+-----------------------+
| first_seat_id | last_seat_id | consecutive_seats_len |
+-----------------+----------------+-----------------------+
| 3 | 5 | 3 |
+-----------------+----------------+-----------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Longest consecutive sequence of available seats starts from seat 3 and ends at seat 5 with a length of 3.</li>
</ul>
Output table is ordered by first_seat_id in ascending order.</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
seat_id - (RANK() OVER (ORDER BY seat_id)) AS gid
FROM Cinema
WHERE free = 1
),
P AS (
SELECT
MIN(seat_id) AS first_seat_id,
MAX(seat_id) AS last_seat_id,
COUNT(1) AS consecutive_seats_len,
RANK() OVER (ORDER BY COUNT(1) DESC) AS rk
FROM T
GROUP BY gid
)
SELECT first_seat_id, last_seat_id, consecutive_seats_len
FROM P
WHERE rk = 1
ORDER BY 1;
|
3,141 |
Maximum Hamming Distances
|
Hard
|
<p>Given an array <code>nums</code> and an integer <code>m</code>, with each element <code>nums[i]</code> satisfying <code>0 <= nums[i] < 2<sup>m</sup></code>, return an array <code>answer</code>. The <code>answer</code> array should be of the same length as <code>nums</code>, where each element <code>answer[i]</code> represents the <em>maximum</em> <strong>Hamming distance </strong>between <code>nums[i]</code> and any other element <code>nums[j]</code> in the array.</p>
<p>The <strong>Hamming distance</strong> between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,12,9,11], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [1001,1100,1001,1011]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[1]</code>: 1100 and 1011 have a distance of 3.</li>
<li><code>nums[2]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[3]</code>: 1011 and 1100 have a distance of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,6,10], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [0011,0100,0110,1010]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 0011 and 0100 have a distance of 3.</li>
<li><code>nums[1]</code>: 0100 and 0011 have a distance of 3.</li>
<li><code>nums[2]</code>: 0110 and 1010 have a distance of 2.</li>
<li><code>nums[3]</code>: 1010 and 0100 have a distance of 3.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m <= 17</code></li>
<li><code>2 <= nums.length <= 2<sup>m</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>m</sup></code></li>
</ul>
|
Bit Manipulation; Breadth-First Search; Array
|
C++
|
class Solution {
public:
vector<int> maxHammingDistances(vector<int>& nums, int m) {
int dist[1 << m];
memset(dist, -1, sizeof(dist));
queue<int> q;
for (int x : nums) {
dist[x] = 0;
q.push(x);
}
for (int k = 1; q.size(); ++k) {
for (int t = q.size(); t; --t) {
int x = q.front();
q.pop();
for (int i = 0; i < m; ++i) {
int y = x ^ (1 << i);
if (dist[y] == -1) {
dist[y] = k;
q.push(y);
}
}
}
}
for (int& x : nums) {
x = m - dist[x ^ ((1 << m) - 1)];
}
return nums;
}
};
|
3,141 |
Maximum Hamming Distances
|
Hard
|
<p>Given an array <code>nums</code> and an integer <code>m</code>, with each element <code>nums[i]</code> satisfying <code>0 <= nums[i] < 2<sup>m</sup></code>, return an array <code>answer</code>. The <code>answer</code> array should be of the same length as <code>nums</code>, where each element <code>answer[i]</code> represents the <em>maximum</em> <strong>Hamming distance </strong>between <code>nums[i]</code> and any other element <code>nums[j]</code> in the array.</p>
<p>The <strong>Hamming distance</strong> between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,12,9,11], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [1001,1100,1001,1011]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[1]</code>: 1100 and 1011 have a distance of 3.</li>
<li><code>nums[2]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[3]</code>: 1011 and 1100 have a distance of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,6,10], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [0011,0100,0110,1010]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 0011 and 0100 have a distance of 3.</li>
<li><code>nums[1]</code>: 0100 and 0011 have a distance of 3.</li>
<li><code>nums[2]</code>: 0110 and 1010 have a distance of 2.</li>
<li><code>nums[3]</code>: 1010 and 0100 have a distance of 3.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m <= 17</code></li>
<li><code>2 <= nums.length <= 2<sup>m</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>m</sup></code></li>
</ul>
|
Bit Manipulation; Breadth-First Search; Array
|
Go
|
func maxHammingDistances(nums []int, m int) []int {
dist := make([]int, 1<<m)
for i := range dist {
dist[i] = -1
}
q := []int{}
for _, x := range nums {
dist[x] = 0
q = append(q, x)
}
for k := 1; len(q) > 0; k++ {
t := []int{}
for _, x := range q {
for i := 0; i < m; i++ {
y := x ^ (1 << i)
if dist[y] == -1 {
dist[y] = k
t = append(t, y)
}
}
}
q = t
}
for i, x := range nums {
nums[i] = m - dist[x^(1<<m-1)]
}
return nums
}
|
3,141 |
Maximum Hamming Distances
|
Hard
|
<p>Given an array <code>nums</code> and an integer <code>m</code>, with each element <code>nums[i]</code> satisfying <code>0 <= nums[i] < 2<sup>m</sup></code>, return an array <code>answer</code>. The <code>answer</code> array should be of the same length as <code>nums</code>, where each element <code>answer[i]</code> represents the <em>maximum</em> <strong>Hamming distance </strong>between <code>nums[i]</code> and any other element <code>nums[j]</code> in the array.</p>
<p>The <strong>Hamming distance</strong> between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,12,9,11], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [1001,1100,1001,1011]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[1]</code>: 1100 and 1011 have a distance of 3.</li>
<li><code>nums[2]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[3]</code>: 1011 and 1100 have a distance of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,6,10], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [0011,0100,0110,1010]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 0011 and 0100 have a distance of 3.</li>
<li><code>nums[1]</code>: 0100 and 0011 have a distance of 3.</li>
<li><code>nums[2]</code>: 0110 and 1010 have a distance of 2.</li>
<li><code>nums[3]</code>: 1010 and 0100 have a distance of 3.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m <= 17</code></li>
<li><code>2 <= nums.length <= 2<sup>m</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>m</sup></code></li>
</ul>
|
Bit Manipulation; Breadth-First Search; Array
|
Java
|
class Solution {
public int[] maxHammingDistances(int[] nums, int m) {
int[] dist = new int[1 << m];
Arrays.fill(dist, -1);
Deque<Integer> q = new ArrayDeque<>();
for (int x : nums) {
dist[x] = 0;
q.offer(x);
}
for (int k = 1; !q.isEmpty(); ++k) {
for (int t = q.size(); t > 0; --t) {
int x = q.poll();
for (int i = 0; i < m; ++i) {
int y = x ^ (1 << i);
if (dist[y] == -1) {
q.offer(y);
dist[y] = k;
}
}
}
}
for (int i = 0; i < nums.length; ++i) {
nums[i] = m - dist[nums[i] ^ ((1 << m) - 1)];
}
return nums;
}
}
|
3,141 |
Maximum Hamming Distances
|
Hard
|
<p>Given an array <code>nums</code> and an integer <code>m</code>, with each element <code>nums[i]</code> satisfying <code>0 <= nums[i] < 2<sup>m</sup></code>, return an array <code>answer</code>. The <code>answer</code> array should be of the same length as <code>nums</code>, where each element <code>answer[i]</code> represents the <em>maximum</em> <strong>Hamming distance </strong>between <code>nums[i]</code> and any other element <code>nums[j]</code> in the array.</p>
<p>The <strong>Hamming distance</strong> between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,12,9,11], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [1001,1100,1001,1011]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[1]</code>: 1100 and 1011 have a distance of 3.</li>
<li><code>nums[2]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[3]</code>: 1011 and 1100 have a distance of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,6,10], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [0011,0100,0110,1010]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 0011 and 0100 have a distance of 3.</li>
<li><code>nums[1]</code>: 0100 and 0011 have a distance of 3.</li>
<li><code>nums[2]</code>: 0110 and 1010 have a distance of 2.</li>
<li><code>nums[3]</code>: 1010 and 0100 have a distance of 3.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m <= 17</code></li>
<li><code>2 <= nums.length <= 2<sup>m</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>m</sup></code></li>
</ul>
|
Bit Manipulation; Breadth-First Search; Array
|
Python
|
class Solution:
def maxHammingDistances(self, nums: List[int], m: int) -> List[int]:
dist = [-1] * (1 << m)
for x in nums:
dist[x] = 0
q = nums
k = 1
while q:
t = []
for x in q:
for i in range(m):
y = x ^ (1 << i)
if dist[y] == -1:
t.append(y)
dist[y] = k
q = t
k += 1
return [m - dist[x ^ ((1 << m) - 1)] for x in nums]
|
3,141 |
Maximum Hamming Distances
|
Hard
|
<p>Given an array <code>nums</code> and an integer <code>m</code>, with each element <code>nums[i]</code> satisfying <code>0 <= nums[i] < 2<sup>m</sup></code>, return an array <code>answer</code>. The <code>answer</code> array should be of the same length as <code>nums</code>, where each element <code>answer[i]</code> represents the <em>maximum</em> <strong>Hamming distance </strong>between <code>nums[i]</code> and any other element <code>nums[j]</code> in the array.</p>
<p>The <strong>Hamming distance</strong> between two binary integers is defined as the number of positions at which the corresponding bits differ (add leading zeroes if needed).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,12,9,11], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [1001,1100,1001,1011]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[1]</code>: 1100 and 1011 have a distance of 3.</li>
<li><code>nums[2]</code>: 1001 and 1100 have a distance of 2.</li>
<li><code>nums[3]</code>: 1011 and 1100 have a distance of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,6,10], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of <code>nums = [0011,0100,0110,1010]</code>.</p>
<p>The maximum hamming distances for each index are:</p>
<ul>
<li><code>nums[0]</code>: 0011 and 0100 have a distance of 3.</li>
<li><code>nums[1]</code>: 0100 and 0011 have a distance of 3.</li>
<li><code>nums[2]</code>: 0110 and 1010 have a distance of 2.</li>
<li><code>nums[3]</code>: 1010 and 0100 have a distance of 3.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m <= 17</code></li>
<li><code>2 <= nums.length <= 2<sup>m</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>m</sup></code></li>
</ul>
|
Bit Manipulation; Breadth-First Search; Array
|
TypeScript
|
function maxHammingDistances(nums: number[], m: number): number[] {
const dist: number[] = Array.from({ length: 1 << m }, () => -1);
const q: number[] = [];
for (const x of nums) {
dist[x] = 0;
q.push(x);
}
for (let k = 1; q.length; ++k) {
const t: number[] = [];
for (const x of q) {
for (let i = 0; i < m; ++i) {
const y = x ^ (1 << i);
if (dist[y] === -1) {
dist[y] = k;
t.push(y);
}
}
}
q.splice(0, q.length, ...t);
}
for (let i = 0; i < nums.length; ++i) {
nums[i] = m - dist[nums[i] ^ ((1 << m) - 1)];
}
return nums;
}
|
3,142 |
Check if Grid Satisfies Conditions
|
Easy
|
<p>You are given a 2D matrix <code>grid</code> of size <code>m x n</code>. You need to check if each cell <code>grid[i][j]</code> is:</p>
<ul>
<li>Equal to the cell below it, i.e. <code>grid[i][j] == grid[i + 1][j]</code> (if it exists).</li>
<li>Different from the cell to its right, i.e. <code>grid[i][j] != grid[i][j + 1]</code> (if it exists).</li>
</ul>
<p>Return <code>true</code> if <strong>all</strong> the cells satisfy these conditions, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,2],[1,0,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/examplechanged.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All the cells in the grid satisfy the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[0,0,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/example21.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All cells in the first row are equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1],[2],[3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/changed.png" style="width: 86px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Cells in the first column have different values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10</code></li>
<li><code>0 <= grid[i][j] <= 9</code></li>
</ul>
|
Array; Matrix
|
C++
|
class Solution {
public:
bool satisfiesConditions(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
};
|
3,142 |
Check if Grid Satisfies Conditions
|
Easy
|
<p>You are given a 2D matrix <code>grid</code> of size <code>m x n</code>. You need to check if each cell <code>grid[i][j]</code> is:</p>
<ul>
<li>Equal to the cell below it, i.e. <code>grid[i][j] == grid[i + 1][j]</code> (if it exists).</li>
<li>Different from the cell to its right, i.e. <code>grid[i][j] != grid[i][j + 1]</code> (if it exists).</li>
</ul>
<p>Return <code>true</code> if <strong>all</strong> the cells satisfy these conditions, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,2],[1,0,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/examplechanged.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All the cells in the grid satisfy the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[0,0,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/example21.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All cells in the first row are equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1],[2],[3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/changed.png" style="width: 86px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Cells in the first column have different values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10</code></li>
<li><code>0 <= grid[i][j] <= 9</code></li>
</ul>
|
Array; Matrix
|
Go
|
func satisfiesConditions(grid [][]int) bool {
m, n := len(grid), len(grid[0])
for i, row := range grid {
for j, x := range row {
if i+1 < m && x != grid[i+1][j] {
return false
}
if j+1 < n && x == grid[i][j+1] {
return false
}
}
}
return true
}
|
3,142 |
Check if Grid Satisfies Conditions
|
Easy
|
<p>You are given a 2D matrix <code>grid</code> of size <code>m x n</code>. You need to check if each cell <code>grid[i][j]</code> is:</p>
<ul>
<li>Equal to the cell below it, i.e. <code>grid[i][j] == grid[i + 1][j]</code> (if it exists).</li>
<li>Different from the cell to its right, i.e. <code>grid[i][j] != grid[i][j + 1]</code> (if it exists).</li>
</ul>
<p>Return <code>true</code> if <strong>all</strong> the cells satisfy these conditions, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,2],[1,0,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/examplechanged.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All the cells in the grid satisfy the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[0,0,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/example21.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All cells in the first row are equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1],[2],[3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/changed.png" style="width: 86px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Cells in the first column have different values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10</code></li>
<li><code>0 <= grid[i][j] <= 9</code></li>
</ul>
|
Array; Matrix
|
Java
|
class Solution {
public boolean satisfiesConditions(int[][] grid) {
int m = grid.length, n = grid[0].length;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
}
|
3,142 |
Check if Grid Satisfies Conditions
|
Easy
|
<p>You are given a 2D matrix <code>grid</code> of size <code>m x n</code>. You need to check if each cell <code>grid[i][j]</code> is:</p>
<ul>
<li>Equal to the cell below it, i.e. <code>grid[i][j] == grid[i + 1][j]</code> (if it exists).</li>
<li>Different from the cell to its right, i.e. <code>grid[i][j] != grid[i][j + 1]</code> (if it exists).</li>
</ul>
<p>Return <code>true</code> if <strong>all</strong> the cells satisfy these conditions, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,2],[1,0,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/examplechanged.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All the cells in the grid satisfy the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[0,0,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/example21.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All cells in the first row are equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1],[2],[3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/changed.png" style="width: 86px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Cells in the first column have different values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10</code></li>
<li><code>0 <= grid[i][j] <= 9</code></li>
</ul>
|
Array; Matrix
|
Python
|
class Solution:
def satisfiesConditions(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
if i + 1 < m and x != grid[i + 1][j]:
return False
if j + 1 < n and x == grid[i][j + 1]:
return False
return True
|
3,142 |
Check if Grid Satisfies Conditions
|
Easy
|
<p>You are given a 2D matrix <code>grid</code> of size <code>m x n</code>. You need to check if each cell <code>grid[i][j]</code> is:</p>
<ul>
<li>Equal to the cell below it, i.e. <code>grid[i][j] == grid[i + 1][j]</code> (if it exists).</li>
<li>Different from the cell to its right, i.e. <code>grid[i][j] != grid[i][j + 1]</code> (if it exists).</li>
</ul>
<p>Return <code>true</code> if <strong>all</strong> the cells satisfy these conditions, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,0,2],[1,0,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/examplechanged.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All the cells in the grid satisfy the conditions.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[0,0,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/example21.png" style="width: 254px; height: 186px;padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
<p>All cells in the first row are equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1],[2],[3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3142.Check%20if%20Grid%20Satisfies%20Conditions/images/changed.png" style="width: 86px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Cells in the first column have different values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10</code></li>
<li><code>0 <= grid[i][j] <= 9</code></li>
</ul>
|
Array; Matrix
|
TypeScript
|
function satisfiesConditions(grid: number[][]): boolean {
const [m, n] = [grid.length, grid[0].length];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] !== grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] === grid[i][j + 1]) {
return false;
}
}
}
return true;
}
|
3,143 |
Maximum Points Inside the Square
|
Medium
|
<p>You are given a 2D<strong> </strong>array <code>points</code> and a string <code>s</code> where, <code>points[i]</code> represents the coordinates of point <code>i</code>, and <code>s[i]</code> represents the <strong>tag</strong> of point <code>i</code>.</p>
<p>A <strong>valid</strong> square is a square centered at the origin <code>(0, 0)</code>, has edges parallel to the axes, and <strong>does not</strong> contain two points with the same tag.</p>
<p>Return the <strong>maximum</strong> number of points contained in a <strong>valid</strong> square.</p>
<p>Note:</p>
<ul>
<li>A point is considered to be inside the square if it lies on or within the square's boundaries.</li>
<li>The side length of the square can be zero.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc1.png" style="width: 303px; height: 303px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 4 covers two points <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc2.png" style="width: 302px; height: 302px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-2,-2],[-2,2]], s = "abb"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 2 covers one point, which is <code>points[0]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-1,-1],[2,-2]], s = "ccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to make any valid squares centered at the origin such that it covers only one point among <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li><code>s.length == points.length</code></li>
<li><code>points</code> consists of distinct coordinates.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Binary Search; Sorting
|
C++
|
class Solution {
public:
int maxPointsInsideSquare(vector<vector<int>>& points, string s) {
map<int, vector<int>> g;
for (int i = 0; i < points.size(); ++i) {
auto& p = points[i];
int key = max(abs(p[0]), abs(p[1]));
g[key].push_back(i);
}
bool vis[26]{};
int ans = 0;
for (auto& [_, idx] : g) {
for (int i : idx) {
int j = s[i] - 'a';
if (vis[j]) {
return ans;
}
vis[j] = true;
}
ans += idx.size();
}
return ans;
}
};
|
3,143 |
Maximum Points Inside the Square
|
Medium
|
<p>You are given a 2D<strong> </strong>array <code>points</code> and a string <code>s</code> where, <code>points[i]</code> represents the coordinates of point <code>i</code>, and <code>s[i]</code> represents the <strong>tag</strong> of point <code>i</code>.</p>
<p>A <strong>valid</strong> square is a square centered at the origin <code>(0, 0)</code>, has edges parallel to the axes, and <strong>does not</strong> contain two points with the same tag.</p>
<p>Return the <strong>maximum</strong> number of points contained in a <strong>valid</strong> square.</p>
<p>Note:</p>
<ul>
<li>A point is considered to be inside the square if it lies on or within the square's boundaries.</li>
<li>The side length of the square can be zero.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc1.png" style="width: 303px; height: 303px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 4 covers two points <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc2.png" style="width: 302px; height: 302px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-2,-2],[-2,2]], s = "abb"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 2 covers one point, which is <code>points[0]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-1,-1],[2,-2]], s = "ccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to make any valid squares centered at the origin such that it covers only one point among <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li><code>s.length == points.length</code></li>
<li><code>points</code> consists of distinct coordinates.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Binary Search; Sorting
|
Go
|
func maxPointsInsideSquare(points [][]int, s string) (ans int) {
g := map[int][]int{}
for i, p := range points {
key := max(p[0], -p[0], p[1], -p[1])
g[key] = append(g[key], i)
}
vis := [26]bool{}
keys := []int{}
for k := range g {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
idx := g[k]
for _, i := range idx {
j := s[i] - 'a'
if vis[j] {
return
}
vis[j] = true
}
ans += len(idx)
}
return
}
|
3,143 |
Maximum Points Inside the Square
|
Medium
|
<p>You are given a 2D<strong> </strong>array <code>points</code> and a string <code>s</code> where, <code>points[i]</code> represents the coordinates of point <code>i</code>, and <code>s[i]</code> represents the <strong>tag</strong> of point <code>i</code>.</p>
<p>A <strong>valid</strong> square is a square centered at the origin <code>(0, 0)</code>, has edges parallel to the axes, and <strong>does not</strong> contain two points with the same tag.</p>
<p>Return the <strong>maximum</strong> number of points contained in a <strong>valid</strong> square.</p>
<p>Note:</p>
<ul>
<li>A point is considered to be inside the square if it lies on or within the square's boundaries.</li>
<li>The side length of the square can be zero.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc1.png" style="width: 303px; height: 303px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 4 covers two points <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc2.png" style="width: 302px; height: 302px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-2,-2],[-2,2]], s = "abb"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 2 covers one point, which is <code>points[0]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-1,-1],[2,-2]], s = "ccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to make any valid squares centered at the origin such that it covers only one point among <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li><code>s.length == points.length</code></li>
<li><code>points</code> consists of distinct coordinates.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Binary Search; Sorting
|
Java
|
class Solution {
public int maxPointsInsideSquare(int[][] points, String s) {
TreeMap<Integer, List<Integer>> g = new TreeMap<>();
for (int i = 0; i < points.length; ++i) {
int x = points[i][0], y = points[i][1];
int key = Math.max(Math.abs(x), Math.abs(y));
g.computeIfAbsent(key, k -> new ArrayList<>()).add(i);
}
boolean[] vis = new boolean[26];
int ans = 0;
for (var idx : g.values()) {
for (int i : idx) {
int j = s.charAt(i) - 'a';
if (vis[j]) {
return ans;
}
vis[j] = true;
}
ans += idx.size();
}
return ans;
}
}
|
3,143 |
Maximum Points Inside the Square
|
Medium
|
<p>You are given a 2D<strong> </strong>array <code>points</code> and a string <code>s</code> where, <code>points[i]</code> represents the coordinates of point <code>i</code>, and <code>s[i]</code> represents the <strong>tag</strong> of point <code>i</code>.</p>
<p>A <strong>valid</strong> square is a square centered at the origin <code>(0, 0)</code>, has edges parallel to the axes, and <strong>does not</strong> contain two points with the same tag.</p>
<p>Return the <strong>maximum</strong> number of points contained in a <strong>valid</strong> square.</p>
<p>Note:</p>
<ul>
<li>A point is considered to be inside the square if it lies on or within the square's boundaries.</li>
<li>The side length of the square can be zero.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc1.png" style="width: 303px; height: 303px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 4 covers two points <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc2.png" style="width: 302px; height: 302px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-2,-2],[-2,2]], s = "abb"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 2 covers one point, which is <code>points[0]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-1,-1],[2,-2]], s = "ccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to make any valid squares centered at the origin such that it covers only one point among <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li><code>s.length == points.length</code></li>
<li><code>points</code> consists of distinct coordinates.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Binary Search; Sorting
|
Python
|
class Solution:
def maxPointsInsideSquare(self, points: List[List[int]], s: str) -> int:
g = defaultdict(list)
for i, (x, y) in enumerate(points):
g[max(abs(x), abs(y))].append(i)
vis = set()
ans = 0
for d in sorted(g):
idx = g[d]
for i in idx:
if s[i] in vis:
return ans
vis.add(s[i])
ans += len(idx)
return ans
|
3,143 |
Maximum Points Inside the Square
|
Medium
|
<p>You are given a 2D<strong> </strong>array <code>points</code> and a string <code>s</code> where, <code>points[i]</code> represents the coordinates of point <code>i</code>, and <code>s[i]</code> represents the <strong>tag</strong> of point <code>i</code>.</p>
<p>A <strong>valid</strong> square is a square centered at the origin <code>(0, 0)</code>, has edges parallel to the axes, and <strong>does not</strong> contain two points with the same tag.</p>
<p>Return the <strong>maximum</strong> number of points contained in a <strong>valid</strong> square.</p>
<p>Note:</p>
<ul>
<li>A point is considered to be inside the square if it lies on or within the square's boundaries.</li>
<li>The side length of the square can be zero.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc1.png" style="width: 303px; height: 303px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 4 covers two points <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3143.Maximum%20Points%20Inside%20the%20Square/images/3708-tc2.png" style="width: 302px; height: 302px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-2,-2],[-2,2]], s = "abb"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The square of side length 2 covers one point, which is <code>points[0]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[-1,-1],[2,-2]], s = "ccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to make any valid squares centered at the origin such that it covers only one point among <code>points[0]</code> and <code>points[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li><code>s.length == points.length</code></li>
<li><code>points</code> consists of distinct coordinates.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; String; Binary Search; Sorting
|
TypeScript
|
function maxPointsInsideSquare(points: number[][], s: string): number {
const n = points.length;
const g: Map<number, number[]> = new Map();
for (let i = 0; i < n; ++i) {
const [x, y] = points[i];
const key = Math.max(Math.abs(x), Math.abs(y));
if (!g.has(key)) {
g.set(key, []);
}
g.get(key)!.push(i);
}
const keys = Array.from(g.keys()).sort((a, b) => a - b);
const vis: boolean[] = Array(26).fill(false);
let ans = 0;
for (const key of keys) {
const idx = g.get(key)!;
for (const i of idx) {
const j = s.charCodeAt(i) - 'a'.charCodeAt(0);
if (vis[j]) {
return ans;
}
vis[j] = true;
}
ans += idx.length;
}
return ans;
}
|
3,144 |
Minimum Substring Partition of Equal Character Frequency
|
Medium
|
<p>Given a string <code>s</code>, you need to partition it into one or more <strong>balanced</strong> <span data-keyword="substring">substrings</span>. For example, if <code>s == "ababcc"</code> then <code>("abab", "c", "c")</code>, <code>("ab", "abc", "c")</code>, and <code>("ababcc")</code> are all valid partitions, but <code>("a", <strong>"bab"</strong>, "cc")</code>, <code>(<strong>"aba"</strong>, "bc", "c")</code>, and <code>("ab", <strong>"abcc"</strong>)</code> are not. The unbalanced substrings are bolded.</p>
<p>Return the <strong>minimum</strong> number of substrings that you can partition <code>s</code> into.</p>
<p><strong>Note:</strong> A <strong>balanced</strong> string is a string where each character in the string occurs the same number of times.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "fabccddg"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 3 substrings in one of the following ways: <code>("fab, "ccdd", "g")</code>, or <code>("fabc", "cd", "dg")</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abababaccddb"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 2 substrings like so: <code>("abab", "abaccddb")</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> consists only of English lowercase letters.</li>
</ul>
|
Hash Table; String; Dynamic Programming; Counting
|
C++
|
class Solution {
public:
int minimumSubstringsInPartition(string s) {
int n = s.size();
int f[n];
memset(f, -1, sizeof(f));
auto dfs = [&](this auto&& dfs, int i) -> int {
if (i >= n) {
return 0;
}
if (f[i] != -1) {
return f[i];
}
f[i] = n - i;
int cnt[26]{};
unordered_map<int, int> freq;
for (int j = i; j < n; ++j) {
int k = s[j] - 'a';
if (cnt[k]) {
freq[cnt[k]]--;
if (freq[cnt[k]] == 0) {
freq.erase(cnt[k]);
}
}
++cnt[k];
++freq[cnt[k]];
if (freq.size() == 1) {
f[i] = min(f[i], 1 + dfs(j + 1));
}
}
return f[i];
};
return dfs(0);
}
};
|
3,144 |
Minimum Substring Partition of Equal Character Frequency
|
Medium
|
<p>Given a string <code>s</code>, you need to partition it into one or more <strong>balanced</strong> <span data-keyword="substring">substrings</span>. For example, if <code>s == "ababcc"</code> then <code>("abab", "c", "c")</code>, <code>("ab", "abc", "c")</code>, and <code>("ababcc")</code> are all valid partitions, but <code>("a", <strong>"bab"</strong>, "cc")</code>, <code>(<strong>"aba"</strong>, "bc", "c")</code>, and <code>("ab", <strong>"abcc"</strong>)</code> are not. The unbalanced substrings are bolded.</p>
<p>Return the <strong>minimum</strong> number of substrings that you can partition <code>s</code> into.</p>
<p><strong>Note:</strong> A <strong>balanced</strong> string is a string where each character in the string occurs the same number of times.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "fabccddg"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 3 substrings in one of the following ways: <code>("fab, "ccdd", "g")</code>, or <code>("fabc", "cd", "dg")</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abababaccddb"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 2 substrings like so: <code>("abab", "abaccddb")</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> consists only of English lowercase letters.</li>
</ul>
|
Hash Table; String; Dynamic Programming; Counting
|
Go
|
func minimumSubstringsInPartition(s string) int {
n := len(s)
f := make([]int, n)
for i := range f {
f[i] = -1
}
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] != -1 {
return f[i]
}
cnt := [26]int{}
freq := map[int]int{}
f[i] = n - i
for j := i; j < n; j++ {
k := int(s[j] - 'a')
if cnt[k] > 0 {
freq[cnt[k]]--
if freq[cnt[k]] == 0 {
delete(freq, cnt[k])
}
}
cnt[k]++
freq[cnt[k]]++
if len(freq) == 1 {
f[i] = min(f[i], 1+dfs(j+1))
}
}
return f[i]
}
return dfs(0)
}
|
3,144 |
Minimum Substring Partition of Equal Character Frequency
|
Medium
|
<p>Given a string <code>s</code>, you need to partition it into one or more <strong>balanced</strong> <span data-keyword="substring">substrings</span>. For example, if <code>s == "ababcc"</code> then <code>("abab", "c", "c")</code>, <code>("ab", "abc", "c")</code>, and <code>("ababcc")</code> are all valid partitions, but <code>("a", <strong>"bab"</strong>, "cc")</code>, <code>(<strong>"aba"</strong>, "bc", "c")</code>, and <code>("ab", <strong>"abcc"</strong>)</code> are not. The unbalanced substrings are bolded.</p>
<p>Return the <strong>minimum</strong> number of substrings that you can partition <code>s</code> into.</p>
<p><strong>Note:</strong> A <strong>balanced</strong> string is a string where each character in the string occurs the same number of times.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "fabccddg"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 3 substrings in one of the following ways: <code>("fab, "ccdd", "g")</code>, or <code>("fabc", "cd", "dg")</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abababaccddb"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 2 substrings like so: <code>("abab", "abaccddb")</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> consists only of English lowercase letters.</li>
</ul>
|
Hash Table; String; Dynamic Programming; Counting
|
Java
|
class Solution {
private int n;
private char[] s;
private Integer[] f;
public int minimumSubstringsInPartition(String s) {
n = s.length();
f = new Integer[n];
this.s = s.toCharArray();
return dfs(0);
}
private int dfs(int i) {
if (i >= n) {
return 0;
}
if (f[i] != null) {
return f[i];
}
int[] cnt = new int[26];
Map<Integer, Integer> freq = new HashMap<>(26);
int ans = n - i;
for (int j = i; j < n; ++j) {
int k = s[j] - 'a';
if (cnt[k] > 0) {
if (freq.merge(cnt[k], -1, Integer::sum) == 0) {
freq.remove(cnt[k]);
}
}
++cnt[k];
freq.merge(cnt[k], 1, Integer::sum);
if (freq.size() == 1) {
ans = Math.min(ans, 1 + dfs(j + 1));
}
}
return f[i] = ans;
}
}
|
3,144 |
Minimum Substring Partition of Equal Character Frequency
|
Medium
|
<p>Given a string <code>s</code>, you need to partition it into one or more <strong>balanced</strong> <span data-keyword="substring">substrings</span>. For example, if <code>s == "ababcc"</code> then <code>("abab", "c", "c")</code>, <code>("ab", "abc", "c")</code>, and <code>("ababcc")</code> are all valid partitions, but <code>("a", <strong>"bab"</strong>, "cc")</code>, <code>(<strong>"aba"</strong>, "bc", "c")</code>, and <code>("ab", <strong>"abcc"</strong>)</code> are not. The unbalanced substrings are bolded.</p>
<p>Return the <strong>minimum</strong> number of substrings that you can partition <code>s</code> into.</p>
<p><strong>Note:</strong> A <strong>balanced</strong> string is a string where each character in the string occurs the same number of times.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "fabccddg"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 3 substrings in one of the following ways: <code>("fab, "ccdd", "g")</code>, or <code>("fabc", "cd", "dg")</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abababaccddb"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 2 substrings like so: <code>("abab", "abaccddb")</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> consists only of English lowercase letters.</li>
</ul>
|
Hash Table; String; Dynamic Programming; Counting
|
Python
|
class Solution:
def minimumSubstringsInPartition(self, s: str) -> int:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
cnt = defaultdict(int)
freq = defaultdict(int)
ans = n - i
for j in range(i, n):
if cnt[s[j]]:
freq[cnt[s[j]]] -= 1
if not freq[cnt[s[j]]]:
freq.pop(cnt[s[j]])
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
if len(freq) == 1 and (t := 1 + dfs(j + 1)) < ans:
ans = t
return ans
n = len(s)
return dfs(0)
|
3,144 |
Minimum Substring Partition of Equal Character Frequency
|
Medium
|
<p>Given a string <code>s</code>, you need to partition it into one or more <strong>balanced</strong> <span data-keyword="substring">substrings</span>. For example, if <code>s == "ababcc"</code> then <code>("abab", "c", "c")</code>, <code>("ab", "abc", "c")</code>, and <code>("ababcc")</code> are all valid partitions, but <code>("a", <strong>"bab"</strong>, "cc")</code>, <code>(<strong>"aba"</strong>, "bc", "c")</code>, and <code>("ab", <strong>"abcc"</strong>)</code> are not. The unbalanced substrings are bolded.</p>
<p>Return the <strong>minimum</strong> number of substrings that you can partition <code>s</code> into.</p>
<p><strong>Note:</strong> A <strong>balanced</strong> string is a string where each character in the string occurs the same number of times.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "fabccddg"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 3 substrings in one of the following ways: <code>("fab, "ccdd", "g")</code>, or <code>("fabc", "cd", "dg")</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abababaccddb"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can partition the string <code>s</code> into 2 substrings like so: <code>("abab", "abaccddb")</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> consists only of English lowercase letters.</li>
</ul>
|
Hash Table; String; Dynamic Programming; Counting
|
TypeScript
|
function minimumSubstringsInPartition(s: string): number {
const n = s.length;
const f: number[] = Array(n).fill(-1);
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i] !== -1) {
return f[i];
}
const cnt: Map<number, number> = new Map();
const freq: Map<number, number> = new Map();
f[i] = n - i;
for (let j = i; j < n; ++j) {
const k = s.charCodeAt(j) - 97;
if (freq.has(cnt.get(k)!)) {
freq.set(cnt.get(k)!, freq.get(cnt.get(k)!)! - 1);
if (freq.get(cnt.get(k)!) === 0) {
freq.delete(cnt.get(k)!);
}
}
cnt.set(k, (cnt.get(k) || 0) + 1);
freq.set(cnt.get(k)!, (freq.get(cnt.get(k)!) || 0) + 1);
if (freq.size === 1) {
f[i] = Math.min(f[i], 1 + dfs(j + 1));
}
}
return f[i];
};
return dfs(0);
}
|
3,145 |
Find Products of Elements of Big Array
|
Hard
|
<p>The <strong>powerful array</strong> of a non-negative integer <code>x</code> is defined as the shortest sorted array of powers of two that sum up to <code>x</code>. The table below illustrates examples of how the <strong>powerful array</strong> is determined. It can be proven that the powerful array of <code>x</code> is unique.</p>
<table border="1">
<tbody>
<tr>
<th>num</th>
<th>Binary Representation</th>
<th>powerful array</th>
</tr>
<tr>
<td>1</td>
<td>0000<u>1</u></td>
<td>[1]</td>
</tr>
<tr>
<td>8</td>
<td>0<u>1</u>000</td>
<td>[8]</td>
</tr>
<tr>
<td>10</td>
<td>0<u>1</u>0<u>1</u>0</td>
<td>[2, 8]</td>
</tr>
<tr>
<td>13</td>
<td>0<u>11</u>0<u>1</u></td>
<td>[1, 4, 8]</td>
</tr>
<tr>
<td>23</td>
<td><u>1</u>0<u>111</u></td>
<td>[1, 2, 4, 16]</td>
</tr>
</tbody>
</table>
<p>The array <code>big_nums</code> is created by concatenating the <strong>powerful arrays</strong> for every positive integer <code>i</code> in ascending order: 1, 2, 3, and so on. Thus, <code>big_nums</code> begins as <code>[<u>1</u>, <u>2</u>, <u>1, 2</u>, <u>4</u>, <u>1, 4</u>, <u>2, 4</u>, <u>1, 2, 4</u>, <u>8</u>, ...]</code>.</p>
<p>You are given a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>, mod<sub>i</sub>]</code> you should calculate <code>(big_nums[from<sub>i</sub>] * big_nums[from<sub>i</sub> + 1] * ... * big_nums[to<sub>i</sub>]) % mod<sub>i</sub></code><!-- notionvc: a71131cc-7b52-4786-9a4b-660d6d864f89 -->.</p>
<p>Return an integer array <code>answer</code> such that <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[1,3,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one query.</p>
<p><code>big_nums[1..3] = [2,1,2]</code>. The product of them is 4. The result is <code>4 % 7 = 4.</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[2,5,3],[7,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two queries.</p>
<p>First query: <code>big_nums[2..5] = [1,2,4,1]</code>. The product of them is 8. The result is <code>8 % 3 = 2</code>.</p>
<p>Second query: <code>big_nums[7] = 2</code>. The result is <code>2 % 4 = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= queries.length <= 500</code></li>
<li><code>queries[i].length == 3</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= 10<sup>15</sup></code></li>
<li><code>1 <= queries[i][2] <= 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Array; Binary Search
|
C++
|
using ll = long long;
const int m = 50;
ll cnt[m + 1];
ll s[m + 1];
ll p = 1;
auto init = [] {
cnt[0] = 0;
s[0] = 0;
for (int i = 1; i <= m; ++i) {
cnt[i] = cnt[i - 1] * 2 + p;
s[i] = s[i - 1] * 2 + p * (i - 1);
p *= 2;
}
return 0;
}();
pair<ll, ll> numIdxAndSum(ll x) {
ll idx = 0;
ll totalSum = 0;
while (x > 0) {
int i = 63 - __builtin_clzll(x);
idx += cnt[i];
totalSum += s[i];
x -= 1LL << i;
totalSum += (x + 1) * i;
idx += x + 1;
}
return make_pair(idx, totalSum);
}
ll f(ll i) {
ll l = 0;
ll r = 1LL << m;
while (l < r) {
ll mid = (l + r + 1) >> 1;
auto idxAndSum = numIdxAndSum(mid);
ll idx = idxAndSum.first;
if (idx < i) {
l = mid;
} else {
r = mid - 1;
}
}
auto idxAndSum = numIdxAndSum(l);
ll totalSum = idxAndSum.second;
ll idx = idxAndSum.first;
i -= idx;
ll x = l + 1;
for (int j = 0; j < i; ++j) {
ll y = x & -x;
totalSum += __builtin_ctzll(y);
x -= y;
}
return totalSum;
}
ll qpow(ll a, ll n, ll mod) {
ll ans = 1 % mod;
a = a % mod;
while (n > 0) {
if (n & 1) {
ans = ans * a % mod;
}
a = a * a % mod;
n >>= 1;
}
return ans;
}
class Solution {
public:
vector<int> findProductsOfElements(vector<vector<ll>>& queries) {
int n = queries.size();
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ll left = queries[i][0];
ll right = queries[i][1];
ll mod = queries[i][2];
ll power = f(right + 1) - f(left);
ans[i] = static_cast<int>(qpow(2, power, mod));
}
return ans;
}
};
|
3,145 |
Find Products of Elements of Big Array
|
Hard
|
<p>The <strong>powerful array</strong> of a non-negative integer <code>x</code> is defined as the shortest sorted array of powers of two that sum up to <code>x</code>. The table below illustrates examples of how the <strong>powerful array</strong> is determined. It can be proven that the powerful array of <code>x</code> is unique.</p>
<table border="1">
<tbody>
<tr>
<th>num</th>
<th>Binary Representation</th>
<th>powerful array</th>
</tr>
<tr>
<td>1</td>
<td>0000<u>1</u></td>
<td>[1]</td>
</tr>
<tr>
<td>8</td>
<td>0<u>1</u>000</td>
<td>[8]</td>
</tr>
<tr>
<td>10</td>
<td>0<u>1</u>0<u>1</u>0</td>
<td>[2, 8]</td>
</tr>
<tr>
<td>13</td>
<td>0<u>11</u>0<u>1</u></td>
<td>[1, 4, 8]</td>
</tr>
<tr>
<td>23</td>
<td><u>1</u>0<u>111</u></td>
<td>[1, 2, 4, 16]</td>
</tr>
</tbody>
</table>
<p>The array <code>big_nums</code> is created by concatenating the <strong>powerful arrays</strong> for every positive integer <code>i</code> in ascending order: 1, 2, 3, and so on. Thus, <code>big_nums</code> begins as <code>[<u>1</u>, <u>2</u>, <u>1, 2</u>, <u>4</u>, <u>1, 4</u>, <u>2, 4</u>, <u>1, 2, 4</u>, <u>8</u>, ...]</code>.</p>
<p>You are given a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>, mod<sub>i</sub>]</code> you should calculate <code>(big_nums[from<sub>i</sub>] * big_nums[from<sub>i</sub> + 1] * ... * big_nums[to<sub>i</sub>]) % mod<sub>i</sub></code><!-- notionvc: a71131cc-7b52-4786-9a4b-660d6d864f89 -->.</p>
<p>Return an integer array <code>answer</code> such that <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[1,3,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one query.</p>
<p><code>big_nums[1..3] = [2,1,2]</code>. The product of them is 4. The result is <code>4 % 7 = 4.</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[2,5,3],[7,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two queries.</p>
<p>First query: <code>big_nums[2..5] = [1,2,4,1]</code>. The product of them is 8. The result is <code>8 % 3 = 2</code>.</p>
<p>Second query: <code>big_nums[7] = 2</code>. The result is <code>2 % 4 = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= queries.length <= 500</code></li>
<li><code>queries[i].length == 3</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= 10<sup>15</sup></code></li>
<li><code>1 <= queries[i][2] <= 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Array; Binary Search
|
Go
|
const m = 50
var cnt [m + 1]int64
var s [m + 1]int64
var p int64 = 1
func init() {
cnt[0] = 0
s[0] = 0
for i := 1; i <= m; i++ {
cnt[i] = cnt[i-1]*2 + p
s[i] = s[i-1]*2 + p*(int64(i)-1)
p *= 2
}
}
func numIdxAndSum(x int64) (int64, int64) {
var idx, totalSum int64
for x > 0 {
i := 63 - bits.LeadingZeros64(uint64(x))
idx += cnt[i]
totalSum += s[i]
x -= 1 << i
totalSum += (x + 1) * int64(i)
idx += x + 1
}
return idx, totalSum
}
func f(i int64) int64 {
l, r := int64(0), int64(1)<<m
for l < r {
mid := (l + r + 1) >> 1
idx, _ := numIdxAndSum(mid)
if idx < i {
l = mid
} else {
r = mid - 1
}
}
_, totalSum := numIdxAndSum(l)
idx, _ := numIdxAndSum(l)
i -= idx
x := l + 1
for j := int64(0); j < i; j++ {
y := x & -x
totalSum += int64(bits.TrailingZeros64(uint64(y)))
x -= y
}
return totalSum
}
func qpow(a, n, mod int64) int64 {
ans := int64(1) % mod
a = a % mod
for n > 0 {
if n&1 == 1 {
ans = (ans * a) % mod
}
a = (a * a) % mod
n >>= 1
}
return ans
}
func findProductsOfElements(queries [][]int64) []int {
ans := make([]int, len(queries))
for i, q := range queries {
left, right, mod := q[0], q[1], q[2]
power := f(right+1) - f(left)
ans[i] = int(qpow(2, power, mod))
}
return ans
}
|
3,145 |
Find Products of Elements of Big Array
|
Hard
|
<p>The <strong>powerful array</strong> of a non-negative integer <code>x</code> is defined as the shortest sorted array of powers of two that sum up to <code>x</code>. The table below illustrates examples of how the <strong>powerful array</strong> is determined. It can be proven that the powerful array of <code>x</code> is unique.</p>
<table border="1">
<tbody>
<tr>
<th>num</th>
<th>Binary Representation</th>
<th>powerful array</th>
</tr>
<tr>
<td>1</td>
<td>0000<u>1</u></td>
<td>[1]</td>
</tr>
<tr>
<td>8</td>
<td>0<u>1</u>000</td>
<td>[8]</td>
</tr>
<tr>
<td>10</td>
<td>0<u>1</u>0<u>1</u>0</td>
<td>[2, 8]</td>
</tr>
<tr>
<td>13</td>
<td>0<u>11</u>0<u>1</u></td>
<td>[1, 4, 8]</td>
</tr>
<tr>
<td>23</td>
<td><u>1</u>0<u>111</u></td>
<td>[1, 2, 4, 16]</td>
</tr>
</tbody>
</table>
<p>The array <code>big_nums</code> is created by concatenating the <strong>powerful arrays</strong> for every positive integer <code>i</code> in ascending order: 1, 2, 3, and so on. Thus, <code>big_nums</code> begins as <code>[<u>1</u>, <u>2</u>, <u>1, 2</u>, <u>4</u>, <u>1, 4</u>, <u>2, 4</u>, <u>1, 2, 4</u>, <u>8</u>, ...]</code>.</p>
<p>You are given a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>, mod<sub>i</sub>]</code> you should calculate <code>(big_nums[from<sub>i</sub>] * big_nums[from<sub>i</sub> + 1] * ... * big_nums[to<sub>i</sub>]) % mod<sub>i</sub></code><!-- notionvc: a71131cc-7b52-4786-9a4b-660d6d864f89 -->.</p>
<p>Return an integer array <code>answer</code> such that <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[1,3,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one query.</p>
<p><code>big_nums[1..3] = [2,1,2]</code>. The product of them is 4. The result is <code>4 % 7 = 4.</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[2,5,3],[7,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two queries.</p>
<p>First query: <code>big_nums[2..5] = [1,2,4,1]</code>. The product of them is 8. The result is <code>8 % 3 = 2</code>.</p>
<p>Second query: <code>big_nums[7] = 2</code>. The result is <code>2 % 4 = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= queries.length <= 500</code></li>
<li><code>queries[i].length == 3</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= 10<sup>15</sup></code></li>
<li><code>1 <= queries[i][2] <= 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Array; Binary Search
|
Java
|
class Solution {
private static final int M = 50;
private static final long[] cnt = new long[M + 1];
private static final long[] s = new long[M + 1];
static {
long p = 1;
for (int i = 1; i <= M; i++) {
cnt[i] = cnt[i - 1] * 2 + p;
s[i] = s[i - 1] * 2 + p * (i - 1);
p *= 2;
}
}
private static long[] numIdxAndSum(long x) {
long idx = 0;
long totalSum = 0;
while (x > 0) {
int i = Long.SIZE - Long.numberOfLeadingZeros(x) - 1;
idx += cnt[i];
totalSum += s[i];
x -= 1L << i;
totalSum += (x + 1) * i;
idx += x + 1;
}
return new long[] {idx, totalSum};
}
private static long f(long i) {
long l = 0;
long r = 1L << M;
while (l < r) {
long mid = (l + r + 1) >> 1;
long[] idxAndSum = numIdxAndSum(mid);
long idx = idxAndSum[0];
if (idx < i) {
l = mid;
} else {
r = mid - 1;
}
}
long[] idxAndSum = numIdxAndSum(l);
long totalSum = idxAndSum[1];
long idx = idxAndSum[0];
i -= idx;
long x = l + 1;
for (int j = 0; j < i; j++) {
long y = x & -x;
totalSum += Long.numberOfTrailingZeros(y);
x -= y;
}
return totalSum;
}
public int[] findProductsOfElements(long[][] queries) {
int n = queries.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
long left = queries[i][0];
long right = queries[i][1];
long mod = queries[i][2];
long power = f(right + 1) - f(left);
ans[i] = qpow(2, power, mod);
}
return ans;
}
private int qpow(long a, long n, long mod) {
long ans = 1 % mod;
for (; n > 0; n >>= 1) {
if ((n & 1) == 1) {
ans = ans * a % mod;
}
a = a * a % mod;
}
return (int) ans;
}
}
|
3,145 |
Find Products of Elements of Big Array
|
Hard
|
<p>The <strong>powerful array</strong> of a non-negative integer <code>x</code> is defined as the shortest sorted array of powers of two that sum up to <code>x</code>. The table below illustrates examples of how the <strong>powerful array</strong> is determined. It can be proven that the powerful array of <code>x</code> is unique.</p>
<table border="1">
<tbody>
<tr>
<th>num</th>
<th>Binary Representation</th>
<th>powerful array</th>
</tr>
<tr>
<td>1</td>
<td>0000<u>1</u></td>
<td>[1]</td>
</tr>
<tr>
<td>8</td>
<td>0<u>1</u>000</td>
<td>[8]</td>
</tr>
<tr>
<td>10</td>
<td>0<u>1</u>0<u>1</u>0</td>
<td>[2, 8]</td>
</tr>
<tr>
<td>13</td>
<td>0<u>11</u>0<u>1</u></td>
<td>[1, 4, 8]</td>
</tr>
<tr>
<td>23</td>
<td><u>1</u>0<u>111</u></td>
<td>[1, 2, 4, 16]</td>
</tr>
</tbody>
</table>
<p>The array <code>big_nums</code> is created by concatenating the <strong>powerful arrays</strong> for every positive integer <code>i</code> in ascending order: 1, 2, 3, and so on. Thus, <code>big_nums</code> begins as <code>[<u>1</u>, <u>2</u>, <u>1, 2</u>, <u>4</u>, <u>1, 4</u>, <u>2, 4</u>, <u>1, 2, 4</u>, <u>8</u>, ...]</code>.</p>
<p>You are given a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>, mod<sub>i</sub>]</code> you should calculate <code>(big_nums[from<sub>i</sub>] * big_nums[from<sub>i</sub> + 1] * ... * big_nums[to<sub>i</sub>]) % mod<sub>i</sub></code><!-- notionvc: a71131cc-7b52-4786-9a4b-660d6d864f89 -->.</p>
<p>Return an integer array <code>answer</code> such that <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[1,3,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one query.</p>
<p><code>big_nums[1..3] = [2,1,2]</code>. The product of them is 4. The result is <code>4 % 7 = 4.</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">queries = [[2,5,3],[7,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two queries.</p>
<p>First query: <code>big_nums[2..5] = [1,2,4,1]</code>. The product of them is 8. The result is <code>8 % 3 = 2</code>.</p>
<p>Second query: <code>big_nums[7] = 2</code>. The result is <code>2 % 4 = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= queries.length <= 500</code></li>
<li><code>queries[i].length == 3</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= 10<sup>15</sup></code></li>
<li><code>1 <= queries[i][2] <= 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Array; Binary Search
|
Python
|
m = 50
cnt = [0] * (m + 1)
s = [0] * (m + 1)
p = 1
for i in range(1, m + 1):
cnt[i] = cnt[i - 1] * 2 + p
s[i] = s[i - 1] * 2 + p * (i - 1)
p *= 2
def num_idx_and_sum(x: int) -> tuple:
idx = 0
total_sum = 0
while x:
i = x.bit_length() - 1
idx += cnt[i]
total_sum += s[i]
x -= 1 << i
total_sum += (x + 1) * i
idx += x + 1
return (idx, total_sum)
def f(i: int) -> int:
l, r = 0, 1 << m
while l < r:
mid = (l + r + 1) >> 1
idx, _ = num_idx_and_sum(mid)
if idx < i:
l = mid
else:
r = mid - 1
total_sum = 0
idx, total_sum = num_idx_and_sum(l)
i -= idx
x = l + 1
for _ in range(i):
y = x & -x
total_sum += y.bit_length() - 1
x -= y
return total_sum
class Solution:
def findProductsOfElements(self, queries: List[List[int]]) -> List[int]:
return [pow(2, f(right + 1) - f(left), mod) for left, right, mod in queries]
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
C++
|
class Solution {
public:
int findPermutationDifference(string s, string t) {
int d[26]{};
int n = s.size();
for (int i = 0; i < n; ++i) {
d[s[i] - 'a'] = i;
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += abs(d[t[i] - 'a'] - i);
}
return ans;
}
};
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
C#
|
public class Solution {
public int FindPermutationDifference(string s, string t) {
int[] d = new int[26];
int n = s.Length;
for (int i = 0; i < n; ++i) {
d[s[i] - 'a'] = i;
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.Abs(d[t[i] - 'a'] - i);
}
return ans;
}
}
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Go
|
func findPermutationDifference(s string, t string) (ans int) {
d := [26]int{}
for i, c := range s {
d[c-'a'] = i
}
for i, c := range t {
ans += max(d[c-'a']-i, i-d[c-'a'])
}
return
}
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Java
|
class Solution {
public int findPermutationDifference(String s, String t) {
int[] d = new int[26];
int n = s.length();
for (int i = 0; i < n; ++i) {
d[s.charAt(i) - 'a'] = i;
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.abs(d[t.charAt(i) - 'a'] - i);
}
return ans;
}
}
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Python
|
class Solution:
def findPermutationDifference(self, s: str, t: str) -> int:
d = {c: i for i, c in enumerate(s)}
return sum(abs(d[c] - i) for i, c in enumerate(t))
|
3,146 |
Permutation Difference between Two Strings
|
Easy
|
<p>You are given two strings <code>s</code> and <code>t</code> such that every character occurs at most once in <code>s</code> and <code>t</code> is a permutation of <code>s</code>.</p>
<p>The <strong>permutation difference</strong> between <code>s</code> and <code>t</code> is defined as the <strong>sum</strong> of the absolute difference between the index of the occurrence of each character in <code>s</code> and the index of the occurrence of the same character in <code>t</code>.</p>
<p>Return the <strong>permutation difference</strong> between <code>s</code> and <code>t</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "bac"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>For <code>s = "abc"</code> and <code>t = "bac"</code>, the permutation difference of <code>s</code> and <code>t</code> is equal to the sum of:</p>
<ul>
<li>The absolute difference between the index of the occurrence of <code>"a"</code> in <code>s</code> and the index of the occurrence of <code>"a"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"b"</code> in <code>s</code> and the index of the occurrence of <code>"b"</code> in <code>t</code>.</li>
<li>The absolute difference between the index of the occurrence of <code>"c"</code> in <code>s</code> and the index of the occurrence of <code>"c"</code> in <code>t</code>.</li>
</ul>
<p>That is, the permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 1| + |1 - 0| + |2 - 2| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "edbac"</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong> The permutation difference between <code>s</code> and <code>t</code> is equal to <code>|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 26</code></li>
<li>Each character occurs at most once in <code>s</code>.</li>
<li><code>t</code> is a permutation of <code>s</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
TypeScript
|
function findPermutationDifference(s: string, t: string): number {
const d: number[] = Array(26).fill(0);
const n = s.length;
for (let i = 0; i < n; ++i) {
d[s.charCodeAt(i) - 97] = i;
}
let ans = 0;
for (let i = 0; i < n; ++i) {
ans += Math.abs(d[t.charCodeAt(i) - 97] - i);
}
return ans;
}
|
3,147 |
Taking Maximum Energy From the Mystic Dungeon
|
Medium
|
<p>In a mystic dungeon, <code>n</code> magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.</p>
<p>You have been cursed in such a way that after absorbing energy from magician <code>i</code>, you will be instantly transported to magician <code>(i + k)</code>. This process will be repeated until you reach the magician where <code>(i + k)</code> does not exist.</p>
<p>In other words, you will choose a starting point and then teleport with <code>k</code> jumps until you reach the end of the magicians' sequence, <strong>absorbing all the energy</strong> during the journey.</p>
<p>You are given an array <code>energy</code> and an integer <code>k</code>. Return the <strong>maximum</strong> possible energy you can gain.</p>
<p><strong>Note</strong> that when you are reach a magician, you <em>must</em> take energy from them, whether it is negative or positive energy.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [5,2,-10,-5,1], k = 3</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 3</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [-2,-3,-1], k = 2</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> -1</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of -1 by starting from magician 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= energy.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= energy[i] <= 1000</code></li>
<li><code>1 <= k <= energy.length - 1</code></li>
</ul>
<p> </p>
|
Array; Prefix Sum
|
C++
|
class Solution {
public:
int maximumEnergy(vector<int>& energy, int k) {
int ans = -(1 << 30);
int n = energy.size();
for (int i = n - k; i < n; ++i) {
for (int j = i, s = 0; j >= 0; j -= k) {
s += energy[j];
ans = max(ans, s);
}
}
return ans;
}
};
|
3,147 |
Taking Maximum Energy From the Mystic Dungeon
|
Medium
|
<p>In a mystic dungeon, <code>n</code> magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.</p>
<p>You have been cursed in such a way that after absorbing energy from magician <code>i</code>, you will be instantly transported to magician <code>(i + k)</code>. This process will be repeated until you reach the magician where <code>(i + k)</code> does not exist.</p>
<p>In other words, you will choose a starting point and then teleport with <code>k</code> jumps until you reach the end of the magicians' sequence, <strong>absorbing all the energy</strong> during the journey.</p>
<p>You are given an array <code>energy</code> and an integer <code>k</code>. Return the <strong>maximum</strong> possible energy you can gain.</p>
<p><strong>Note</strong> that when you are reach a magician, you <em>must</em> take energy from them, whether it is negative or positive energy.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [5,2,-10,-5,1], k = 3</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 3</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [-2,-3,-1], k = 2</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> -1</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of -1 by starting from magician 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= energy.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= energy[i] <= 1000</code></li>
<li><code>1 <= k <= energy.length - 1</code></li>
</ul>
<p> </p>
|
Array; Prefix Sum
|
Go
|
func maximumEnergy(energy []int, k int) int {
ans := -(1 << 30)
n := len(energy)
for i := n - k; i < n; i++ {
for j, s := i, 0; j >= 0; j -= k {
s += energy[j]
ans = max(ans, s)
}
}
return ans
}
|
3,147 |
Taking Maximum Energy From the Mystic Dungeon
|
Medium
|
<p>In a mystic dungeon, <code>n</code> magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.</p>
<p>You have been cursed in such a way that after absorbing energy from magician <code>i</code>, you will be instantly transported to magician <code>(i + k)</code>. This process will be repeated until you reach the magician where <code>(i + k)</code> does not exist.</p>
<p>In other words, you will choose a starting point and then teleport with <code>k</code> jumps until you reach the end of the magicians' sequence, <strong>absorbing all the energy</strong> during the journey.</p>
<p>You are given an array <code>energy</code> and an integer <code>k</code>. Return the <strong>maximum</strong> possible energy you can gain.</p>
<p><strong>Note</strong> that when you are reach a magician, you <em>must</em> take energy from them, whether it is negative or positive energy.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [5,2,-10,-5,1], k = 3</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 3</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [-2,-3,-1], k = 2</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> -1</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of -1 by starting from magician 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= energy.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= energy[i] <= 1000</code></li>
<li><code>1 <= k <= energy.length - 1</code></li>
</ul>
<p> </p>
|
Array; Prefix Sum
|
Java
|
class Solution {
public int maximumEnergy(int[] energy, int k) {
int ans = -(1 << 30);
int n = energy.length;
for (int i = n - k; i < n; ++i) {
for (int j = i, s = 0; j >= 0; j -= k) {
s += energy[j];
ans = Math.max(ans, s);
}
}
return ans;
}
}
|
3,147 |
Taking Maximum Energy From the Mystic Dungeon
|
Medium
|
<p>In a mystic dungeon, <code>n</code> magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.</p>
<p>You have been cursed in such a way that after absorbing energy from magician <code>i</code>, you will be instantly transported to magician <code>(i + k)</code>. This process will be repeated until you reach the magician where <code>(i + k)</code> does not exist.</p>
<p>In other words, you will choose a starting point and then teleport with <code>k</code> jumps until you reach the end of the magicians' sequence, <strong>absorbing all the energy</strong> during the journey.</p>
<p>You are given an array <code>energy</code> and an integer <code>k</code>. Return the <strong>maximum</strong> possible energy you can gain.</p>
<p><strong>Note</strong> that when you are reach a magician, you <em>must</em> take energy from them, whether it is negative or positive energy.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [5,2,-10,-5,1], k = 3</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 3</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [-2,-3,-1], k = 2</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> -1</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of -1 by starting from magician 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= energy.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= energy[i] <= 1000</code></li>
<li><code>1 <= k <= energy.length - 1</code></li>
</ul>
<p> </p>
|
Array; Prefix Sum
|
Python
|
class Solution:
def maximumEnergy(self, energy: List[int], k: int) -> int:
ans = -inf
n = len(energy)
for i in range(n - k, n):
j, s = i, 0
while j >= 0:
s += energy[j]
ans = max(ans, s)
j -= k
return ans
|
3,147 |
Taking Maximum Energy From the Mystic Dungeon
|
Medium
|
<p>In a mystic dungeon, <code>n</code> magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.</p>
<p>You have been cursed in such a way that after absorbing energy from magician <code>i</code>, you will be instantly transported to magician <code>(i + k)</code>. This process will be repeated until you reach the magician where <code>(i + k)</code> does not exist.</p>
<p>In other words, you will choose a starting point and then teleport with <code>k</code> jumps until you reach the end of the magicians' sequence, <strong>absorbing all the energy</strong> during the journey.</p>
<p>You are given an array <code>energy</code> and an integer <code>k</code>. Return the <strong>maximum</strong> possible energy you can gain.</p>
<p><strong>Note</strong> that when you are reach a magician, you <em>must</em> take energy from them, whether it is negative or positive energy.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [5,2,-10,-5,1], k = 3</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 3</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="
border-color: var(--border-tertiary);
border-left-width: 2px;
color: var(--text-secondary);
font-size: .875rem;
margin-bottom: 1rem;
margin-top: 1rem;
overflow: visible;
padding-left: 1rem;
">
<p><strong>Input:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> energy = [-2,-3,-1], k = 2</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> -1</span></p>
<p><strong>Explanation:</strong> We can gain a total energy of -1 by starting from magician 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= energy.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= energy[i] <= 1000</code></li>
<li><code>1 <= k <= energy.length - 1</code></li>
</ul>
<p> </p>
|
Array; Prefix Sum
|
TypeScript
|
function maximumEnergy(energy: number[], k: number): number {
const n = energy.length;
let ans = -Infinity;
for (let i = n - k; i < n; ++i) {
for (let j = i, s = 0; j >= 0; j -= k) {
s += energy[j];
ans = Math.max(ans, s);
}
}
return ans;
}
|
3,148 |
Maximum Difference Score in a Grid
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers. You can move from a cell in the matrix to <strong>any</strong> other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value <code>c1</code> to a cell with the value <code>c2</code> is <code>c2 - c1</code>.<!-- notionvc: 8819ca04-8606-4ecf-815b-fb77bc63b851 --></p>
<p>You can start at <strong>any</strong> cell, and you have to make <strong>at least</strong> one move.</p>
<p>Return the <strong>maximum</strong> total score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/grid1.png" style="width: 240px; height: 240px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 1)</code>, and we perform the following moves:<br />
- Move from the cell <code>(0, 1)</code> to <code>(2, 1)</code> with a score of <code>7 - 5 = 2</code>.<br />
- Move from the cell <code>(2, 1)</code> to <code>(2, 2)</code> with a score of <code>14 - 7 = 7</code>.<br />
The total score is <code>2 + 7 = 9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/moregridsdrawio-1.png" style="width: 180px; height: 116px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[4,3,2],[3,2,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 0)</code>, and we perform one move: <code>(0, 0)</code> to <code>(0, 1)</code>. The score is <code>3 - 4 = -1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= m, n <= 1000</code></li>
<li><code>4 <= m * n <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
C++
|
class Solution {
public:
int maxScore(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
const int inf = 1 << 30;
int ans = -inf;
int f[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int mi = inf;
if (i) {
mi = min(mi, f[i - 1][j]);
}
if (j) {
mi = min(mi, f[i][j - 1]);
}
ans = max(ans, grid[i][j] - mi);
f[i][j] = min(grid[i][j], mi);
}
}
return ans;
}
};
|
3,148 |
Maximum Difference Score in a Grid
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers. You can move from a cell in the matrix to <strong>any</strong> other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value <code>c1</code> to a cell with the value <code>c2</code> is <code>c2 - c1</code>.<!-- notionvc: 8819ca04-8606-4ecf-815b-fb77bc63b851 --></p>
<p>You can start at <strong>any</strong> cell, and you have to make <strong>at least</strong> one move.</p>
<p>Return the <strong>maximum</strong> total score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/grid1.png" style="width: 240px; height: 240px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 1)</code>, and we perform the following moves:<br />
- Move from the cell <code>(0, 1)</code> to <code>(2, 1)</code> with a score of <code>7 - 5 = 2</code>.<br />
- Move from the cell <code>(2, 1)</code> to <code>(2, 2)</code> with a score of <code>14 - 7 = 7</code>.<br />
The total score is <code>2 + 7 = 9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/moregridsdrawio-1.png" style="width: 180px; height: 116px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[4,3,2],[3,2,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 0)</code>, and we perform one move: <code>(0, 0)</code> to <code>(0, 1)</code>. The score is <code>3 - 4 = -1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= m, n <= 1000</code></li>
<li><code>4 <= m * n <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Go
|
func maxScore(grid [][]int) int {
m, n := len(grid), len(grid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
const inf int = 1 << 30
ans := -inf
for i, row := range grid {
for j, x := range row {
mi := inf
if i > 0 {
mi = min(mi, f[i-1][j])
}
if j > 0 {
mi = min(mi, f[i][j-1])
}
ans = max(ans, x-mi)
f[i][j] = min(x, mi)
}
}
return ans
}
|
3,148 |
Maximum Difference Score in a Grid
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers. You can move from a cell in the matrix to <strong>any</strong> other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value <code>c1</code> to a cell with the value <code>c2</code> is <code>c2 - c1</code>.<!-- notionvc: 8819ca04-8606-4ecf-815b-fb77bc63b851 --></p>
<p>You can start at <strong>any</strong> cell, and you have to make <strong>at least</strong> one move.</p>
<p>Return the <strong>maximum</strong> total score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/grid1.png" style="width: 240px; height: 240px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 1)</code>, and we perform the following moves:<br />
- Move from the cell <code>(0, 1)</code> to <code>(2, 1)</code> with a score of <code>7 - 5 = 2</code>.<br />
- Move from the cell <code>(2, 1)</code> to <code>(2, 2)</code> with a score of <code>14 - 7 = 7</code>.<br />
The total score is <code>2 + 7 = 9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/moregridsdrawio-1.png" style="width: 180px; height: 116px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[4,3,2],[3,2,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 0)</code>, and we perform one move: <code>(0, 0)</code> to <code>(0, 1)</code>. The score is <code>3 - 4 = -1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= m, n <= 1000</code></li>
<li><code>4 <= m * n <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Java
|
class Solution {
public int maxScore(List<List<Integer>> grid) {
int m = grid.size(), n = grid.get(0).size();
final int inf = 1 << 30;
int ans = -inf;
int[][] f = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int mi = inf;
if (i > 0) {
mi = Math.min(mi, f[i - 1][j]);
}
if (j > 0) {
mi = Math.min(mi, f[i][j - 1]);
}
ans = Math.max(ans, grid.get(i).get(j) - mi);
f[i][j] = Math.min(grid.get(i).get(j), mi);
}
}
return ans;
}
}
|
3,148 |
Maximum Difference Score in a Grid
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers. You can move from a cell in the matrix to <strong>any</strong> other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value <code>c1</code> to a cell with the value <code>c2</code> is <code>c2 - c1</code>.<!-- notionvc: 8819ca04-8606-4ecf-815b-fb77bc63b851 --></p>
<p>You can start at <strong>any</strong> cell, and you have to make <strong>at least</strong> one move.</p>
<p>Return the <strong>maximum</strong> total score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/grid1.png" style="width: 240px; height: 240px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 1)</code>, and we perform the following moves:<br />
- Move from the cell <code>(0, 1)</code> to <code>(2, 1)</code> with a score of <code>7 - 5 = 2</code>.<br />
- Move from the cell <code>(2, 1)</code> to <code>(2, 2)</code> with a score of <code>14 - 7 = 7</code>.<br />
The total score is <code>2 + 7 = 9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/moregridsdrawio-1.png" style="width: 180px; height: 116px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[4,3,2],[3,2,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 0)</code>, and we perform one move: <code>(0, 0)</code> to <code>(0, 1)</code>. The score is <code>3 - 4 = -1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= m, n <= 1000</code></li>
<li><code>4 <= m * n <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def maxScore(self, grid: List[List[int]]) -> int:
f = [[0] * len(grid[0]) for _ in range(len(grid))]
ans = -inf
for i, row in enumerate(grid):
for j, x in enumerate(row):
mi = inf
if i:
mi = min(mi, f[i - 1][j])
if j:
mi = min(mi, f[i][j - 1])
ans = max(ans, x - mi)
f[i][j] = min(x, mi)
return ans
|
3,148 |
Maximum Difference Score in a Grid
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers. You can move from a cell in the matrix to <strong>any</strong> other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value <code>c1</code> to a cell with the value <code>c2</code> is <code>c2 - c1</code>.<!-- notionvc: 8819ca04-8606-4ecf-815b-fb77bc63b851 --></p>
<p>You can start at <strong>any</strong> cell, and you have to make <strong>at least</strong> one move.</p>
<p>Return the <strong>maximum</strong> total score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/grid1.png" style="width: 240px; height: 240px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 1)</code>, and we perform the following moves:<br />
- Move from the cell <code>(0, 1)</code> to <code>(2, 1)</code> with a score of <code>7 - 5 = 2</code>.<br />
- Move from the cell <code>(2, 1)</code> to <code>(2, 2)</code> with a score of <code>14 - 7 = 7</code>.<br />
The total score is <code>2 + 7 = 9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3148.Maximum%20Difference%20Score%20in%20a%20Grid/images/moregridsdrawio-1.png" style="width: 180px; height: 116px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[4,3,2],[3,2,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> We start at the cell <code>(0, 0)</code>, and we perform one move: <code>(0, 0)</code> to <code>(0, 1)</code>. The score is <code>3 - 4 = -1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= m, n <= 1000</code></li>
<li><code>4 <= m * n <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming; Matrix
|
TypeScript
|
function maxScore(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
const f: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0));
let ans = -Infinity;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
let mi = Infinity;
if (i) {
mi = Math.min(mi, f[i - 1][j]);
}
if (j) {
mi = Math.min(mi, f[i][j - 1]);
}
ans = Math.max(ans, grid[i][j] - mi);
f[i][j] = Math.min(mi, grid[i][j]);
}
}
return ans;
}
|
3,149 |
Find the Minimum Cost Array Permutation
|
Hard
|
<p>You are given an array <code>nums</code> which is a <span data-keyword="permutation">permutation</span> of <code>[0, 1, 2, ..., n - 1]</code>. The <strong>score</strong> of any permutation of <code>[0, 1, 2, ..., n - 1]</code> named <code>perm</code> is defined as:</p>
<p><code>score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|</code></p>
<p>Return the permutation <code>perm</code> which has the <strong>minimum</strong> possible score. If <em>multiple</em> permutations exist with this score, return the one that is <span data-keyword="lexicographically-smaller-array">lexicographically smallest</span> among them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example0gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,1,2]</code>. The cost of this permutation is <code>|0 - 0| + |1 - 2| + |2 - 1| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example1gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,2,1]</code>. The cost of this permutation is <code>|0 - 1| + |2 - 2| + |1 - 0| = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 14</code></li>
<li><code>nums</code> is a permutation of <code>[0, 1, 2, ..., n - 1]</code>.</li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
C++
|
class Solution {
public:
vector<int> findPermutation(vector<int>& nums) {
int n = nums.size();
vector<int> ans;
int f[1 << n][n];
memset(f, -1, sizeof(f));
function<int(int, int)> dfs = [&](int mask, int pre) {
if (mask == (1 << n) - 1) {
return abs(pre - nums[0]);
}
int* res = &f[mask][pre];
if (*res != -1) {
return *res;
}
*res = INT_MAX;
for (int cur = 1; cur < n; ++cur) {
if (mask >> cur & 1 ^ 1) {
*res = min(*res, abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur));
}
}
return *res;
};
function<void(int, int)> g = [&](int mask, int pre) {
ans.push_back(pre);
if (mask == (1 << n) - 1) {
return;
}
int res = dfs(mask, pre);
for (int cur = 1; cur < n; ++cur) {
if (mask >> cur & 1 ^ 1) {
if (abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur) == res) {
g(mask | 1 << cur, cur);
break;
}
}
}
};
g(1, 0);
return ans;
}
};
|
3,149 |
Find the Minimum Cost Array Permutation
|
Hard
|
<p>You are given an array <code>nums</code> which is a <span data-keyword="permutation">permutation</span> of <code>[0, 1, 2, ..., n - 1]</code>. The <strong>score</strong> of any permutation of <code>[0, 1, 2, ..., n - 1]</code> named <code>perm</code> is defined as:</p>
<p><code>score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|</code></p>
<p>Return the permutation <code>perm</code> which has the <strong>minimum</strong> possible score. If <em>multiple</em> permutations exist with this score, return the one that is <span data-keyword="lexicographically-smaller-array">lexicographically smallest</span> among them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example0gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,1,2]</code>. The cost of this permutation is <code>|0 - 0| + |1 - 2| + |2 - 1| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example1gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,2,1]</code>. The cost of this permutation is <code>|0 - 1| + |2 - 2| + |1 - 0| = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 14</code></li>
<li><code>nums</code> is a permutation of <code>[0, 1, 2, ..., n - 1]</code>.</li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Go
|
func findPermutation(nums []int) (ans []int) {
n := len(nums)
f := make([][]int, 1<<n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(int, int) int
dfs = func(mask, pre int) int {
if mask == 1<<n-1 {
return abs(pre - nums[0])
}
if f[mask][pre] != -1 {
return f[mask][pre]
}
res := &f[mask][pre]
*res = math.MaxInt32
for cur := 1; cur < n; cur++ {
if mask>>cur&1 == 0 {
*res = min(*res, abs(pre-nums[cur])+dfs(mask|1<<cur, cur))
}
}
return *res
}
var g func(int, int)
g = func(mask, pre int) {
ans = append(ans, pre)
if mask == 1<<n-1 {
return
}
res := dfs(mask, pre)
for cur := 1; cur < n; cur++ {
if mask>>cur&1 == 0 {
if abs(pre-nums[cur])+dfs(mask|1<<cur, cur) == res {
g(mask|1<<cur, cur)
break
}
}
}
}
g(1, 0)
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,149 |
Find the Minimum Cost Array Permutation
|
Hard
|
<p>You are given an array <code>nums</code> which is a <span data-keyword="permutation">permutation</span> of <code>[0, 1, 2, ..., n - 1]</code>. The <strong>score</strong> of any permutation of <code>[0, 1, 2, ..., n - 1]</code> named <code>perm</code> is defined as:</p>
<p><code>score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|</code></p>
<p>Return the permutation <code>perm</code> which has the <strong>minimum</strong> possible score. If <em>multiple</em> permutations exist with this score, return the one that is <span data-keyword="lexicographically-smaller-array">lexicographically smallest</span> among them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example0gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,1,2]</code>. The cost of this permutation is <code>|0 - 0| + |1 - 2| + |2 - 1| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example1gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,2,1]</code>. The cost of this permutation is <code>|0 - 1| + |2 - 2| + |1 - 0| = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 14</code></li>
<li><code>nums</code> is a permutation of <code>[0, 1, 2, ..., n - 1]</code>.</li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Java
|
class Solution {
private Integer[][] f;
private int[] nums;
private int[] ans;
private int n;
public int[] findPermutation(int[] nums) {
n = nums.length;
ans = new int[n];
this.nums = nums;
f = new Integer[1 << n][n];
g(1, 0, 0);
return ans;
}
private int dfs(int mask, int pre) {
if (mask == (1 << n) - 1) {
return Math.abs(pre - nums[0]);
}
if (f[mask][pre] != null) {
return f[mask][pre];
}
int res = Integer.MAX_VALUE;
for (int cur = 1; cur < n; ++cur) {
if ((mask >> cur & 1) == 0) {
res = Math.min(res, Math.abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur));
}
}
return f[mask][pre] = res;
}
private void g(int mask, int pre, int k) {
ans[k] = pre;
if (mask == (1 << n) - 1) {
return;
}
int res = dfs(mask, pre);
for (int cur = 1; cur < n; ++cur) {
if ((mask >> cur & 1) == 0) {
if (Math.abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur) == res) {
g(mask | 1 << cur, cur, k + 1);
break;
}
}
}
}
}
|
3,149 |
Find the Minimum Cost Array Permutation
|
Hard
|
<p>You are given an array <code>nums</code> which is a <span data-keyword="permutation">permutation</span> of <code>[0, 1, 2, ..., n - 1]</code>. The <strong>score</strong> of any permutation of <code>[0, 1, 2, ..., n - 1]</code> named <code>perm</code> is defined as:</p>
<p><code>score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|</code></p>
<p>Return the permutation <code>perm</code> which has the <strong>minimum</strong> possible score. If <em>multiple</em> permutations exist with this score, return the one that is <span data-keyword="lexicographically-smaller-array">lexicographically smallest</span> among them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example0gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,1,2]</code>. The cost of this permutation is <code>|0 - 0| + |1 - 2| + |2 - 1| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example1gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,2,1]</code>. The cost of this permutation is <code>|0 - 1| + |2 - 2| + |1 - 0| = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 14</code></li>
<li><code>nums</code> is a permutation of <code>[0, 1, 2, ..., n - 1]</code>.</li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
Python
|
class Solution:
def findPermutation(self, nums: List[int]) -> List[int]:
@cache
def dfs(mask: int, pre: int) -> int:
if mask == (1 << n) - 1:
return abs(pre - nums[0])
res = inf
for cur in range(1, n):
if mask >> cur & 1 ^ 1:
res = min(res, abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur))
return res
def g(mask: int, pre: int):
ans.append(pre)
if mask == (1 << n) - 1:
return
res = dfs(mask, pre)
for cur in range(1, n):
if mask >> cur & 1 ^ 1:
if abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur) == res:
g(mask | 1 << cur, cur)
break
n = len(nums)
ans = []
g(1, 0)
return ans
|
3,149 |
Find the Minimum Cost Array Permutation
|
Hard
|
<p>You are given an array <code>nums</code> which is a <span data-keyword="permutation">permutation</span> of <code>[0, 1, 2, ..., n - 1]</code>. The <strong>score</strong> of any permutation of <code>[0, 1, 2, ..., n - 1]</code> named <code>perm</code> is defined as:</p>
<p><code>score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|</code></p>
<p>Return the permutation <code>perm</code> which has the <strong>minimum</strong> possible score. If <em>multiple</em> permutations exist with this score, return the one that is <span data-keyword="lexicographically-smaller-array">lexicographically smallest</span> among them.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example0gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,1,2]</code>. The cost of this permutation is <code>|0 - 0| + |1 - 2| + |2 - 1| = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3149.Find%20the%20Minimum%20Cost%20Array%20Permutation/images/example1gif.gif" style="width: 235px; height: 235px;" /></strong></p>
<p>The lexicographically smallest permutation with minimum cost is <code>[0,2,1]</code>. The cost of this permutation is <code>|0 - 1| + |2 - 2| + |1 - 0| = 2</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 14</code></li>
<li><code>nums</code> is a permutation of <code>[0, 1, 2, ..., n - 1]</code>.</li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Bitmask
|
TypeScript
|
function findPermutation(nums: number[]): number[] {
const n = nums.length;
const ans: number[] = [];
const f: number[][] = Array.from({ length: 1 << n }, () => Array(n).fill(-1));
const dfs = (mask: number, pre: number): number => {
if (mask === (1 << n) - 1) {
return Math.abs(pre - nums[0]);
}
if (f[mask][pre] !== -1) {
return f[mask][pre];
}
let res = Infinity;
for (let cur = 1; cur < n; ++cur) {
if (((mask >> cur) & 1) ^ 1) {
res = Math.min(res, Math.abs(pre - nums[cur]) + dfs(mask | (1 << cur), cur));
}
}
return (f[mask][pre] = res);
};
const g = (mask: number, pre: number) => {
ans.push(pre);
if (mask === (1 << n) - 1) {
return;
}
const res = dfs(mask, pre);
for (let cur = 1; cur < n; ++cur) {
if (((mask >> cur) & 1) ^ 1) {
if (Math.abs(pre - nums[cur]) + dfs(mask | (1 << cur), cur) === res) {
g(mask | (1 << cur), cur);
break;
}
}
}
};
g(1, 0);
return ans;
}
|
3,150 |
Invalid Tweets II
|
Easy
|
<p>Table: <code>Tweets</code></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.
</pre>
<p>Write a solution to find <strong>invalid tweets</strong>. A tweet is considered invalid if it meets <strong>any</strong> of the following criteria:</p>
<ul>
<li>It exceeds <code>140</code> characters in length.</li>
<li>It has more than <code>3</code> mentions.</li>
<li>It includes more than <code><font face="monospace">3</font></code> hashtags.</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>tweet_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tweets table:</p>
<pre class="example-io">
+----------+-----------------------------------------------------------------------------------+
| tweet_id | content |
+----------+-----------------------------------------------------------------------------------+
| 1 | Traveling, exploring, and living my best life @JaneSmith @SaraJohnson @LisaTaylor |
| | @MikeBrown #Foodie #Fitness #Learning |
| 2 | Just had the best dinner with friends! #Foodie #Friends #Fun |
| 4 | Working hard on my new project #Work #Goals #Productivity #Fun |
+----------+-----------------------------------------------------------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+----------+
| tweet_id |
+----------+
| 1 |
| 4 |
+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>tweet_id 1 contains 4 mentions.</li>
<li>tweet_id 4 contains 4 hashtags.</li>
</ul>
Output table is ordered by tweet_id in ascending order.</div>
|
Database
|
Python
|
import pandas as pd
def find_invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:
invalid_tweets = tweets[
(tweets["content"].str.len() > 140)
| (tweets["content"].str.count("@") > 3)
| (tweets["content"].str.count("#") > 3)
].sort_values(by="tweet_id")
return invalid_tweets[["tweet_id"]]
|
3,150 |
Invalid Tweets II
|
Easy
|
<p>Table: <code>Tweets</code></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| tweet_id | int |
| content | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.
</pre>
<p>Write a solution to find <strong>invalid tweets</strong>. A tweet is considered invalid if it meets <strong>any</strong> of the following criteria:</p>
<ul>
<li>It exceeds <code>140</code> characters in length.</li>
<li>It has more than <code>3</code> mentions.</li>
<li>It includes more than <code><font face="monospace">3</font></code> hashtags.</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>tweet_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tweets table:</p>
<pre class="example-io">
+----------+-----------------------------------------------------------------------------------+
| tweet_id | content |
+----------+-----------------------------------------------------------------------------------+
| 1 | Traveling, exploring, and living my best life @JaneSmith @SaraJohnson @LisaTaylor |
| | @MikeBrown #Foodie #Fitness #Learning |
| 2 | Just had the best dinner with friends! #Foodie #Friends #Fun |
| 4 | Working hard on my new project #Work #Goals #Productivity #Fun |
+----------+-----------------------------------------------------------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+----------+
| tweet_id |
+----------+
| 1 |
| 4 |
+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>tweet_id 1 contains 4 mentions.</li>
<li>tweet_id 4 contains 4 hashtags.</li>
</ul>
Output table is ordered by tweet_id in ascending order.</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT tweet_id
FROM Tweets
WHERE LENGTH(content) > 140
OR (LENGTH(content) - LENGTH(REPLACE(content, '@', ''))) > 3
OR (LENGTH(content) - LENGTH(REPLACE(content, '#', ''))) > 3
ORDER BY 1;
|
3,151 |
Special Array I
|
Easy
|
<p>An array is considered <strong>special</strong> if the <em>parity</em> of every pair of adjacent elements is different. In other words, one element in each pair <strong>must</strong> be even, and the other <strong>must</strong> be odd.</p>
<p>You are given an array of integers <code>nums</code>. Return <code>true</code> if <code>nums</code> is a <strong>special</strong> array, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one element. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only two pairs: <code>(2,1)</code> and <code>(1,4)</code>, and both of them contain numbers with different parity. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums[1]</code> and <code>nums[2]</code> are both odd. So the answer is <code>false</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
bool isArraySpecial(vector<int>& nums) {
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] % 2 == nums[i - 1] % 2) {
return false;
}
}
return true;
}
};
|
3,151 |
Special Array I
|
Easy
|
<p>An array is considered <strong>special</strong> if the <em>parity</em> of every pair of adjacent elements is different. In other words, one element in each pair <strong>must</strong> be even, and the other <strong>must</strong> be odd.</p>
<p>You are given an array of integers <code>nums</code>. Return <code>true</code> if <code>nums</code> is a <strong>special</strong> array, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one element. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only two pairs: <code>(2,1)</code> and <code>(1,4)</code>, and both of them contain numbers with different parity. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums[1]</code> and <code>nums[2]</code> are both odd. So the answer is <code>false</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array
|
Go
|
func isArraySpecial(nums []int) bool {
for i, x := range nums[1:] {
if x%2 == nums[i]%2 {
return false
}
}
return true
}
|
3,151 |
Special Array I
|
Easy
|
<p>An array is considered <strong>special</strong> if the <em>parity</em> of every pair of adjacent elements is different. In other words, one element in each pair <strong>must</strong> be even, and the other <strong>must</strong> be odd.</p>
<p>You are given an array of integers <code>nums</code>. Return <code>true</code> if <code>nums</code> is a <strong>special</strong> array, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one element. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only two pairs: <code>(2,1)</code> and <code>(1,4)</code>, and both of them contain numbers with different parity. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums[1]</code> and <code>nums[2]</code> are both odd. So the answer is <code>false</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array
|
Java
|
class Solution {
public boolean isArraySpecial(int[] nums) {
for (int i = 1; i < nums.length; ++i) {
if (nums[i] % 2 == nums[i - 1] % 2) {
return false;
}
}
return true;
}
}
|
3,151 |
Special Array I
|
Easy
|
<p>An array is considered <strong>special</strong> if the <em>parity</em> of every pair of adjacent elements is different. In other words, one element in each pair <strong>must</strong> be even, and the other <strong>must</strong> be odd.</p>
<p>You are given an array of integers <code>nums</code>. Return <code>true</code> if <code>nums</code> is a <strong>special</strong> array, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one element. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only two pairs: <code>(2,1)</code> and <code>(1,4)</code>, and both of them contain numbers with different parity. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums[1]</code> and <code>nums[2]</code> are both odd. So the answer is <code>false</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array
|
Python
|
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
return all(a % 2 != b % 2 for a, b in pairwise(nums))
|
3,151 |
Special Array I
|
Easy
|
<p>An array is considered <strong>special</strong> if the <em>parity</em> of every pair of adjacent elements is different. In other words, one element in each pair <strong>must</strong> be even, and the other <strong>must</strong> be odd.</p>
<p>You are given an array of integers <code>nums</code>. Return <code>true</code> if <code>nums</code> is a <strong>special</strong> array, otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one element. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only two pairs: <code>(2,1)</code> and <code>(1,4)</code>, and both of them contain numbers with different parity. So the answer is <code>true</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums[1]</code> and <code>nums[2]</code> are both odd. So the answer is <code>false</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array
|
TypeScript
|
function isArraySpecial(nums: number[]): boolean {
for (let i = 1; i < nums.length; ++i) {
if (nums[i] % 2 === nums[i - 1] % 2) {
return false;
}
}
return true;
}
|
3,152 |
Special Array II
|
Medium
|
<p>An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity.</p>
<p>You are given an array of integer <code>nums</code> and a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> your task is to check that <span data-keyword="subarray">subarray</span> <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is <strong>special</strong> or not.</p>
<p>Return an array of booleans <code>answer</code> such that <code>answer[i]</code> is <code>true</code> if <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is special.<!-- notionvc: e5d6f4e2-d20a-4fbd-9c7f-22fbe52ef730 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,1,2,6], queries = [[0,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false]</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray is <code>[3,4,1,2,6]</code>. 2 and 6 are both even.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6], queries = [[0,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,true]</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>The subarray is <code>[4,3,1]</code>. 3 and 1 are both odd. So the answer to this query is <code>false</code>.</li>
<li>The subarray is <code>[1,6]</code>. There is only one pair: <code>(1,6)</code> and it contains numbers with different parity. So the answer to this query is <code>true</code>.</li>
</ol>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= nums.length - 1</code></li>
</ul>
|
Array; Binary Search; Prefix Sum
|
C++
|
class Solution {
public:
vector<bool> isArraySpecial(vector<int>& nums, vector<vector<int>>& queries) {
int n = nums.size();
vector<int> d(n);
iota(d.begin(), d.end(), 0);
for (int i = 1; i < n; ++i) {
if (nums[i] % 2 != nums[i - 1] % 2) {
d[i] = d[i - 1];
}
}
vector<bool> ans;
for (auto& q : queries) {
ans.push_back(d[q[1]] <= q[0]);
}
return ans;
}
};
|
3,152 |
Special Array II
|
Medium
|
<p>An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity.</p>
<p>You are given an array of integer <code>nums</code> and a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> your task is to check that <span data-keyword="subarray">subarray</span> <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is <strong>special</strong> or not.</p>
<p>Return an array of booleans <code>answer</code> such that <code>answer[i]</code> is <code>true</code> if <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is special.<!-- notionvc: e5d6f4e2-d20a-4fbd-9c7f-22fbe52ef730 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,1,2,6], queries = [[0,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false]</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray is <code>[3,4,1,2,6]</code>. 2 and 6 are both even.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6], queries = [[0,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,true]</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>The subarray is <code>[4,3,1]</code>. 3 and 1 are both odd. So the answer to this query is <code>false</code>.</li>
<li>The subarray is <code>[1,6]</code>. There is only one pair: <code>(1,6)</code> and it contains numbers with different parity. So the answer to this query is <code>true</code>.</li>
</ol>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= nums.length - 1</code></li>
</ul>
|
Array; Binary Search; Prefix Sum
|
Go
|
func isArraySpecial(nums []int, queries [][]int) (ans []bool) {
n := len(nums)
d := make([]int, n)
for i := range d {
d[i] = i
}
for i := 1; i < len(nums); i++ {
if nums[i]%2 != nums[i-1]%2 {
d[i] = d[i-1]
}
}
for _, q := range queries {
ans = append(ans, d[q[1]] <= q[0])
}
return
}
|
3,152 |
Special Array II
|
Medium
|
<p>An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity.</p>
<p>You are given an array of integer <code>nums</code> and a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> your task is to check that <span data-keyword="subarray">subarray</span> <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is <strong>special</strong> or not.</p>
<p>Return an array of booleans <code>answer</code> such that <code>answer[i]</code> is <code>true</code> if <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is special.<!-- notionvc: e5d6f4e2-d20a-4fbd-9c7f-22fbe52ef730 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,1,2,6], queries = [[0,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false]</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray is <code>[3,4,1,2,6]</code>. 2 and 6 are both even.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6], queries = [[0,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,true]</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>The subarray is <code>[4,3,1]</code>. 3 and 1 are both odd. So the answer to this query is <code>false</code>.</li>
<li>The subarray is <code>[1,6]</code>. There is only one pair: <code>(1,6)</code> and it contains numbers with different parity. So the answer to this query is <code>true</code>.</li>
</ol>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= nums.length - 1</code></li>
</ul>
|
Array; Binary Search; Prefix Sum
|
Java
|
class Solution {
public boolean[] isArraySpecial(int[] nums, int[][] queries) {
int n = nums.length;
int[] d = new int[n];
for (int i = 1; i < n; ++i) {
if (nums[i] % 2 != nums[i - 1] % 2) {
d[i] = d[i - 1];
} else {
d[i] = i;
}
}
int m = queries.length;
boolean[] ans = new boolean[m];
for (int i = 0; i < m; ++i) {
ans[i] = d[queries[i][1]] <= queries[i][0];
}
return ans;
}
}
|
3,152 |
Special Array II
|
Medium
|
<p>An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity.</p>
<p>You are given an array of integer <code>nums</code> and a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> your task is to check that <span data-keyword="subarray">subarray</span> <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is <strong>special</strong> or not.</p>
<p>Return an array of booleans <code>answer</code> such that <code>answer[i]</code> is <code>true</code> if <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is special.<!-- notionvc: e5d6f4e2-d20a-4fbd-9c7f-22fbe52ef730 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,1,2,6], queries = [[0,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false]</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray is <code>[3,4,1,2,6]</code>. 2 and 6 are both even.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6], queries = [[0,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,true]</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>The subarray is <code>[4,3,1]</code>. 3 and 1 are both odd. So the answer to this query is <code>false</code>.</li>
<li>The subarray is <code>[1,6]</code>. There is only one pair: <code>(1,6)</code> and it contains numbers with different parity. So the answer to this query is <code>true</code>.</li>
</ol>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= nums.length - 1</code></li>
</ul>
|
Array; Binary Search; Prefix Sum
|
Python
|
class Solution:
def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]:
n = len(nums)
d = list(range(n))
for i in range(1, n):
if nums[i] % 2 != nums[i - 1] % 2:
d[i] = d[i - 1]
return [d[t] <= f for f, t in queries]
|
3,152 |
Special Array II
|
Medium
|
<p>An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity.</p>
<p>You are given an array of integer <code>nums</code> and a 2D integer matrix <code>queries</code>, where for <code>queries[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> your task is to check that <span data-keyword="subarray">subarray</span> <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is <strong>special</strong> or not.</p>
<p>Return an array of booleans <code>answer</code> such that <code>answer[i]</code> is <code>true</code> if <code>nums[from<sub>i</sub>..to<sub>i</sub>]</code> is special.<!-- notionvc: e5d6f4e2-d20a-4fbd-9c7f-22fbe52ef730 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,1,2,6], queries = [[0,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false]</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray is <code>[3,4,1,2,6]</code>. 2 and 6 are both even.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,6], queries = [[0,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,true]</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>The subarray is <code>[4,3,1]</code>. 3 and 1 are both odd. So the answer to this query is <code>false</code>.</li>
<li>The subarray is <code>[1,6]</code>. There is only one pair: <code>(1,6)</code> and it contains numbers with different parity. So the answer to this query is <code>true</code>.</li>
</ol>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= queries[i][0] <= queries[i][1] <= nums.length - 1</code></li>
</ul>
|
Array; Binary Search; Prefix Sum
|
TypeScript
|
function isArraySpecial(nums: number[], queries: number[][]): boolean[] {
const n = nums.length;
const d: number[] = Array.from({ length: n }, (_, i) => i);
for (let i = 1; i < n; ++i) {
if (nums[i] % 2 !== nums[i - 1] % 2) {
d[i] = d[i - 1];
}
}
return queries.map(([from, to]) => d[to] <= from);
}
|
3,153 |
Sum of Digit Differences of All Pairs
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers where all integers have the <strong>same</strong> number of digits.</p>
<p>The <strong>digit difference</strong> between two integers is the <em>count</em> of different digits that are in the <strong>same</strong> position in the two integers.</p>
<p>Return the <strong>sum</strong> of the <strong>digit differences</strong> between <strong>all</strong> pairs of integers in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [13,23,12]</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong><br />
We have the following:<br />
- The digit difference between <strong>1</strong>3 and <strong>2</strong>3 is 1.<br />
- The digit difference between 1<strong>3</strong> and 1<strong>2</strong> is 1.<br />
- The digit difference between <strong>23</strong> and <strong>12</strong> is 2.<br />
So the total sum of digit differences between all pairs of integers is <code>1 + 1 + 2 = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.</p>
</div>
<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>
<li>All integers in <code>nums</code> have the same number of digits.</li>
</ul>
|
Array; Hash Table; Math; Counting
|
C++
|
class Solution {
public:
long long sumDigitDifferences(vector<int>& nums) {
int n = nums.size();
int m = floor(log10(nums[0])) + 1;
int cnt[10];
long long ans = 0;
for (int k = 0; k < m; ++k) {
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i < n; ++i) {
++cnt[nums[i] % 10];
nums[i] /= 10;
}
for (int i = 0; i < 10; ++i) {
ans += 1LL * cnt[i] * (n - cnt[i]);
}
}
return ans / 2;
}
};
|
3,153 |
Sum of Digit Differences of All Pairs
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers where all integers have the <strong>same</strong> number of digits.</p>
<p>The <strong>digit difference</strong> between two integers is the <em>count</em> of different digits that are in the <strong>same</strong> position in the two integers.</p>
<p>Return the <strong>sum</strong> of the <strong>digit differences</strong> between <strong>all</strong> pairs of integers in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [13,23,12]</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong><br />
We have the following:<br />
- The digit difference between <strong>1</strong>3 and <strong>2</strong>3 is 1.<br />
- The digit difference between 1<strong>3</strong> and 1<strong>2</strong> is 1.<br />
- The digit difference between <strong>23</strong> and <strong>12</strong> is 2.<br />
So the total sum of digit differences between all pairs of integers is <code>1 + 1 + 2 = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.</p>
</div>
<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>
<li>All integers in <code>nums</code> have the same number of digits.</li>
</ul>
|
Array; Hash Table; Math; Counting
|
Go
|
func sumDigitDifferences(nums []int) (ans int64) {
n := len(nums)
m := int(math.Floor(math.Log10(float64(nums[0])))) + 1
for k := 0; k < m; k++ {
cnt := [10]int{}
for i, x := range nums {
cnt[x%10]++
nums[i] /= 10
}
for _, v := range cnt {
ans += int64(v) * int64(n-v)
}
}
ans /= 2
return
}
|
3,153 |
Sum of Digit Differences of All Pairs
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers where all integers have the <strong>same</strong> number of digits.</p>
<p>The <strong>digit difference</strong> between two integers is the <em>count</em> of different digits that are in the <strong>same</strong> position in the two integers.</p>
<p>Return the <strong>sum</strong> of the <strong>digit differences</strong> between <strong>all</strong> pairs of integers in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [13,23,12]</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong><br />
We have the following:<br />
- The digit difference between <strong>1</strong>3 and <strong>2</strong>3 is 1.<br />
- The digit difference between 1<strong>3</strong> and 1<strong>2</strong> is 1.<br />
- The digit difference between <strong>23</strong> and <strong>12</strong> is 2.<br />
So the total sum of digit differences between all pairs of integers is <code>1 + 1 + 2 = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.</p>
</div>
<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>
<li>All integers in <code>nums</code> have the same number of digits.</li>
</ul>
|
Array; Hash Table; Math; Counting
|
Java
|
class Solution {
public long sumDigitDifferences(int[] nums) {
int n = nums.length;
int m = (int) Math.floor(Math.log10(nums[0])) + 1;
int[] cnt = new int[10];
long ans = 0;
for (int k = 0; k < m; ++k) {
Arrays.fill(cnt, 0);
for (int i = 0; i < n; ++i) {
++cnt[nums[i] % 10];
nums[i] /= 10;
}
for (int i = 0; i < 10; ++i) {
ans += 1L * cnt[i] * (n - cnt[i]);
}
}
return ans / 2;
}
}
|
3,153 |
Sum of Digit Differences of All Pairs
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers where all integers have the <strong>same</strong> number of digits.</p>
<p>The <strong>digit difference</strong> between two integers is the <em>count</em> of different digits that are in the <strong>same</strong> position in the two integers.</p>
<p>Return the <strong>sum</strong> of the <strong>digit differences</strong> between <strong>all</strong> pairs of integers in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [13,23,12]</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong><br />
We have the following:<br />
- The digit difference between <strong>1</strong>3 and <strong>2</strong>3 is 1.<br />
- The digit difference between 1<strong>3</strong> and 1<strong>2</strong> is 1.<br />
- The digit difference between <strong>23</strong> and <strong>12</strong> is 2.<br />
So the total sum of digit differences between all pairs of integers is <code>1 + 1 + 2 = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.</p>
</div>
<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>
<li>All integers in <code>nums</code> have the same number of digits.</li>
</ul>
|
Array; Hash Table; Math; Counting
|
Python
|
class Solution:
def sumDigitDifferences(self, nums: List[int]) -> int:
n = len(nums)
m = int(log10(nums[0])) + 1
ans = 0
for _ in range(m):
cnt = Counter()
for i, x in enumerate(nums):
nums[i], y = divmod(x, 10)
cnt[y] += 1
ans += sum(v * (n - v) for v in cnt.values()) // 2
return ans
|
3,153 |
Sum of Digit Differences of All Pairs
|
Medium
|
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers where all integers have the <strong>same</strong> number of digits.</p>
<p>The <strong>digit difference</strong> between two integers is the <em>count</em> of different digits that are in the <strong>same</strong> position in the two integers.</p>
<p>Return the <strong>sum</strong> of the <strong>digit differences</strong> between <strong>all</strong> pairs of integers in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [13,23,12]</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong><br />
We have the following:<br />
- The digit difference between <strong>1</strong>3 and <strong>2</strong>3 is 1.<br />
- The digit difference between 1<strong>3</strong> and 1<strong>2</strong> is 1.<br />
- The digit difference between <strong>23</strong> and <strong>12</strong> is 2.<br />
So the total sum of digit differences between all pairs of integers is <code>1 + 1 + 2 = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.</p>
</div>
<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>
<li>All integers in <code>nums</code> have the same number of digits.</li>
</ul>
|
Array; Hash Table; Math; Counting
|
TypeScript
|
function sumDigitDifferences(nums: number[]): number {
const n = nums.length;
const m = Math.floor(Math.log10(nums[0])) + 1;
let ans: bigint = BigInt(0);
for (let k = 0; k < m; ++k) {
const cnt: number[] = Array(10).fill(0);
for (let i = 0; i < n; ++i) {
++cnt[nums[i] % 10];
nums[i] = Math.floor(nums[i] / 10);
}
for (let i = 0; i < 10; ++i) {
ans += BigInt(cnt[i]) * BigInt(n - cnt[i]);
}
}
ans /= BigInt(2);
return Number(ans);
}
|
3,154 |
Find Number of Ways to Reach the K-th Stair
|
Hard
|
<p>You are given a <strong>non-negative</strong> integer <code>k</code>. There exists a staircase with an infinite number of stairs, with the <strong>lowest</strong> stair numbered 0.</p>
<p>Alice has an integer <code>jump</code>, with an initial value of 0. She starts on stair 1 and wants to reach stair <code>k</code> using <strong>any</strong> number of <strong>operations</strong>. If she is on stair <code>i</code>, in one <strong>operation</strong> she can:</p>
<ul>
<li>Go down to stair <code>i - 1</code>. This operation <strong>cannot</strong> be used consecutively or on stair 0.</li>
<li>Go up to stair <code>i + 2<sup>jump</sup></code>. And then, <code>jump</code> becomes <code>jump + 1</code>.</li>
</ul>
<p>Return the <em>total</em> number of ways Alice can reach stair <code>k</code>.</p>
<p><strong>Note</strong> that it is possible that Alice reaches the stair <code>k</code>, and performs some operations to reach the stair <code>k</code> again.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 possible ways of reaching stair 0 are:</p>
<ul>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The 4 possible ways of reaching stair 1 are:</p>
<ul>
<li>Alice starts at stair 1. Alice is at stair 1.</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>1</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Combinatorics
|
C++
|
class Solution {
public:
int waysToReachStair(int k) {
unordered_map<long long, int> f;
auto dfs = [&](this auto&& dfs, int i, int j, int jump) -> int {
if (i > k + 1) {
return 0;
}
long long key = ((long long) i << 32) | jump << 1 | j;
if (f.contains(key)) {
return f[key];
}
int ans = i == k ? 1 : 0;
if (i > 0 && j == 0) {
ans += dfs(i - 1, 1, jump);
}
ans += dfs(i + (1 << jump), 0, jump + 1);
f[key] = ans;
return ans;
};
return dfs(1, 0, 0);
}
};
|
3,154 |
Find Number of Ways to Reach the K-th Stair
|
Hard
|
<p>You are given a <strong>non-negative</strong> integer <code>k</code>. There exists a staircase with an infinite number of stairs, with the <strong>lowest</strong> stair numbered 0.</p>
<p>Alice has an integer <code>jump</code>, with an initial value of 0. She starts on stair 1 and wants to reach stair <code>k</code> using <strong>any</strong> number of <strong>operations</strong>. If she is on stair <code>i</code>, in one <strong>operation</strong> she can:</p>
<ul>
<li>Go down to stair <code>i - 1</code>. This operation <strong>cannot</strong> be used consecutively or on stair 0.</li>
<li>Go up to stair <code>i + 2<sup>jump</sup></code>. And then, <code>jump</code> becomes <code>jump + 1</code>.</li>
</ul>
<p>Return the <em>total</em> number of ways Alice can reach stair <code>k</code>.</p>
<p><strong>Note</strong> that it is possible that Alice reaches the stair <code>k</code>, and performs some operations to reach the stair <code>k</code> again.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 possible ways of reaching stair 0 are:</p>
<ul>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The 4 possible ways of reaching stair 1 are:</p>
<ul>
<li>Alice starts at stair 1. Alice is at stair 1.</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>1</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Combinatorics
|
Go
|
func waysToReachStair(k int) int {
f := map[int]int{}
var dfs func(i, j, jump int) int
dfs = func(i, j, jump int) int {
if i > k+1 {
return 0
}
key := (i << 32) | jump<<1 | j
if v, has := f[key]; has {
return v
}
ans := 0
if i == k {
ans++
}
if i > 0 && j == 0 {
ans += dfs(i-1, 1, jump)
}
ans += dfs(i+(1<<jump), 0, jump+1)
f[key] = ans
return ans
}
return dfs(1, 0, 0)
}
|
3,154 |
Find Number of Ways to Reach the K-th Stair
|
Hard
|
<p>You are given a <strong>non-negative</strong> integer <code>k</code>. There exists a staircase with an infinite number of stairs, with the <strong>lowest</strong> stair numbered 0.</p>
<p>Alice has an integer <code>jump</code>, with an initial value of 0. She starts on stair 1 and wants to reach stair <code>k</code> using <strong>any</strong> number of <strong>operations</strong>. If she is on stair <code>i</code>, in one <strong>operation</strong> she can:</p>
<ul>
<li>Go down to stair <code>i - 1</code>. This operation <strong>cannot</strong> be used consecutively or on stair 0.</li>
<li>Go up to stair <code>i + 2<sup>jump</sup></code>. And then, <code>jump</code> becomes <code>jump + 1</code>.</li>
</ul>
<p>Return the <em>total</em> number of ways Alice can reach stair <code>k</code>.</p>
<p><strong>Note</strong> that it is possible that Alice reaches the stair <code>k</code>, and performs some operations to reach the stair <code>k</code> again.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 possible ways of reaching stair 0 are:</p>
<ul>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The 4 possible ways of reaching stair 1 are:</p>
<ul>
<li>Alice starts at stair 1. Alice is at stair 1.</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>1</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Combinatorics
|
Java
|
class Solution {
private Map<Long, Integer> f = new HashMap<>();
private int k;
public int waysToReachStair(int k) {
this.k = k;
return dfs(1, 0, 0);
}
private int dfs(int i, int j, int jump) {
if (i > k + 1) {
return 0;
}
long key = ((long) i << 32) | jump << 1 | j;
if (f.containsKey(key)) {
return f.get(key);
}
int ans = i == k ? 1 : 0;
if (i > 0 && j == 0) {
ans += dfs(i - 1, 1, jump);
}
ans += dfs(i + (1 << jump), 0, jump + 1);
f.put(key, ans);
return ans;
}
}
|
3,154 |
Find Number of Ways to Reach the K-th Stair
|
Hard
|
<p>You are given a <strong>non-negative</strong> integer <code>k</code>. There exists a staircase with an infinite number of stairs, with the <strong>lowest</strong> stair numbered 0.</p>
<p>Alice has an integer <code>jump</code>, with an initial value of 0. She starts on stair 1 and wants to reach stair <code>k</code> using <strong>any</strong> number of <strong>operations</strong>. If she is on stair <code>i</code>, in one <strong>operation</strong> she can:</p>
<ul>
<li>Go down to stair <code>i - 1</code>. This operation <strong>cannot</strong> be used consecutively or on stair 0.</li>
<li>Go up to stair <code>i + 2<sup>jump</sup></code>. And then, <code>jump</code> becomes <code>jump + 1</code>.</li>
</ul>
<p>Return the <em>total</em> number of ways Alice can reach stair <code>k</code>.</p>
<p><strong>Note</strong> that it is possible that Alice reaches the stair <code>k</code>, and performs some operations to reach the stair <code>k</code> again.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 possible ways of reaching stair 0 are:</p>
<ul>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The 4 possible ways of reaching stair 1 are:</p>
<ul>
<li>Alice starts at stair 1. Alice is at stair 1.</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>1</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def waysToReachStair(self, k: int) -> int:
@cache
def dfs(i: int, j: int, jump: int) -> int:
if i > k + 1:
return 0
ans = int(i == k)
if i > 0 and j == 0:
ans += dfs(i - 1, 1, jump)
ans += dfs(i + (1 << jump), 0, jump + 1)
return ans
return dfs(1, 0, 0)
|
3,154 |
Find Number of Ways to Reach the K-th Stair
|
Hard
|
<p>You are given a <strong>non-negative</strong> integer <code>k</code>. There exists a staircase with an infinite number of stairs, with the <strong>lowest</strong> stair numbered 0.</p>
<p>Alice has an integer <code>jump</code>, with an initial value of 0. She starts on stair 1 and wants to reach stair <code>k</code> using <strong>any</strong> number of <strong>operations</strong>. If she is on stair <code>i</code>, in one <strong>operation</strong> she can:</p>
<ul>
<li>Go down to stair <code>i - 1</code>. This operation <strong>cannot</strong> be used consecutively or on stair 0.</li>
<li>Go up to stair <code>i + 2<sup>jump</sup></code>. And then, <code>jump</code> becomes <code>jump + 1</code>.</li>
</ul>
<p>Return the <em>total</em> number of ways Alice can reach stair <code>k</code>.</p>
<p><strong>Note</strong> that it is possible that Alice reaches the stair <code>k</code>, and performs some operations to reach the stair <code>k</code> again.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The 2 possible ways of reaching stair 0 are:</p>
<ul>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The 4 possible ways of reaching stair 1 are:</p>
<ul>
<li>Alice starts at stair 1. Alice is at stair 1.</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
<li>Alice starts at stair 1.
<ul>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>0</sup> stairs to reach stair 1.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 0.</li>
<li>Using an operation of the second type, she goes up 2<sup>1</sup> stairs to reach stair 2.</li>
<li>Using an operation of the first type, she goes down 1 stair to reach stair 1.</li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Combinatorics
|
TypeScript
|
function waysToReachStair(k: number): number {
const f: Map<bigint, number> = new Map();
const dfs = (i: number, j: number, jump: number): number => {
if (i > k + 1) {
return 0;
}
const key: bigint = (BigInt(i) << BigInt(32)) | BigInt(jump << 1) | BigInt(j);
if (f.has(key)) {
return f.get(key)!;
}
let ans: number = 0;
if (i === k) {
ans++;
}
if (i > 0 && j === 0) {
ans += dfs(i - 1, 1, jump);
}
ans += dfs(i + (1 << jump), 0, jump + 1);
f.set(key, ans);
return ans;
};
return dfs(1, 0, 0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.