id
int64
1
3.64k
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,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 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 = [1,2,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumLength(self, nums: List[int]) -> int: k = 2 f = [[0] * k for _ in range(k)] ans = 0 for x in nums: x %= k for j in range(k): y = (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) return ans
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 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 = [1,2,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_length(nums: Vec<i32>) -> i32 { let mut f = [[0; 2]; 2]; let mut ans = 0; for x in nums { let x = (x % 2) as usize; for j in 0..2 { let y = ((j + 2 - x) % 2) as usize; f[x][y] = f[y][x] + 1; ans = ans.max(f[x][y]); } } ans } }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 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 = [1,2,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumLength(nums: number[]): number { const k = 2; const f: number[][] = Array.from({ length: k }, () => Array(k).fill(0)); let ans: number = 0; for (let x of nums) { x %= k; for (let j = 0; j < k; ++j) { const y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maximumLength(vector<int>& nums, int k) { int f[k][k]; memset(f, 0, sizeof(f)); int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = max(ans, f[x][y]); } } return ans; } };
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public int MaximumLength(int[] nums, int k) { int[,] f = new int[k, k]; int ans = 0; foreach (int num in nums) { int x = num % k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x, y] = f[y, x] + 1; ans = Math.Max(ans, f[x, y]); } } return ans; } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumLength(nums []int, k int) (ans int) { f := make([][]int, k) for i := range f { f[i] = make([]int, k) } for _, x := range nums { x %= k for j := 0; j < k; j++ { y := (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) } } return }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maximumLength(int[] nums, int k) { int[][] f = new int[k][k]; int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumLength(self, nums: List[int], k: int) -> int: f = [[0] * k for _ in range(k)] ans = 0 for x in nums: x %= k for j in range(k): y = (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) return ans
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_length(nums: Vec<i32>, k: i32) -> i32 { let k = k as usize; let mut f = vec![vec![0; k]; k]; let mut ans = 0; for x in nums { let x = (x % k as i32) as usize; for j in 0..k { let y = (j + k - x) % k; f[x][y] = f[y][x] + 1; ans = ans.max(f[x][y]); } } ans } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</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,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumLength(nums: number[], k: number): number { const f: number[][] = Array.from({ length: k }, () => Array(k).fill(0)); let ans: number = 0; for (let x of nums) { x %= k; for (let j = 0; j < k; ++j) { const y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
C++
class Solution { public: int minimumDiameterAfterMerge(vector<vector<int>>& edges1, vector<vector<int>>& edges2) { int d1 = treeDiameter(edges1); int d2 = treeDiameter(edges2); return max({d1, d2, (d1 + 1) / 2 + (d2 + 1) / 2 + 1}); } int treeDiameter(vector<vector<int>>& edges) { int n = edges.size() + 1; vector<int> g[n]; for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } int ans = 0, a = 0; auto dfs = [&](this auto&& dfs, int i, int fa, int t) -> void { for (int j : g[i]) { if (j != fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } }; dfs(0, -1, 0); dfs(a, -1, 0); return ans; } };
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
C#
public class Solution { private List<int>[] g; private int ans; private int a; public int MinimumDiameterAfterMerge(int[][] edges1, int[][] edges2) { int d1 = TreeDiameter(edges1); int d2 = TreeDiameter(edges2); return Math.Max(Math.Max(d1, d2), (d1 + 1) / 2 + (d2 + 1) / 2 + 1); } public int TreeDiameter(int[][] edges) { int n = edges.Length + 1; g = new List<int>[n]; for (int k = 0; k < n; ++k) { g[k] = new List<int>(); } ans = 0; a = 0; foreach (var e in edges) { int a = e[0], b = e[1]; g[a].Add(b); g[b].Add(a); } Dfs(0, -1, 0); Dfs(a, -1, 0); return ans; } private void Dfs(int i, int fa, int t) { foreach (int j in g[i]) { if (j != fa) { Dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
Go
func minimumDiameterAfterMerge(edges1 [][]int, edges2 [][]int) int { d1 := treeDiameter(edges1) d2 := treeDiameter(edges2) return max(d1, d2, (d1+1)/2+(d2+1)/2+1) } func treeDiameter(edges [][]int) (ans int) { n := len(edges) + 1 g := make([][]int, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } a := 0 var dfs func(i, fa, t int) dfs = func(i, fa, t int) { for _, j := range g[i] { if j != fa { dfs(j, i, t+1) } } if ans < t { ans = t a = i } } dfs(0, -1, 0) dfs(a, -1, 0) return }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
Java
class Solution { private List<Integer>[] g; private int ans; private int a; public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) { int d1 = treeDiameter(edges1); int d2 = treeDiameter(edges2); return Math.max(Math.max(d1, d2), (d1 + 1) / 2 + (d2 + 1) / 2 + 1); } public int treeDiameter(int[][] edges) { int n = edges.length + 1; g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); ans = 0; a = 0; for (var e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } dfs(0, -1, 0); dfs(a, -1, 0); return ans; } private void dfs(int i, int fa, int t) { for (int j : g[i]) { if (j != fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
Python
class Solution: def minimumDiameterAfterMerge( self, edges1: List[List[int]], edges2: List[List[int]] ) -> int: d1 = self.treeDiameter(edges1) d2 = self.treeDiameter(edges2) return max(d1, d2, (d1 + 1) // 2 + (d2 + 1) // 2 + 1) def treeDiameter(self, edges: List[List[int]]) -> int: def dfs(i: int, fa: int, t: int): for j in g[i]: if j != fa: dfs(j, i, t + 1) nonlocal ans, a if ans < t: ans = t a = i g = defaultdict(list) for a, b in edges: g[a].append(b) g[b].append(a) ans = a = 0 dfs(0, -1, 0) dfs(a, -1, 0) return ans
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
Rust
impl Solution { pub fn minimum_diameter_after_merge(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>) -> i32 { let d1 = Self::tree_diameter(&edges1); let d2 = Self::tree_diameter(&edges2); d1.max(d2).max((d1 + 1) / 2 + (d2 + 1) / 2 + 1) } fn tree_diameter(edges: &Vec<Vec<i32>>) -> i32 { let n = edges.len() + 1; let mut g = vec![vec![]; n]; for e in edges { let a = e[0] as usize; let b = e[1] as usize; g[a].push(b); g[b].push(a); } let mut ans = 0; let mut a = 0; fn dfs(g: &Vec<Vec<usize>>, i: usize, fa: isize, t: i32, ans: &mut i32, a: &mut usize) { for &j in &g[i] { if j as isize != fa { dfs(g, j, i as isize, t + 1, ans, a); } } if *ans < t { *ans = t; *a = i; } } dfs(&g, 0, -1, 0, &mut ans, &mut a); dfs(&g, a, -1, 0, &mut ans, &mut a); ans } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p> <p>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>edges1.length == n - 1</code></li> <li><code>edges2.length == m - 1</code></li> <li><code>edges1[i].length == edges2[i].length == 2</code></li> <li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; m</code></li> <li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Graph
TypeScript
function minimumDiameterAfterMerge(edges1: number[][], edges2: number[][]): number { const d1 = treeDiameter(edges1); const d2 = treeDiameter(edges2); return Math.max(d1, d2, Math.ceil(d1 / 2) + Math.ceil(d2 / 2) + 1); } function treeDiameter(edges: number[][]): number { const n = edges.length + 1; const g: number[][] = Array.from({ length: n }, () => []); for (const [a, b] of edges) { g[a].push(b); g[b].push(a); } let [ans, a] = [0, 0]; const dfs = (i: number, fa: number, t: number): void => { for (const j of g[i]) { if (j !== fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } }; dfs(0, -1, 0); dfs(a, -1, 0); return ans; }
3,204
Bitwise User Permissions Analysis
Medium
<p>Table: <code>user_permissions</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | permissions | int | +-------------+---------+ user_id is the primary key. Each row of this table contains the user ID and their permissions encoded as an integer. </pre> <p>Consider that each bit in the <code>permissions</code> integer represents a different access level or feature that a user has.</p> <p>Write a solution to calculate the following:</p> <ul> <li>common_perms: The access level granted to <strong>all users</strong>. This is computed using a <strong>bitwise AND</strong> operation on the <code>permissions</code> column.</li> <li>any_perms: The access level granted to <strong>any user</strong>. This is computed using a <strong>bitwise OR</strong> operation on the <code>permissions</code> column.</li> </ul> <p>Return <em>the result table in <strong>any</strong> order</em>.</p> <p>The result format is shown in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>user_permissions table:</p> <pre class="example-io"> +---------+-------------+ | user_id | permissions | +---------+-------------+ | 1 | 5 | | 2 | 12 | | 3 | 7 | | 4 | 3 | +---------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+--------------+ | common_perms | any_perms | +--------------+-------------+ | 0 | 15 | +--------------+-------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>common_perms:</strong> Represents the bitwise AND result of all permissions: <ul> <li>For user 1 (5): 5 (binary 0101)</li> <li>For user 2 (12): 12 (binary 1100)</li> <li>For user 3 (7): 7 (binary 0111)</li> <li>For user 4 (3): 3 (binary 0011)</li> <li>Bitwise AND: 5 &amp; 12 &amp; 7 &amp; 3 = 0 (binary 0000)</li> </ul> </li> <li><strong>any_perms:</strong> Represents the bitwise OR result of all permissions: <ul> <li>Bitwise OR: 5 | 12 | 7 | 3 = 15 (binary 1111)</li> </ul> </li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT BIT_AND(permissions) AS common_perms, BIT_OR(permissions) AS any_perms FROM user_permissions;
3,205
Maximum Array Hopping Score I
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of&nbsp;<code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of&nbsp;<code>(2 - 0) * 8 =&nbsp;16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
C++
class Solution { public: int maxScore(vector<int>& nums) { int n = nums.size(); vector<int> f(n); auto dfs = [&](this auto&& dfs, int i) -> int { if (f[i]) { return f[i]; } for (int j = i + 1; j < n; ++j) { f[i] = max(f[i], (j - i) * nums[j] + dfs(j)); } return f[i]; }; return dfs(0); } };
3,205
Maximum Array Hopping Score I
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of&nbsp;<code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of&nbsp;<code>(2 - 0) * 8 =&nbsp;16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
Go
func maxScore(nums []int) int { n := len(nums) f := make([]int, n) var dfs func(int) int dfs = func(i int) int { if f[i] > 0 { return f[i] } for j := i + 1; j < n; j++ { f[i] = max(f[i], (j-i)*nums[j]+dfs(j)) } return f[i] } return dfs(0) }
3,205
Maximum Array Hopping Score I
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of&nbsp;<code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of&nbsp;<code>(2 - 0) * 8 =&nbsp;16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
Java
class Solution { private Integer[] f; private int[] nums; private int n; public int maxScore(int[] nums) { n = nums.length; f = new Integer[n]; this.nums = nums; return dfs(0); } private int dfs(int i) { if (f[i] != null) { return f[i]; } f[i] = 0; for (int j = i + 1; j < n; ++j) { f[i] = Math.max(f[i], (j - i) * nums[j] + dfs(j)); } return f[i]; } }
3,205
Maximum Array Hopping Score I
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of&nbsp;<code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of&nbsp;<code>(2 - 0) * 8 =&nbsp;16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
Python
class Solution: def maxScore(self, nums: List[int]) -> int: @cache def dfs(i: int) -> int: return max( [(j - i) * nums[j] + dfs(j) for j in range(i + 1, len(nums))] or [0] ) return dfs(0)
3,205
Maximum Array Hopping Score I
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of&nbsp;<code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of&nbsp;<code>(2 - 0) * 8 =&nbsp;16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
TypeScript
function maxScore(nums: number[]): number { const n = nums.length; const f: number[] = Array(n).fill(0); const dfs = (i: number): number => { if (f[i]) { return f[i]; } for (let j = i + 1; j < n; ++j) { f[i] = Math.max(f[i], (j - i) * nums[j] + dfs(j)); } return f[i]; }; return dfs(0); }
3,206
Alternating Groups I
Easy
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> <p>Alternating groups:</p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 100</code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> </ul>
Array; Sliding Window
C++
class Solution { public: int numberOfAlternatingGroups(vector<int>& colors) { int k = 3; int n = colors.size(); int ans = 0, cnt = 0; for (int i = 0; i < n << 1; ++i) { if (i && colors[i % n] == colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; } };
3,206
Alternating Groups I
Easy
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> <p>Alternating groups:</p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 100</code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> </ul>
Array; Sliding Window
Go
func numberOfAlternatingGroups(colors []int) (ans int) { k := 3 n := len(colors) cnt := 0 for i := 0; i < n<<1; i++ { if i > 0 && colors[i%n] == colors[(i-1)%n] { cnt = 1 } else { cnt++ } if i >= n && cnt >= k { ans++ } } return }
3,206
Alternating Groups I
Easy
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> <p>Alternating groups:</p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 100</code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> </ul>
Array; Sliding Window
Java
class Solution { public int numberOfAlternatingGroups(int[] colors) { int k = 3; int n = colors.length; int ans = 0, cnt = 0; for (int i = 0; i < n << 1; ++i) { if (i > 0 && colors[i % n] == colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; } }
3,206
Alternating Groups I
Easy
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> <p>Alternating groups:</p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 100</code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> </ul>
Array; Sliding Window
Python
class Solution: def numberOfAlternatingGroups(self, colors: List[int]) -> int: k = 3 n = len(colors) ans = cnt = 0 for i in range(n << 1): if i and colors[i % n] == colors[(i - 1) % n]: cnt = 1 else: cnt += 1 ans += i >= n and cnt >= k return ans
3,206
Alternating Groups I
Easy
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p> <p>Alternating groups:</p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 100</code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> </ul>
Array; Sliding Window
TypeScript
function numberOfAlternatingGroups(colors: number[]): number { const k = 3; const n = colors.length; let [ans, cnt] = [0, 0]; for (let i = 0; i < n << 1; ++i) { if (i && colors[i % n] === colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; }
3,207
Maximum Points After Enemy Battles
Medium
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p> <p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p> <p>You start with 0 points, and all the enemies are unmarked initially.</p> <p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p> <ul> <li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy &gt;= enemyEnergies[i]</code>. By choosing this option: <ul> <li>You gain 1 point.</li> <li>Your energy is reduced by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li> </ul> </li> <li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option: <ul> <li>Your energy increases by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li> <li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li> </ul> </li> </ul> <p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The following operations can be performed to get 3 points, which is the maximum:</p> <ul> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li> <li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li> <li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li> <li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation: </strong></p> <p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= enemyEnergies.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= enemyEnergies[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= currentEnergy &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array
C++
class Solution { public: long long maximumPoints(vector<int>& enemyEnergies, int currentEnergy) { sort(enemyEnergies.begin(), enemyEnergies.end()); if (currentEnergy < enemyEnergies[0]) { return 0; } long long ans = 0; for (int i = enemyEnergies.size() - 1; i >= 0; --i) { ans += currentEnergy / enemyEnergies[0]; currentEnergy %= enemyEnergies[0]; currentEnergy += enemyEnergies[i]; } return ans; } };
3,207
Maximum Points After Enemy Battles
Medium
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p> <p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p> <p>You start with 0 points, and all the enemies are unmarked initially.</p> <p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p> <ul> <li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy &gt;= enemyEnergies[i]</code>. By choosing this option: <ul> <li>You gain 1 point.</li> <li>Your energy is reduced by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li> </ul> </li> <li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option: <ul> <li>Your energy increases by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li> <li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li> </ul> </li> </ul> <p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The following operations can be performed to get 3 points, which is the maximum:</p> <ul> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li> <li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li> <li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li> <li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation: </strong></p> <p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= enemyEnergies.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= enemyEnergies[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= currentEnergy &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array
Go
func maximumPoints(enemyEnergies []int, currentEnergy int) (ans int64) { sort.Ints(enemyEnergies) if currentEnergy < enemyEnergies[0] { return 0 } for i := len(enemyEnergies) - 1; i >= 0; i-- { ans += int64(currentEnergy / enemyEnergies[0]) currentEnergy %= enemyEnergies[0] currentEnergy += enemyEnergies[i] } return }
3,207
Maximum Points After Enemy Battles
Medium
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p> <p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p> <p>You start with 0 points, and all the enemies are unmarked initially.</p> <p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p> <ul> <li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy &gt;= enemyEnergies[i]</code>. By choosing this option: <ul> <li>You gain 1 point.</li> <li>Your energy is reduced by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li> </ul> </li> <li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option: <ul> <li>Your energy increases by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li> <li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li> </ul> </li> </ul> <p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The following operations can be performed to get 3 points, which is the maximum:</p> <ul> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li> <li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li> <li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li> <li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation: </strong></p> <p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= enemyEnergies.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= enemyEnergies[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= currentEnergy &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array
Java
class Solution { public long maximumPoints(int[] enemyEnergies, int currentEnergy) { Arrays.sort(enemyEnergies); if (currentEnergy < enemyEnergies[0]) { return 0; } long ans = 0; for (int i = enemyEnergies.length - 1; i >= 0; --i) { ans += currentEnergy / enemyEnergies[0]; currentEnergy %= enemyEnergies[0]; currentEnergy += enemyEnergies[i]; } return ans; } };
3,207
Maximum Points After Enemy Battles
Medium
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p> <p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p> <p>You start with 0 points, and all the enemies are unmarked initially.</p> <p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p> <ul> <li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy &gt;= enemyEnergies[i]</code>. By choosing this option: <ul> <li>You gain 1 point.</li> <li>Your energy is reduced by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li> </ul> </li> <li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option: <ul> <li>Your energy increases by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li> <li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li> </ul> </li> </ul> <p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The following operations can be performed to get 3 points, which is the maximum:</p> <ul> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li> <li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li> <li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li> <li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation: </strong></p> <p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= enemyEnergies.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= enemyEnergies[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= currentEnergy &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array
Python
class Solution: def maximumPoints(self, enemyEnergies: List[int], currentEnergy: int) -> int: enemyEnergies.sort() if currentEnergy < enemyEnergies[0]: return 0 ans = 0 for i in range(len(enemyEnergies) - 1, -1, -1): ans += currentEnergy // enemyEnergies[0] currentEnergy %= enemyEnergies[0] currentEnergy += enemyEnergies[i] return ans
3,207
Maximum Points After Enemy Battles
Medium
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p> <p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p> <p>You start with 0 points, and all the enemies are unmarked initially.</p> <p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p> <ul> <li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy &gt;= enemyEnergies[i]</code>. By choosing this option: <ul> <li>You gain 1 point.</li> <li>Your energy is reduced by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li> </ul> </li> <li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option: <ul> <li>Your energy increases by the enemy&#39;s energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li> <li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li> </ul> </li> </ul> <p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The following operations can be performed to get 3 points, which is the maximum:</p> <ul> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li> <li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li> <li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li> <li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li> <li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation: </strong></p> <p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= enemyEnergies.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= enemyEnergies[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= currentEnergy &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array
TypeScript
function maximumPoints(enemyEnergies: number[], currentEnergy: number): number { enemyEnergies.sort((a, b) => a - b); if (currentEnergy < enemyEnergies[0]) { return 0; } let ans = 0; for (let i = enemyEnergies.length - 1; ~i; --i) { ans += Math.floor(currentEnergy / enemyEnergies[0]); currentEnergy %= enemyEnergies[0]; currentEnergy += enemyEnergies[i]; } return ans; }
3,208
Alternating Groups II
Medium
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> <li><code>3 &lt;= k &lt;= colors.length</code></li> </ul>
Array; Sliding Window
C++
class Solution { public: int numberOfAlternatingGroups(vector<int>& colors, int k) { int n = colors.size(); int ans = 0, cnt = 0; for (int i = 0; i < n << 1; ++i) { if (i && colors[i % n] == colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; } };
3,208
Alternating Groups II
Medium
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> <li><code>3 &lt;= k &lt;= colors.length</code></li> </ul>
Array; Sliding Window
Go
func numberOfAlternatingGroups(colors []int, k int) (ans int) { n := len(colors) cnt := 0 for i := 0; i < n<<1; i++ { if i > 0 && colors[i%n] == colors[(i-1)%n] { cnt = 1 } else { cnt++ } if i >= n && cnt >= k { ans++ } } return }
3,208
Alternating Groups II
Medium
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> <li><code>3 &lt;= k &lt;= colors.length</code></li> </ul>
Array; Sliding Window
Java
class Solution { public int numberOfAlternatingGroups(int[] colors, int k) { int n = colors.length; int ans = 0, cnt = 0; for (int i = 0; i < n << 1; ++i) { if (i > 0 && colors[i % n] == colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; } }
3,208
Alternating Groups II
Medium
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> <li><code>3 &lt;= k &lt;= colors.length</code></li> </ul>
Array; Sliding Window
Python
class Solution: def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int: n = len(colors) ans = cnt = 0 for i in range(n << 1): if i and colors[i % n] == colors[(i - 1) % n]: cnt = 1 else: cnt += 1 ans += i >= n and cnt >= k return ans
3,208
Alternating Groups II
Medium
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p> <ul> <li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li> <li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li> </ul> <p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p> <p>Return the number of <strong>alternating</strong> groups.</p> <p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p> <p>Alternating groups:</p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= colors.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= colors[i] &lt;= 1</code></li> <li><code>3 &lt;= k &lt;= colors.length</code></li> </ul>
Array; Sliding Window
TypeScript
function numberOfAlternatingGroups(colors: number[], k: number): number { const n = colors.length; let [ans, cnt] = [0, 0]; for (let i = 0; i < n << 1; ++i) { if (i && colors[i % n] === colors[(i - 1) % n]) { cnt = 1; } else { ++cnt; } ans += i >= n && cnt >= k ? 1 : 0; } return ans; }
3,209
Number of Subarrays With AND Value of K
Hard
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>All subarrays contain only 1&#39;s.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Segment Tree; Array; Binary Search
C++
class Solution { public: long long countSubarrays(vector<int>& nums, int k) { long long ans = 0; unordered_map<int, int> pre; for (int x : nums) { unordered_map<int, int> cur; for (auto& [y, v] : pre) { cur[x & y] += v; } cur[x]++; ans += cur[k]; pre = cur; } return ans; } };
3,209
Number of Subarrays With AND Value of K
Hard
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>All subarrays contain only 1&#39;s.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Segment Tree; Array; Binary Search
Go
func countSubarrays(nums []int, k int) (ans int64) { pre := map[int]int{} for _, x := range nums { cur := map[int]int{} for y, v := range pre { cur[x&y] += v } cur[x]++ ans += int64(cur[k]) pre = cur } return }
3,209
Number of Subarrays With AND Value of K
Hard
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>All subarrays contain only 1&#39;s.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Segment Tree; Array; Binary Search
Java
class Solution { public long countSubarrays(int[] nums, int k) { long ans = 0; Map<Integer, Integer> pre = new HashMap<>(); for (int x : nums) { Map<Integer, Integer> cur = new HashMap<>(); for (var e : pre.entrySet()) { int y = e.getKey(), v = e.getValue(); cur.merge(x & y, v, Integer::sum); } cur.merge(x, 1, Integer::sum); ans += cur.getOrDefault(k, 0); pre = cur; } return ans; } }
3,209
Number of Subarrays With AND Value of K
Hard
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>All subarrays contain only 1&#39;s.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Segment Tree; Array; Binary Search
Python
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: ans = 0 pre = Counter() for x in nums: cur = Counter() for y, v in pre.items(): cur[x & y] += v cur[x] += 1 ans += cur[k] pre = cur return ans
3,209
Number of Subarrays With AND Value of K
Hard
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>All subarrays contain only 1&#39;s.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Segment Tree; Array; Binary Search
TypeScript
function countSubarrays(nums: number[], k: number): number { let ans = 0; let pre = new Map<number, number>(); for (const x of nums) { const cur = new Map<number, number>(); for (const [y, v] of pre) { const z = x & y; cur.set(z, (cur.get(z) || 0) + v); } cur.set(x, (cur.get(x) || 0) + 1); ans += cur.get(k) || 0; pre = cur; } return ans; }
3,210
Find the Encrypted String
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p> <ul> <li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li> </ul> <p>Return the <em>encrypted string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;dart&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;tdar&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>&#39;d&#39;</code> is <code>&#39;t&#39;</code>.</li> <li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>&#39;a&#39;</code> is <code>&#39;d&#39;</code>.</li> <li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>&#39;r&#39;</code> is <code>&#39;a&#39;</code>.</li> <li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>&#39;t&#39;</code> is <code>&#39;r&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaa&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p>As all the characters are the same, the encrypted string will also be the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
C++
class Solution { public: string getEncryptedString(string s, int k) { int n = s.length(); string cs(n, ' '); for (int i = 0; i < n; ++i) { cs[i] = s[(i + k) % n]; } return cs; } };
3,210
Find the Encrypted String
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p> <ul> <li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li> </ul> <p>Return the <em>encrypted string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;dart&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;tdar&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>&#39;d&#39;</code> is <code>&#39;t&#39;</code>.</li> <li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>&#39;a&#39;</code> is <code>&#39;d&#39;</code>.</li> <li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>&#39;r&#39;</code> is <code>&#39;a&#39;</code>.</li> <li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>&#39;t&#39;</code> is <code>&#39;r&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaa&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p>As all the characters are the same, the encrypted string will also be the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Go
func getEncryptedString(s string, k int) string { cs := []byte(s) for i := range s { cs[i] = s[(i+k)%len(s)] } return string(cs) }
3,210
Find the Encrypted String
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p> <ul> <li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li> </ul> <p>Return the <em>encrypted string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;dart&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;tdar&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>&#39;d&#39;</code> is <code>&#39;t&#39;</code>.</li> <li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>&#39;a&#39;</code> is <code>&#39;d&#39;</code>.</li> <li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>&#39;r&#39;</code> is <code>&#39;a&#39;</code>.</li> <li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>&#39;t&#39;</code> is <code>&#39;r&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaa&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p>As all the characters are the same, the encrypted string will also be the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Java
class Solution { public String getEncryptedString(String s, int k) { char[] cs = s.toCharArray(); int n = cs.length; for (int i = 0; i < n; ++i) { cs[i] = s.charAt((i + k) % n); } return new String(cs); } }
3,210
Find the Encrypted String
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p> <ul> <li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li> </ul> <p>Return the <em>encrypted string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;dart&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;tdar&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>&#39;d&#39;</code> is <code>&#39;t&#39;</code>.</li> <li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>&#39;a&#39;</code> is <code>&#39;d&#39;</code>.</li> <li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>&#39;r&#39;</code> is <code>&#39;a&#39;</code>.</li> <li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>&#39;t&#39;</code> is <code>&#39;r&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaa&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p>As all the characters are the same, the encrypted string will also be the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Python
class Solution: def getEncryptedString(self, s: str, k: int) -> str: cs = list(s) n = len(s) for i in range(n): cs[i] = s[(i + k) % n] return "".join(cs)
3,210
Find the Encrypted String
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p> <ul> <li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li> </ul> <p>Return the <em>encrypted string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;dart&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;tdar&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>&#39;d&#39;</code> is <code>&#39;t&#39;</code>.</li> <li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>&#39;a&#39;</code> is <code>&#39;d&#39;</code>.</li> <li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>&#39;r&#39;</code> is <code>&#39;a&#39;</code>.</li> <li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>&#39;t&#39;</code> is <code>&#39;r&#39;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaa&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p>As all the characters are the same, the encrypted string will also be the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
TypeScript
function getEncryptedString(s: string, k: number): string { const cs: string[] = []; const n = s.length; for (let i = 0; i < n; ++i) { cs[i] = s[(i + k) % n]; } return cs.join(''); }
3,211
Generate Binary Strings Without Adjacent Zeros
Medium
<p>You are given a positive integer <code>n</code>.</p> <p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>&quot;1&quot;</code>.</p> <p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;010&quot;,&quot;011&quot;,&quot;101&quot;,&quot;110&quot;,&quot;111&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 3 are: <code>&quot;010&quot;</code>, <code>&quot;011&quot;</code>, <code>&quot;101&quot;</code>, <code>&quot;110&quot;</code>, and <code>&quot;111&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;0&quot;,&quot;1&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 1 are: <code>&quot;0&quot;</code> and <code>&quot;1&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 18</code></li> </ul>
Bit Manipulation; String; Backtracking
C++
class Solution { public: vector<string> validStrings(int n) { vector<string> ans; string t; auto dfs = [&](this auto&& dfs, int i) { if (i >= n) { ans.emplace_back(t); return; } for (int j = 0; j < 2; ++j) { if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) { t.push_back('0' + j); dfs(i + 1); t.pop_back(); } } }; dfs(0); return ans; } };
3,211
Generate Binary Strings Without Adjacent Zeros
Medium
<p>You are given a positive integer <code>n</code>.</p> <p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>&quot;1&quot;</code>.</p> <p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;010&quot;,&quot;011&quot;,&quot;101&quot;,&quot;110&quot;,&quot;111&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 3 are: <code>&quot;010&quot;</code>, <code>&quot;011&quot;</code>, <code>&quot;101&quot;</code>, <code>&quot;110&quot;</code>, and <code>&quot;111&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;0&quot;,&quot;1&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 1 are: <code>&quot;0&quot;</code> and <code>&quot;1&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 18</code></li> </ul>
Bit Manipulation; String; Backtracking
Go
func validStrings(n int) (ans []string) { t := []byte{} var dfs func(int) dfs = func(i int) { if i >= n { ans = append(ans, string(t)) return } for j := 0; j < 2; j++ { if (j == 0 && (i == 0 || t[i-1] == '1')) || j == 1 { t = append(t, byte('0'+j)) dfs(i + 1) t = t[:len(t)-1] } } } dfs(0) return }
3,211
Generate Binary Strings Without Adjacent Zeros
Medium
<p>You are given a positive integer <code>n</code>.</p> <p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>&quot;1&quot;</code>.</p> <p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;010&quot;,&quot;011&quot;,&quot;101&quot;,&quot;110&quot;,&quot;111&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 3 are: <code>&quot;010&quot;</code>, <code>&quot;011&quot;</code>, <code>&quot;101&quot;</code>, <code>&quot;110&quot;</code>, and <code>&quot;111&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;0&quot;,&quot;1&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 1 are: <code>&quot;0&quot;</code> and <code>&quot;1&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 18</code></li> </ul>
Bit Manipulation; String; Backtracking
Java
class Solution { private List<String> ans = new ArrayList<>(); private StringBuilder t = new StringBuilder(); private int n; public List<String> validStrings(int n) { this.n = n; dfs(0); return ans; } private void dfs(int i) { if (i >= n) { ans.add(t.toString()); return; } for (int j = 0; j < 2; ++j) { if ((j == 0 && (i == 0 || t.charAt(i - 1) == '1')) || j == 1) { t.append(j); dfs(i + 1); t.deleteCharAt(t.length() - 1); } } } }
3,211
Generate Binary Strings Without Adjacent Zeros
Medium
<p>You are given a positive integer <code>n</code>.</p> <p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>&quot;1&quot;</code>.</p> <p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;010&quot;,&quot;011&quot;,&quot;101&quot;,&quot;110&quot;,&quot;111&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 3 are: <code>&quot;010&quot;</code>, <code>&quot;011&quot;</code>, <code>&quot;101&quot;</code>, <code>&quot;110&quot;</code>, and <code>&quot;111&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;0&quot;,&quot;1&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 1 are: <code>&quot;0&quot;</code> and <code>&quot;1&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 18</code></li> </ul>
Bit Manipulation; String; Backtracking
Python
class Solution: def validStrings(self, n: int) -> List[str]: def dfs(i: int): if i >= n: ans.append("".join(t)) return for j in range(2): if (j == 0 and (i == 0 or t[i - 1] == "1")) or j == 1: t.append(str(j)) dfs(i + 1) t.pop() ans = [] t = [] dfs(0) return ans
3,211
Generate Binary Strings Without Adjacent Zeros
Medium
<p>You are given a positive integer <code>n</code>.</p> <p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>&quot;1&quot;</code>.</p> <p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;010&quot;,&quot;011&quot;,&quot;101&quot;,&quot;110&quot;,&quot;111&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 3 are: <code>&quot;010&quot;</code>, <code>&quot;011&quot;</code>, <code>&quot;101&quot;</code>, <code>&quot;110&quot;</code>, and <code>&quot;111&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;0&quot;,&quot;1&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The valid strings of length 1 are: <code>&quot;0&quot;</code> and <code>&quot;1&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 18</code></li> </ul>
Bit Manipulation; String; Backtracking
TypeScript
function validStrings(n: number): string[] { const ans: string[] = []; const t: string[] = []; const dfs = (i: number) => { if (i >= n) { ans.push(t.join('')); return; } for (let j = 0; j < 2; ++j) { if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) { t.push(j.toString()); dfs(i + 1); t.pop(); } } }; dfs(0); return ans; }
3,212
Count Submatrices With Equal Frequency of X and Y
Medium
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p> <ul> <li><code>grid[0][0]</code></li> <li>an <strong>equal</strong> frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</li> <li><strong>at least</strong> one <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;Y&quot;,&quot;.&quot;],[&quot;Y&quot;,&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;Y&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has an equal frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has at least one <code>&#39;X&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>.</li> </ul>
Array; Matrix; Prefix Sum
C++
class Solution { public: int numberOfSubmatrices(vector<vector<char>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<vector<int>>> s(m + 1, vector<vector<int>>(n + 1, vector<int>(2))); int ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] + (grid[i - 1][j - 1] == 'X' ? 1 : 0); s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] + (grid[i - 1][j - 1] == 'Y' ? 1 : 0); if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) { ++ans; } } } return ans; } };
3,212
Count Submatrices With Equal Frequency of X and Y
Medium
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p> <ul> <li><code>grid[0][0]</code></li> <li>an <strong>equal</strong> frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</li> <li><strong>at least</strong> one <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;Y&quot;,&quot;.&quot;],[&quot;Y&quot;,&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;Y&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has an equal frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has at least one <code>&#39;X&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>.</li> </ul>
Array; Matrix; Prefix Sum
Go
func numberOfSubmatrices(grid [][]byte) (ans int) { m, n := len(grid), len(grid[0]) s := make([][][]int, m+1) for i := range s { s[i] = make([][]int, n+1) for j := range s[i] { s[i][j] = make([]int, 2) } } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { s[i][j][0] = s[i-1][j][0] + s[i][j-1][0] - s[i-1][j-1][0] if grid[i-1][j-1] == 'X' { s[i][j][0]++ } s[i][j][1] = s[i-1][j][1] + s[i][j-1][1] - s[i-1][j-1][1] if grid[i-1][j-1] == 'Y' { s[i][j][1]++ } if s[i][j][0] > 0 && s[i][j][0] == s[i][j][1] { ans++ } } } return }
3,212
Count Submatrices With Equal Frequency of X and Y
Medium
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p> <ul> <li><code>grid[0][0]</code></li> <li>an <strong>equal</strong> frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</li> <li><strong>at least</strong> one <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;Y&quot;,&quot;.&quot;],[&quot;Y&quot;,&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;Y&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has an equal frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has at least one <code>&#39;X&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>.</li> </ul>
Array; Matrix; Prefix Sum
Java
class Solution { public int numberOfSubmatrices(char[][] grid) { int m = grid.length, n = grid[0].length; int[][][] s = new int[m + 1][n + 1][2]; int ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] + (grid[i - 1][j - 1] == 'X' ? 1 : 0); s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] + (grid[i - 1][j - 1] == 'Y' ? 1 : 0); if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) { ++ans; } } } return ans; } }
3,212
Count Submatrices With Equal Frequency of X and Y
Medium
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p> <ul> <li><code>grid[0][0]</code></li> <li>an <strong>equal</strong> frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</li> <li><strong>at least</strong> one <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;Y&quot;,&quot;.&quot;],[&quot;Y&quot;,&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;Y&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has an equal frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has at least one <code>&#39;X&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>.</li> </ul>
Array; Matrix; Prefix Sum
Python
class Solution: def numberOfSubmatrices(self, grid: List[List[str]]) -> int: m, n = len(grid), len(grid[0]) s = [[[0] * 2 for _ in range(n + 1)] for _ in range(m + 1)] ans = 0 for i, row in enumerate(grid, 1): for j, x in enumerate(row, 1): s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] if x != ".": s[i][j][ord(x) & 1] += 1 if s[i][j][0] > 0 and s[i][j][0] == s[i][j][1]: ans += 1 return ans
3,212
Count Submatrices With Equal Frequency of X and Y
Medium
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p> <ul> <li><code>grid[0][0]</code></li> <li>an <strong>equal</strong> frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</li> <li><strong>at least</strong> one <code>&#39;X&#39;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;Y&quot;,&quot;.&quot;],[&quot;Y&quot;,&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;Y&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has an equal frequency of <code>&#39;X&#39;</code> and <code>&#39;Y&#39;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No submatrix has at least one <code>&#39;X&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either <code>&#39;X&#39;</code>, <code>&#39;Y&#39;</code>, or <code>&#39;.&#39;</code>.</li> </ul>
Array; Matrix; Prefix Sum
TypeScript
function numberOfSubmatrices(grid: string[][]): number { const [m, n] = [grid.length, grid[0].length]; const s = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => [0, 0])); let ans = 0; for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0] + (grid[i - 1][j - 1] === 'X' ? 1 : 0); s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1] + (grid[i - 1][j - 1] === 'Y' ? 1 : 0); if (s[i][j][0] > 0 && s[i][j][0] === s[i][j][1]) { ++ans; } } } return ans; }
3,213
Construct String with Minimum Cost
Hard
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p> <p>Imagine an empty string <code>s</code>.</p> <p>You can perform the following operation any number of times (including <strong>zero</strong>):</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li> <li>Append <code>words[i]</code> to <code>s</code>.</li> <li>The cost of operation is <code>costs[i]</code>.</li> </ul> <p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it&#39;s not possible, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;abcdef&quot;, words = [&quot;abdef&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;def&quot;,&quot;ef&quot;], costs = [100,1,1,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The minimum cost can be achieved by performing the following operations:</p> <ul> <li>Select index 1 and append <code>&quot;abc&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abc&quot;</code>.</li> <li>Select index 2 and append <code>&quot;d&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abcd&quot;</code>.</li> <li>Select index 4 and append <code>&quot;ef&quot;</code> to <code>s</code> at a cost of 5, resulting in <code>s = &quot;abcdef&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;aaaa&quot;, words = [&quot;z&quot;,&quot;zz&quot;,&quot;zzz&quot;], costs = [1,10,100]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length == costs.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= target.length</code></li> <li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li> <li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li> <li><code>1 &lt;= costs[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming; Suffix Array
C++
class Hashing { private: vector<long> p, h; long mod; public: Hashing(const string& word, long base, long mod) : p(word.size() + 1, 1) , h(word.size() + 1, 0) , mod(mod) { for (int i = 1; i <= word.size(); ++i) { p[i] = p[i - 1] * base % mod; h[i] = (h[i - 1] * base + word[i - 1]) % mod; } } long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } }; class Solution { public: int minimumCost(string target, vector<string>& words, vector<int>& costs) { const int base = 13331; const int mod = 998244353; const int inf = INT_MAX / 2; int n = target.size(); Hashing hashing(target, base, mod); vector<int> f(n + 1, inf); f[0] = 0; set<int> ss; for (const string& w : words) { ss.insert(w.size()); } unordered_map<long, int> d; for (int i = 0; i < words.size(); ++i) { long x = 0; for (char c : words[i]) { x = (x * base + c) % mod; } d[x] = d.find(x) == d.end() ? costs[i] : min(d[x], costs[i]); } for (int i = 1; i <= n; ++i) { for (int j : ss) { if (j > i) { break; } long x = hashing.query(i - j + 1, i); if (d.contains(x)) { f[i] = min(f[i], f[i - j] + d[x]); } } } return f[n] >= inf ? -1 : f[n]; } };
3,213
Construct String with Minimum Cost
Hard
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p> <p>Imagine an empty string <code>s</code>.</p> <p>You can perform the following operation any number of times (including <strong>zero</strong>):</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li> <li>Append <code>words[i]</code> to <code>s</code>.</li> <li>The cost of operation is <code>costs[i]</code>.</li> </ul> <p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it&#39;s not possible, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;abcdef&quot;, words = [&quot;abdef&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;def&quot;,&quot;ef&quot;], costs = [100,1,1,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The minimum cost can be achieved by performing the following operations:</p> <ul> <li>Select index 1 and append <code>&quot;abc&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abc&quot;</code>.</li> <li>Select index 2 and append <code>&quot;d&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abcd&quot;</code>.</li> <li>Select index 4 and append <code>&quot;ef&quot;</code> to <code>s</code> at a cost of 5, resulting in <code>s = &quot;abcdef&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;aaaa&quot;, words = [&quot;z&quot;,&quot;zz&quot;,&quot;zzz&quot;], costs = [1,10,100]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length == costs.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= target.length</code></li> <li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li> <li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li> <li><code>1 &lt;= costs[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming; Suffix Array
Go
type Hashing struct { p []int64 h []int64 mod int64 } func NewHashing(word string, base, mod int64) *Hashing { n := len(word) p := make([]int64, n+1) h := make([]int64, n+1) p[0] = 1 for i := 1; i <= n; i++ { p[i] = p[i-1] * base % mod h[i] = (h[i-1]*base + int64(word[i-1])) % mod } return &Hashing{p, h, mod} } func (hs *Hashing) query(l, r int) int64 { return (hs.h[r] - hs.h[l-1]*hs.p[r-l+1]%hs.mod + hs.mod) % hs.mod } func minimumCost(target string, words []string, costs []int) int { const base = 13331 const mod = 998244353 const inf = math.MaxInt32 / 2 n := len(target) hashing := NewHashing(target, base, mod) f := make([]int, n+1) for i := range f { f[i] = inf } f[0] = 0 ss := make(map[int]struct{}) for _, w := range words { ss[len(w)] = struct{}{} } lengths := make([]int, 0, len(ss)) for length := range ss { lengths = append(lengths, length) } sort.Ints(lengths) d := make(map[int64]int) for i, w := range words { var x int64 for _, c := range w { x = (x*base + int64(c)) % mod } if existingCost, exists := d[x]; exists { if costs[i] < existingCost { d[x] = costs[i] } } else { d[x] = costs[i] } } for i := 1; i <= n; i++ { for _, j := range lengths { if j > i { break } x := hashing.query(i-j+1, i) if cost, ok := d[x]; ok { f[i] = min(f[i], f[i-j]+cost) } } } if f[n] >= inf { return -1 } return f[n] }
3,213
Construct String with Minimum Cost
Hard
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p> <p>Imagine an empty string <code>s</code>.</p> <p>You can perform the following operation any number of times (including <strong>zero</strong>):</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li> <li>Append <code>words[i]</code> to <code>s</code>.</li> <li>The cost of operation is <code>costs[i]</code>.</li> </ul> <p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it&#39;s not possible, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;abcdef&quot;, words = [&quot;abdef&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;def&quot;,&quot;ef&quot;], costs = [100,1,1,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The minimum cost can be achieved by performing the following operations:</p> <ul> <li>Select index 1 and append <code>&quot;abc&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abc&quot;</code>.</li> <li>Select index 2 and append <code>&quot;d&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abcd&quot;</code>.</li> <li>Select index 4 and append <code>&quot;ef&quot;</code> to <code>s</code> at a cost of 5, resulting in <code>s = &quot;abcdef&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;aaaa&quot;, words = [&quot;z&quot;,&quot;zz&quot;,&quot;zzz&quot;], costs = [1,10,100]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length == costs.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= target.length</code></li> <li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li> <li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li> <li><code>1 &lt;= costs[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming; Suffix Array
Java
class Hashing { private final long[] p; private final long[] h; private final long mod; public Hashing(String word, long base, int mod) { int n = word.length(); p = new long[n + 1]; h = new long[n + 1]; p[0] = 1; this.mod = mod; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] * base % mod; h[i] = (h[i - 1] * base + word.charAt(i - 1)) % mod; } } public long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } } class Solution { public int minimumCost(String target, String[] words, int[] costs) { final int base = 13331; final int mod = 998244353; final int inf = Integer.MAX_VALUE / 2; int n = target.length(); Hashing hashing = new Hashing(target, base, mod); int[] f = new int[n + 1]; Arrays.fill(f, inf); f[0] = 0; TreeSet<Integer> ss = new TreeSet<>(); for (String w : words) { ss.add(w.length()); } Map<Long, Integer> d = new HashMap<>(); for (int i = 0; i < words.length; i++) { long x = 0; for (char c : words[i].toCharArray()) { x = (x * base + c) % mod; } d.merge(x, costs[i], Integer::min); } for (int i = 1; i <= n; i++) { for (int j : ss) { if (j > i) { break; } long x = hashing.query(i - j + 1, i); f[i] = Math.min(f[i], f[i - j] + d.getOrDefault(x, inf)); } } return f[n] >= inf ? -1 : f[n]; } }
3,213
Construct String with Minimum Cost
Hard
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p> <p>Imagine an empty string <code>s</code>.</p> <p>You can perform the following operation any number of times (including <strong>zero</strong>):</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li> <li>Append <code>words[i]</code> to <code>s</code>.</li> <li>The cost of operation is <code>costs[i]</code>.</li> </ul> <p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it&#39;s not possible, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;abcdef&quot;, words = [&quot;abdef&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;def&quot;,&quot;ef&quot;], costs = [100,1,1,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The minimum cost can be achieved by performing the following operations:</p> <ul> <li>Select index 1 and append <code>&quot;abc&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abc&quot;</code>.</li> <li>Select index 2 and append <code>&quot;d&quot;</code> to <code>s</code> at a cost of 1, resulting in <code>s = &quot;abcd&quot;</code>.</li> <li>Select index 4 and append <code>&quot;ef&quot;</code> to <code>s</code> at a cost of 5, resulting in <code>s = &quot;abcdef&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">target = &quot;aaaa&quot;, words = [&quot;z&quot;,&quot;zz&quot;,&quot;zzz&quot;], costs = [1,10,100]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words.length == costs.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= target.length</code></li> <li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li> <li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li> <li><code>1 &lt;= costs[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; String; Dynamic Programming; Suffix Array
Python
class Solution: def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int: base, mod = 13331, 998244353 n = len(target) h = [0] * (n + 1) p = [1] * (n + 1) for i, c in enumerate(target, 1): h[i] = (h[i - 1] * base + ord(c)) % mod p[i] = (p[i - 1] * base) % mod f = [0] + [inf] * n ss = sorted(set(map(len, words))) d = defaultdict(lambda: inf) min = lambda a, b: a if a < b else b for w, c in zip(words, costs): x = 0 for ch in w: x = (x * base + ord(ch)) % mod d[x] = min(d[x], c) for i in range(1, n + 1): for j in ss: if j > i: break x = (h[i] - h[i - j] * p[j]) % mod f[i] = min(f[i], f[i - j] + d[x]) return f[n] if f[n] < inf else -1
3,214
Year on Year Growth Rate
Hard
<p>Table: <code>user_transactions</code></p> <pre> +------------------+----------+ | Column Name | Type | +------------------+----------+ | transaction_id | integer | | product_id | integer | | spend | decimal | | transaction_date | datetime | +------------------+----------+ The transaction_id column uniquely identifies each row in this table. Each row of this table contains the transaction ID, product ID, the spend amount, and the transaction date. </pre> <p>Write a solution to calculate the <strong>year-on-year growth rate</strong> for the total spend <strong>for each product</strong>.</p> <p>The result table should include the following columns:</p> <ul> <li><code>year</code>: The year of the transaction.</li> <li><code>product_id</code>: The ID of the product.</li> <li><code>curr_year_spend</code>: The total spend for the current year.</li> <li><code>prev_year_spend</code>: The total spend for the previous year.</li> <li><code>yoy_rate</code>: The year-on-year growth rate percentage, rounded to <code>2</code> decimal places.</li> </ul> <p>Return <em>the result table ordered by</em>&nbsp;<code>product_id</code>,<code>year</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p><code>user_transactions</code> table:</p> <pre class="example-io"> +----------------+------------+---------+---------------------+ | transaction_id | product_id | spend | transaction_date | +----------------+------------+---------+---------------------+ | 1341 | 123424 | 1500.60 | 2019-12-31 12:00:00 | | 1423 | 123424 | 1000.20 | 2020-12-31 12:00:00 | | 1623 | 123424 | 1246.44 | 2021-12-31 12:00:00 | | 1322 | 123424 | 2145.32 | 2022-12-31 12:00:00 | +----------------+------------+---------+---------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------+------------+----------------+----------------+----------+ | year | product_id | curr_year_spend| prev_year_spend| yoy_rate | +------+------------+----------------+----------------+----------+ | 2019 | 123424 | 1500.60 | NULL | NULL | | 2020 | 123424 | 1000.20 | 1500.60 | -33.35 | | 2021 | 123424 | 1246.44 | 1000.20 | 24.62 | | 2022 | 123424 | 2145.32 | 1246.44 | 72.12 | +------+------------+----------------+----------------+----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For product ID 123424: <ul> <li>In 2019: <ul> <li>Current year&#39;s spend is 1500.60</li> <li>No previous year&#39;s spend recorded</li> <li>YoY growth rate: NULL</li> </ul> </li> <li>In 2020: <ul> <li>Current year&#39;s spend is 1000.20</li> <li>Previous year&#39;s spend is 1500.60</li> <li>YoY growth rate: ((1000.20 - 1500.60) / 1500.60) * 100 = -33.35%</li> </ul> </li> <li>In 2021: <ul> <li>Current year&#39;s spend is 1246.44</li> <li>Previous year&#39;s spend is 1000.20</li> <li>YoY growth rate: ((1246.44 - 1000.20) / 1000.20) * 100 = 24.62%</li> </ul> </li> <li>In 2022: <ul> <li>Current year&#39;s spend is 2145.32</li> <li>Previous year&#39;s spend is 1246.44</li> <li>YoY growth rate: ((2145.32 - 1246.44) / 1246.44) * 100 = 72.12%</li> </ul> </li> </ul> </li> </ul> <p><strong>Note:</strong> Output table is ordered by <code>product_id</code> and <code>year</code> in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT product_id, YEAR(transaction_date) year, SUM(spend) curr_year_spend FROM user_transactions GROUP BY 1, 2 ), S AS ( SELECT t1.year, t1.product_id, t1.curr_year_spend, t2.curr_year_spend prev_year_spend FROM T t1 LEFT JOIN T t2 ON t1.product_id = t2.product_id AND t1.year = t2.year + 1 ) SELECT *, ROUND((curr_year_spend - prev_year_spend) / prev_year_spend * 100, 2) yoy_rate FROM S ORDER BY 2, 1;
3,215
Count Triplets with Even XOR Set Bits II
Medium
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) { int cnt1[2]{}; int cnt2[2]{}; int cnt3[2]{}; for (int x : a) { ++cnt1[__builtin_popcount(x) & 1]; } for (int x : b) { ++cnt2[__builtin_popcount(x) & 1]; } for (int x : c) { ++cnt3[__builtin_popcount(x) & 1]; } long long ans = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { if ((i + j + k) % 2 == 0) { ans += 1LL * cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } };
3,215
Count Triplets with Even XOR Set Bits II
Medium
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array
Go
func tripletCount(a []int, b []int, c []int) (ans int64) { cnt1 := [2]int{} cnt2 := [2]int{} cnt3 := [2]int{} for _, x := range a { cnt1[bits.OnesCount(uint(x))%2]++ } for _, x := range b { cnt2[bits.OnesCount(uint(x))%2]++ } for _, x := range c { cnt3[bits.OnesCount(uint(x))%2]++ } for i := 0; i < 2; i++ { for j := 0; j < 2; j++ { for k := 0; k < 2; k++ { if (i+j+k)%2 == 0 { ans += int64(cnt1[i] * cnt2[j] * cnt3[k]) } } } } return }
3,215
Count Triplets with Even XOR Set Bits II
Medium
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array
Java
class Solution { public long tripletCount(int[] a, int[] b, int[] c) { int[] cnt1 = new int[2]; int[] cnt2 = new int[2]; int[] cnt3 = new int[2]; for (int x : a) { ++cnt1[Integer.bitCount(x) & 1]; } for (int x : b) { ++cnt2[Integer.bitCount(x) & 1]; } for (int x : c) { ++cnt3[Integer.bitCount(x) & 1]; } long ans = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { if ((i + j + k) % 2 == 0) { ans += 1L * cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } }
3,215
Count Triplets with Even XOR Set Bits II
Medium
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array
Python
class Solution: def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int: cnt1 = Counter(x.bit_count() & 1 for x in a) cnt2 = Counter(x.bit_count() & 1 for x in b) cnt3 = Counter(x.bit_count() & 1 for x in c) ans = 0 for i in range(2): for j in range(2): for k in range(2): if (i + j + k) & 1 ^ 1: ans += cnt1[i] * cnt2[j] * cnt3[k] return ans
3,215
Count Triplets with Even XOR Set Bits II
Medium
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array
TypeScript
function tripletCount(a: number[], b: number[], c: number[]): number { const cnt1: [number, number] = [0, 0]; const cnt2: [number, number] = [0, 0]; const cnt3: [number, number] = [0, 0]; for (const x of a) { ++cnt1[bitCount(x) & 1]; } for (const x of b) { ++cnt2[bitCount(x) & 1]; } for (const x of c) { ++cnt3[bitCount(x) & 1]; } let ans = 0; for (let i = 0; i < 2; ++i) { for (let j = 0; j < 2; ++j) { for (let k = 0; k < 2; ++k) { if ((i + j + k) % 2 === 0) { ans += cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } function bitCount(i: number): number { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
3,216
Lexicographically Smallest String After a Swap
Easy
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p> <p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;45320&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;43520&quot;</span></p> <p><strong>Explanation: </strong></p> <p><code>s[1] == &#39;5&#39;</code> and <code>s[2] == &#39;3&#39;</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;001&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of digits.</li> </ul>
Greedy; String
C++
class Solution { public: string getSmallestString(string s) { int n = s.length(); for (int i = 1; i < n; ++i) { char a = s[i - 1], b = s[i]; if (a > b && a % 2 == b % 2) { s[i - 1] = b; s[i] = a; break; } } return s; } };
3,216
Lexicographically Smallest String After a Swap
Easy
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p> <p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;45320&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;43520&quot;</span></p> <p><strong>Explanation: </strong></p> <p><code>s[1] == &#39;5&#39;</code> and <code>s[2] == &#39;3&#39;</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;001&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of digits.</li> </ul>
Greedy; String
Go
func getSmallestString(s string) string { cs := []byte(s) n := len(cs) for i := 1; i < n; i++ { a, b := cs[i-1], cs[i] if a > b && a%2 == b%2 { cs[i-1], cs[i] = b, a return string(cs) } } return s }
3,216
Lexicographically Smallest String After a Swap
Easy
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p> <p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;45320&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;43520&quot;</span></p> <p><strong>Explanation: </strong></p> <p><code>s[1] == &#39;5&#39;</code> and <code>s[2] == &#39;3&#39;</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;001&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of digits.</li> </ul>
Greedy; String
Java
class Solution { public String getSmallestString(String s) { char[] cs = s.toCharArray(); int n = cs.length; for (int i = 1; i < n; ++i) { char a = cs[i - 1], b = cs[i]; if (a > b && a % 2 == b % 2) { cs[i] = a; cs[i - 1] = b; return new String(cs); } } return s; } }
3,216
Lexicographically Smallest String After a Swap
Easy
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p> <p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;45320&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;43520&quot;</span></p> <p><strong>Explanation: </strong></p> <p><code>s[1] == &#39;5&#39;</code> and <code>s[2] == &#39;3&#39;</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;001&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of digits.</li> </ul>
Greedy; String
Python
class Solution: def getSmallestString(self, s: str) -> str: for i, (a, b) in enumerate(pairwise(map(ord, s))): if (a + b) % 2 == 0 and a > b: return s[:i] + s[i + 1] + s[i] + s[i + 2 :] return s
3,216
Lexicographically Smallest String After a Swap
Easy
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p> <p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;45320&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;43520&quot;</span></p> <p><strong>Explanation: </strong></p> <p><code>s[1] == &#39;5&#39;</code> and <code>s[2] == &#39;3&#39;</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;001&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of digits.</li> </ul>
Greedy; String
TypeScript
function getSmallestString(s: string): string { const n = s.length; const cs: string[] = s.split(''); for (let i = 1; i < n; ++i) { const a = cs[i - 1]; const b = cs[i]; if (a > b && +a % 2 === +b % 2) { cs[i - 1] = b; cs[i] = a; return cs.join(''); } } return s; }
3,217
Delete Nodes From Linked List Present in Array
Medium
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p> <p>&nbsp;</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], head = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p> <p>Remove the nodes with values 1, 2, and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p> <p>Remove the nodes with value 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p> <p>No node has value 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li>All elements in <code>nums</code> are unique.</li> <li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li> </ul>
Array; Hash Table; Linked List
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* modifiedList(vector<int>& nums, ListNode* head) { unordered_set<int> s(nums.begin(), nums.end()); ListNode* dummy = new ListNode(0, head); for (ListNode* pre = dummy; pre->next;) { if (s.count(pre->next->val)) { pre->next = pre->next->next; } else { pre = pre->next; } } return dummy->next; } };
3,217
Delete Nodes From Linked List Present in Array
Medium
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p> <p>&nbsp;</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], head = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p> <p>Remove the nodes with values 1, 2, and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p> <p>Remove the nodes with value 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p> <p>No node has value 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li>All elements in <code>nums</code> are unique.</li> <li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li> </ul>
Array; Hash Table; Linked List
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func modifiedList(nums []int, head *ListNode) *ListNode { s := map[int]bool{} for _, x := range nums { s[x] = true } dummy := &ListNode{Next: head} for pre := dummy; pre.Next != nil; { if s[pre.Next.Val] { pre.Next = pre.Next.Next } else { pre = pre.Next } } return dummy.Next }
3,217
Delete Nodes From Linked List Present in Array
Medium
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p> <p>&nbsp;</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], head = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p> <p>Remove the nodes with values 1, 2, and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p> <p>Remove the nodes with value 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p> <p>No node has value 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li>All elements in <code>nums</code> are unique.</li> <li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li> </ul>
Array; Hash Table; Linked List
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode modifiedList(int[] nums, ListNode head) { Set<Integer> s = new HashSet<>(); for (int x : nums) { s.add(x); } ListNode dummy = new ListNode(0, head); for (ListNode pre = dummy; pre.next != null;) { if (s.contains(pre.next.val)) { pre.next = pre.next.next; } else { pre = pre.next; } } return dummy.next; } }
3,217
Delete Nodes From Linked List Present in Array
Medium
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p> <p>&nbsp;</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], head = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p> <p>Remove the nodes with values 1, 2, and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p> <p>Remove the nodes with value 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p> <p>No node has value 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li>All elements in <code>nums</code> are unique.</li> <li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li> </ul>
Array; Hash Table; Linked List
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def modifiedList( self, nums: List[int], head: Optional[ListNode] ) -> Optional[ListNode]: s = set(nums) pre = dummy = ListNode(next=head) while pre.next: if pre.next.val in s: pre.next = pre.next.next else: pre = pre.next return dummy.next
3,217
Delete Nodes From Linked List Present in Array
Medium
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p> <p>&nbsp;</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], head = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p> <p>Remove the nodes with values 1, 2, and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p> <p>Remove the nodes with value 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p> <p>No node has value 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li>All elements in <code>nums</code> are unique.</li> <li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li> </ul>
Array; Hash Table; Linked List
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function modifiedList(nums: number[], head: ListNode | null): ListNode | null { const s: Set<number> = new Set(nums); const dummy = new ListNode(0, head); for (let pre = dummy; pre.next; ) { if (s.has(pre.next.val)) { pre.next = pre.next.next; } else { pre = pre.next; } } return dummy.next; }
3,218
Minimum Cost for Cutting Cake I
Medium
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 20</code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
C++
class Solution { public: int minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) { sort(horizontalCut.rbegin(), horizontalCut.rend()); sort(verticalCut.rbegin(), verticalCut.rend()); int ans = 0; int i = 0, j = 0; int h = 1, v = 1; while (i < m - 1 || j < n - 1) { if (j == n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) { ans += horizontalCut[i++] * v; h++; } else { ans += verticalCut[j++] * h; v++; } } return ans; } };
3,218
Minimum Cost for Cutting Cake I
Medium
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 20</code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Go
func minimumCost(m int, n int, horizontalCut []int, verticalCut []int) (ans int) { sort.Sort(sort.Reverse(sort.IntSlice(horizontalCut))) sort.Sort(sort.Reverse(sort.IntSlice(verticalCut))) i, j := 0, 0 h, v := 1, 1 for i < m-1 || j < n-1 { if j == n-1 || (i < m-1 && horizontalCut[i] > verticalCut[j]) { ans += horizontalCut[i] * v h++ i++ } else { ans += verticalCut[j] * h v++ j++ } } return }
3,218
Minimum Cost for Cutting Cake I
Medium
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 20</code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Java
class Solution { public int minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) { Arrays.sort(horizontalCut); Arrays.sort(verticalCut); int ans = 0; int i = m - 2, j = n - 2; int h = 1, v = 1; while (i >= 0 || j >= 0) { if (j < 0 || (i >= 0 && horizontalCut[i] > verticalCut[j])) { ans += horizontalCut[i--] * v; ++h; } else { ans += verticalCut[j--] * h; ++v; } } return ans; } }
3,218
Minimum Cost for Cutting Cake I
Medium
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 20</code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
Python
class Solution: def minimumCost( self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int] ) -> int: horizontalCut.sort(reverse=True) verticalCut.sort(reverse=True) ans = i = j = 0 h = v = 1 while i < m - 1 or j < n - 1: if j == n - 1 or (i < m - 1 and horizontalCut[i] > verticalCut[j]): ans += horizontalCut[i] * v h, i = h + 1, i + 1 else: ans += verticalCut[j] * h v, j = v + 1, j + 1 return ans
3,218
Minimum Cost for Cutting Cake I
Medium
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 20</code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Dynamic Programming; Sorting
TypeScript
function minimumCost(m: number, n: number, horizontalCut: number[], verticalCut: number[]): number { horizontalCut.sort((a, b) => b - a); verticalCut.sort((a, b) => b - a); let ans = 0; let [i, j] = [0, 0]; let [h, v] = [1, 1]; while (i < m - 1 || j < n - 1) { if (j === n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) { ans += horizontalCut[i] * v; h++; i++; } else { ans += verticalCut[j] * h; v++; j++; } } return ans; }
3,219
Minimum Cost for Cutting Cake II
Hard
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: long long minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) { sort(horizontalCut.rbegin(), horizontalCut.rend()); sort(verticalCut.rbegin(), verticalCut.rend()); long long ans = 0; int i = 0, j = 0; int h = 1, v = 1; while (i < m - 1 || j < n - 1) { if (j == n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) { ans += 1LL * horizontalCut[i++] * v; h++; } else { ans += 1LL * verticalCut[j++] * h; v++; } } return ans; } };
3,219
Minimum Cost for Cutting Cake II
Hard
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func minimumCost(m int, n int, horizontalCut []int, verticalCut []int) (ans int64) { sort.Sort(sort.Reverse(sort.IntSlice(horizontalCut))) sort.Sort(sort.Reverse(sort.IntSlice(verticalCut))) i, j := 0, 0 h, v := 1, 1 for i < m-1 || j < n-1 { if j == n-1 || (i < m-1 && horizontalCut[i] > verticalCut[j]) { ans += int64(horizontalCut[i] * v) h++ i++ } else { ans += int64(verticalCut[j] * h) v++ j++ } } return }
3,219
Minimum Cost for Cutting Cake II
Hard
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public long minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) { Arrays.sort(horizontalCut); Arrays.sort(verticalCut); long ans = 0; int i = m - 2, j = n - 2; int h = 1, v = 1; while (i >= 0 || j >= 0) { if (j < 0 || (i >= 0 && horizontalCut[i] > verticalCut[j])) { ans += 1L * horizontalCut[i--] * v; ++h; } else { ans += 1L * verticalCut[j--] * h; ++v; } } return ans; } }
3,219
Minimum Cost for Cutting Cake II
Hard
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minimumCost( self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int] ) -> int: horizontalCut.sort(reverse=True) verticalCut.sort(reverse=True) ans = i = j = 0 h = v = 1 while i < m - 1 or j < n - 1: if j == n - 1 or (i < m - 1 and horizontalCut[i] > verticalCut[j]): ans += horizontalCut[i] * v h, i = h + 1, i + 1 else: ans += verticalCut[j] * h v, j = v + 1, j + 1 return ans
3,219
Minimum Cost for Cutting Cake II
Hard
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p> <p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p> <ul> <li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li> <li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li> </ul> <p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p> <ol> <li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li> <li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li> </ol> <p>After the cut, the piece of cake is divided into two distinct pieces.</p> <p>The cost of a cut depends only on the initial cost of the line and does not change.</p> <p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p> <ul> <li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> <li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li> </ul> <p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform a cut on the horizontal line 0 with cost 7.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> <li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li> </ul> <p>The total cost is <code>7 + 4 + 4 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>horizontalCut.length == m - 1</code></li> <li><code>verticalCut.length == n - 1</code></li> <li><code>1 &lt;= horizontalCut[i], verticalCut[i] &lt;= 10<sup>3</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minimumCost(m: number, n: number, horizontalCut: number[], verticalCut: number[]): number { horizontalCut.sort((a, b) => b - a); verticalCut.sort((a, b) => b - a); let ans = 0; let [i, j] = [0, 0]; let [h, v] = [1, 1]; while (i < m - 1 || j < n - 1) { if (j === n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) { ans += horizontalCut[i] * v; h++; i++; } else { ans += verticalCut[j] * h; v++; j++; } } return ans; }
3,220
Odd and Even Transactions
Medium
<p>Table: <code>transactions</code></p> <pre> +------------------+------+ | Column Name | Type | +------------------+------+ | transaction_id | int | | amount | int | | transaction_date | date | +------------------+------+ The transactions_id column uniquely identifies each row in this table. Each row of this table contains the transaction id, amount and transaction date. </pre> <p>Write a solution to find the <strong>sum of amounts</strong> for <strong>odd</strong> and <strong>even</strong> transactions for each day. If there are no odd or even transactions for a specific date, display as <code>0</code>.</p> <p>Return <em>the result table ordered by</em> <code>transaction_date</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p><code>transactions</code> table:</p> <pre class="example-io"> +----------------+--------+------------------+ | transaction_id | amount | transaction_date | +----------------+--------+------------------+ | 1 | 150 | 2024-07-01 | | 2 | 200 | 2024-07-01 | | 3 | 75 | 2024-07-01 | | 4 | 300 | 2024-07-02 | | 5 | 50 | 2024-07-02 | | 6 | 120 | 2024-07-03 | +----------------+--------+------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------------+---------+----------+ | transaction_date | odd_sum | even_sum | +------------------+---------+----------+ | 2024-07-01 | 75 | 350 | | 2024-07-02 | 0 | 350 | | 2024-07-03 | 0 | 120 | +------------------+---------+----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For transaction dates: <ul> <li>2024-07-01: <ul> <li>Sum of amounts for odd transactions: 75</li> <li>Sum of amounts for even transactions: 150 + 200 = 350</li> </ul> </li> <li>2024-07-02: <ul> <li>Sum of amounts for odd transactions: 0</li> <li>Sum of amounts for even transactions: 300 + 50 = 350</li> </ul> </li> <li>2024-07-03: <ul> <li>Sum of amounts for odd transactions: 0</li> <li>Sum of amounts for even transactions: 120</li> </ul> </li> </ul> </li> </ul> <p><strong>Note:</strong> The output table is ordered by <code>transaction_date</code> in ascending order.</p> </div>
Database
Python
import pandas as pd def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame: transactions["odd_sum"] = transactions["amount"].where( transactions["amount"] % 2 == 1, 0 ) transactions["even_sum"] = transactions["amount"].where( transactions["amount"] % 2 == 0, 0 ) result = ( transactions.groupby("transaction_date") .agg(odd_sum=("odd_sum", "sum"), even_sum=("even_sum", "sum")) .reset_index() ) result = result.sort_values("transaction_date") return result
3,220
Odd and Even Transactions
Medium
<p>Table: <code>transactions</code></p> <pre> +------------------+------+ | Column Name | Type | +------------------+------+ | transaction_id | int | | amount | int | | transaction_date | date | +------------------+------+ The transactions_id column uniquely identifies each row in this table. Each row of this table contains the transaction id, amount and transaction date. </pre> <p>Write a solution to find the <strong>sum of amounts</strong> for <strong>odd</strong> and <strong>even</strong> transactions for each day. If there are no odd or even transactions for a specific date, display as <code>0</code>.</p> <p>Return <em>the result table ordered by</em> <code>transaction_date</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p><code>transactions</code> table:</p> <pre class="example-io"> +----------------+--------+------------------+ | transaction_id | amount | transaction_date | +----------------+--------+------------------+ | 1 | 150 | 2024-07-01 | | 2 | 200 | 2024-07-01 | | 3 | 75 | 2024-07-01 | | 4 | 300 | 2024-07-02 | | 5 | 50 | 2024-07-02 | | 6 | 120 | 2024-07-03 | +----------------+--------+------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------------+---------+----------+ | transaction_date | odd_sum | even_sum | +------------------+---------+----------+ | 2024-07-01 | 75 | 350 | | 2024-07-02 | 0 | 350 | | 2024-07-03 | 0 | 120 | +------------------+---------+----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For transaction dates: <ul> <li>2024-07-01: <ul> <li>Sum of amounts for odd transactions: 75</li> <li>Sum of amounts for even transactions: 150 + 200 = 350</li> </ul> </li> <li>2024-07-02: <ul> <li>Sum of amounts for odd transactions: 0</li> <li>Sum of amounts for even transactions: 300 + 50 = 350</li> </ul> </li> <li>2024-07-03: <ul> <li>Sum of amounts for odd transactions: 0</li> <li>Sum of amounts for even transactions: 120</li> </ul> </li> </ul> </li> </ul> <p><strong>Note:</strong> The output table is ordered by <code>transaction_date</code> in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT transaction_date, SUM(IF(amount % 2 = 1, amount, 0)) AS odd_sum, SUM(IF(amount % 2 = 0, amount, 0)) AS even_sum FROM transactions GROUP BY 1 ORDER BY 1;
3,221
Maximum Array Hopping Score II
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
C++
class Solution { public: long long maxScore(vector<int>& nums) { vector<int> stk; for (int i = 0; i < nums.size(); ++i) { while (stk.size() && nums[stk.back()] <= nums[i]) { stk.pop_back(); } stk.push_back(i); } long long ans = 0, i = 0; for (int j : stk) { ans += (j - i) * nums[j]; i = j; } return ans; } };
3,221
Maximum Array Hopping Score II
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Go
func maxScore(nums []int) (ans int64) { stk := []int{} for i, x := range nums { for len(stk) > 0 && nums[stk[len(stk)-1]] <= x { stk = stk[:len(stk)-1] } stk = append(stk, i) } i := 0 for _, j := range stk { ans += int64((j - i) * nums[j]) i = j } return }
3,221
Maximum Array Hopping Score II
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Java
class Solution { public long maxScore(int[] nums) { Deque<Integer> stk = new ArrayDeque<>(); for (int i = 0; i < nums.length; ++i) { while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { stk.pop(); } stk.push(i); } long ans = 0, i = 0; while (!stk.isEmpty()) { int j = stk.pollLast(); ans += (j - i) * nums[j]; i = j; } return ans; } }
3,221
Maximum Array Hopping Score II
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Python
class Solution: def maxScore(self, nums: List[int]) -> int: stk = [] for i, x in enumerate(nums): while stk and nums[stk[-1]] <= x: stk.pop() stk.append(i) ans = i = 0 for j in stk: ans += nums[j] * (j - i) i = j return ans
3,221
Maximum Array Hopping Score II
Medium
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p> <p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j &gt; i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p> <p>Return the <em>maximum score</em> you can get.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>There are two possible ways to reach the last element:</p> <ul> <li><code>0 -&gt; 1 -&gt; 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li> <li><code>0 -&gt; 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">42</span></p> <p><strong>Explanation:</strong></p> <p>We can do the hopping <code>0 -&gt; 4 -&gt; 6</code> with a score of&nbsp;<code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
TypeScript
function maxScore(nums: number[]): number { const stk: number[] = []; for (let i = 0; i < nums.length; ++i) { while (stk.length && nums[stk.at(-1)!] <= nums[i]) { stk.pop(); } stk.push(i); } let ans = 0; let i = 0; for (const j of stk) { ans += (j - i) * nums[j]; i = j; } return ans; }
3,222
Find the Winning Player in Coin Game
Easy
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p> <p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p> <p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Alice&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in a single turn:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Bob&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in 2 turns:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> <li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y &lt;= 100</code></li> </ul>
Math; Game Theory; Simulation
C++
class Solution { public: string losingPlayer(int x, int y) { int k = min(x / 2, y / 8); x -= k * 2; y -= k * 8; return x && y >= 4 ? "Alice" : "Bob"; } };
3,222
Find the Winning Player in Coin Game
Easy
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p> <p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p> <p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Alice&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in a single turn:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Bob&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in 2 turns:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> <li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y &lt;= 100</code></li> </ul>
Math; Game Theory; Simulation
Go
func losingPlayer(x int, y int) string { k := min(x/2, y/8) x -= 2 * k y -= 8 * k if x > 0 && y >= 4 { return "Alice" } return "Bob" }
3,222
Find the Winning Player in Coin Game
Easy
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p> <p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p> <p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Alice&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in a single turn:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Bob&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in 2 turns:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> <li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y &lt;= 100</code></li> </ul>
Math; Game Theory; Simulation
Java
class Solution { public String losingPlayer(int x, int y) { int k = Math.min(x / 2, y / 8); x -= k * 2; y -= k * 8; return x > 0 && y >= 4 ? "Alice" : "Bob"; } }
3,222
Find the Winning Player in Coin Game
Easy
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p> <p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p> <p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Alice&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in a single turn:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Bob&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in 2 turns:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> <li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y &lt;= 100</code></li> </ul>
Math; Game Theory; Simulation
Python
class Solution: def losingPlayer(self, x: int, y: int) -> str: k = min(x // 2, y // 8) x -= k * 2 y -= k * 8 return "Alice" if x and y >= 4 else "Bob"
3,222
Find the Winning Player in Coin Game
Easy
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p> <p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p> <p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Alice&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in a single turn:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;Bob&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The game ends in 2 turns:</p> <ul> <li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> <li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y &lt;= 100</code></li> </ul>
Math; Game Theory; Simulation
TypeScript
function losingPlayer(x: number, y: number): string { const k = Math.min((x / 2) | 0, (y / 8) | 0); x -= k * 2; y -= k * 8; return x && y >= 4 ? 'Alice' : 'Bob'; }