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,319
K-th Largest Perfect Subtree Size in Binary Tree
Medium
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p> <p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn&#39;t exist.</p> <p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p> <p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br /> The <code>2<sup>nd</sup></code> largest size is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 2000</code></li> <li><code>1 &lt;= k &lt;= 1024</code></li> </ul>
Tree; Depth-First Search; Binary Tree; Sorting
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private List<Integer> nums = new ArrayList<>(); public int kthLargestPerfectSubtree(TreeNode root, int k) { dfs(root); if (nums.size() < k) { return -1; } nums.sort(Comparator.reverseOrder()); return nums.get(k - 1); } private int dfs(TreeNode root) { if (root == null) { return 0; } int l = dfs(root.left); int r = dfs(root.right); if (l < 0 || l != r) { return -1; } int cnt = l + r + 1; nums.add(cnt); return cnt; } }
3,319
K-th Largest Perfect Subtree Size in Binary Tree
Medium
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p> <p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn&#39;t exist.</p> <p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p> <p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br /> The <code>2<sup>nd</sup></code> largest size is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 2000</code></li> <li><code>1 &lt;= k &lt;= 1024</code></li> </ul>
Tree; Depth-First Search; Binary Tree; Sorting
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l, r = dfs(root.left), dfs(root.right) if l < 0 or l != r: return -1 cnt = l + r + 1 nums.append(cnt) return cnt nums = [] dfs(root) if len(nums) < k: return -1 nums.sort(reverse=True) return nums[k - 1]
3,319
K-th Largest Perfect Subtree Size in Binary Tree
Medium
<p>You are given the <code>root</code> of a <strong>binary tree</strong> and an integer <code>k</code>.</p> <p>Return an integer denoting the size of the <code>k<sup>th</sup></code> <strong>largest<em> </em>perfect binary</strong><em> </em><span data-keyword="subtree">subtree</span>, or <code>-1</code> if it doesn&#39;t exist.</p> <p>A <strong>perfect binary tree</strong> is a tree where all leaves are on the same level, and every parent has two children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmpresl95rp-1.png" style="width: 400px; height: 173px;" /></p> <p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are <code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br /> The <code>2<sup>nd</sup></code> largest size is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,4,5,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp_s508x9e-1.png" style="width: 300px; height: 189px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">root = [1,2,3,null,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3319.K-th%20Largest%20Perfect%20Subtree%20Size%20in%20Binary%20Tree/images/tmp74xnmpj4-1.png" style="width: 250px; height: 225px;" /></p> <p>The sizes of the perfect binary subtrees in non-increasing order are <code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 2000</code></li> <li><code>1 &lt;= k &lt;= 1024</code></li> </ul>
Tree; Depth-First Search; Binary Tree; Sorting
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function kthLargestPerfectSubtree(root: TreeNode | null, k: number): number { const nums: number[] = []; const dfs = (root: TreeNode | null): number => { if (!root) { return 0; } const l = dfs(root.left); const r = dfs(root.right); if (l < 0 || l !== r) { return -1; } const cnt = l + r + 1; nums.push(cnt); return cnt; }; dfs(root); if (nums.length < k) { return -1; } return nums.sort((a, b) => b - a)[k - 1]; }
3,320
Count The Number of Winning Sequences
Hard
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p> <ul> <li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li> <li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li> <li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li> <li>If both players summon the same creature, no player is awarded a point.</li> </ul> <p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, and <code>&#39;E&#39;</code>, representing the sequence of creatures Alice will summon in each round:</p> <ul> <li>If <code>s[i] == &#39;F&#39;</code>, Alice summons a Fire Dragon.</li> <li>If <code>s[i] == &#39;W&#39;</code>, Alice summons a Water Serpent.</li> <li>If <code>s[i] == &#39;E&#39;</code>, Alice summons an Earth Golem.</li> </ul> <p>Bob&rsquo;s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p> <p>Return the number of distinct sequences Bob can use to beat Alice.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FFF&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;WFW&quot;</code>, <code>&quot;FWF&quot;</code>, or <code>&quot;WEW&quot;</code>. Note that other winning sequences like <code>&quot;WWE&quot;</code> or <code>&quot;EWW&quot;</code> are invalid since Bob cannot make the same move twice in a row.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FWEFW&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p><w>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;FWFWF&quot;</code>, <code>&quot;FWFWE&quot;</code>, <code>&quot;FWEFE&quot;</code>, <code>&quot;FWEWE&quot;</code>, <code>&quot;FEFWF&quot;</code>, <code>&quot;FEFWE&quot;</code>, <code>&quot;FEFEW&quot;</code>, <code>&quot;FEWFE&quot;</code>, <code>&quot;WFEFE&quot;</code>, <code>&quot;WFEWE&quot;</code>, <code>&quot;WEFWF&quot;</code>, <code>&quot;WEFWE&quot;</code>, <code>&quot;WEFEF&quot;</code>, <code>&quot;WEFEW&quot;</code>, <code>&quot;WEWFW&quot;</code>, <code>&quot;WEWFE&quot;</code>, <code>&quot;EWFWE&quot;</code>, or <code>&quot;EWEWE&quot;</code>.</w></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is one of <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, or <code>&#39;E&#39;</code>.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int countWinningSequences(string s) { int n = s.size(); int d[26]{}; d['W' - 'A'] = 1; d['E' - 'A'] = 2; int f[n][n + n + 1][4]; memset(f, -1, sizeof(f)); auto calc = [](int x, int y) -> int { if (x == y) { return 0; } if (x < y) { return x == 0 && y == 2 ? 1 : -1; } return x == 2 && y == 0 ? -1 : 1; }; const int mod = 1e9 + 7; auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (n - i <= j - n) { return 0; } if (i >= n) { return j - n < 0 ? 1 : 0; } if (f[i][j][k] != -1) { return f[i][j][k]; } int ans = 0; for (int l = 0; l < 3; ++l) { if (l == k) { continue; } ans = (ans + dfs(i + 1, j + calc(d[s[i] - 'A'], l), l)) % mod; } return f[i][j][k] = ans; }; return dfs(0, n, 3); } };
3,320
Count The Number of Winning Sequences
Hard
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p> <ul> <li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li> <li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li> <li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li> <li>If both players summon the same creature, no player is awarded a point.</li> </ul> <p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, and <code>&#39;E&#39;</code>, representing the sequence of creatures Alice will summon in each round:</p> <ul> <li>If <code>s[i] == &#39;F&#39;</code>, Alice summons a Fire Dragon.</li> <li>If <code>s[i] == &#39;W&#39;</code>, Alice summons a Water Serpent.</li> <li>If <code>s[i] == &#39;E&#39;</code>, Alice summons an Earth Golem.</li> </ul> <p>Bob&rsquo;s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p> <p>Return the number of distinct sequences Bob can use to beat Alice.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FFF&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;WFW&quot;</code>, <code>&quot;FWF&quot;</code>, or <code>&quot;WEW&quot;</code>. Note that other winning sequences like <code>&quot;WWE&quot;</code> or <code>&quot;EWW&quot;</code> are invalid since Bob cannot make the same move twice in a row.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FWEFW&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p><w>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;FWFWF&quot;</code>, <code>&quot;FWFWE&quot;</code>, <code>&quot;FWEFE&quot;</code>, <code>&quot;FWEWE&quot;</code>, <code>&quot;FEFWF&quot;</code>, <code>&quot;FEFWE&quot;</code>, <code>&quot;FEFEW&quot;</code>, <code>&quot;FEWFE&quot;</code>, <code>&quot;WFEFE&quot;</code>, <code>&quot;WFEWE&quot;</code>, <code>&quot;WEFWF&quot;</code>, <code>&quot;WEFWE&quot;</code>, <code>&quot;WEFEF&quot;</code>, <code>&quot;WEFEW&quot;</code>, <code>&quot;WEWFW&quot;</code>, <code>&quot;WEWFE&quot;</code>, <code>&quot;EWFWE&quot;</code>, or <code>&quot;EWEWE&quot;</code>.</w></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is one of <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, or <code>&#39;E&#39;</code>.</li> </ul>
String; Dynamic Programming
Go
func countWinningSequences(s string) int { const mod int = 1e9 + 7 d := [26]int{} d['W'-'A'] = 1 d['E'-'A'] = 2 n := len(s) f := make([][][4]int, n) for i := range f { f[i] = make([][4]int, n+n+1) for j := range f[i] { for k := range f[i][j] { f[i][j][k] = -1 } } } calc := func(x, y int) int { if x == y { return 0 } if x < y { if x == 0 && y == 2 { return 1 } return -1 } if x == 2 && y == 0 { return -1 } return 1 } var dfs func(int, int, int) int dfs = func(i, j, k int) int { if n-i <= j-n { return 0 } if i >= n { if j-n < 0 { return 1 } return 0 } if v := f[i][j][k]; v != -1 { return v } ans := 0 for l := 0; l < 3; l++ { if l == k { continue } ans = (ans + dfs(i+1, j+calc(d[s[i]-'A'], l), l)) % mod } f[i][j][k] = ans return ans } return dfs(0, n, 3) }
3,320
Count The Number of Winning Sequences
Hard
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p> <ul> <li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li> <li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li> <li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li> <li>If both players summon the same creature, no player is awarded a point.</li> </ul> <p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, and <code>&#39;E&#39;</code>, representing the sequence of creatures Alice will summon in each round:</p> <ul> <li>If <code>s[i] == &#39;F&#39;</code>, Alice summons a Fire Dragon.</li> <li>If <code>s[i] == &#39;W&#39;</code>, Alice summons a Water Serpent.</li> <li>If <code>s[i] == &#39;E&#39;</code>, Alice summons an Earth Golem.</li> </ul> <p>Bob&rsquo;s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p> <p>Return the number of distinct sequences Bob can use to beat Alice.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FFF&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;WFW&quot;</code>, <code>&quot;FWF&quot;</code>, or <code>&quot;WEW&quot;</code>. Note that other winning sequences like <code>&quot;WWE&quot;</code> or <code>&quot;EWW&quot;</code> are invalid since Bob cannot make the same move twice in a row.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FWEFW&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p><w>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;FWFWF&quot;</code>, <code>&quot;FWFWE&quot;</code>, <code>&quot;FWEFE&quot;</code>, <code>&quot;FWEWE&quot;</code>, <code>&quot;FEFWF&quot;</code>, <code>&quot;FEFWE&quot;</code>, <code>&quot;FEFEW&quot;</code>, <code>&quot;FEWFE&quot;</code>, <code>&quot;WFEFE&quot;</code>, <code>&quot;WFEWE&quot;</code>, <code>&quot;WEFWF&quot;</code>, <code>&quot;WEFWE&quot;</code>, <code>&quot;WEFEF&quot;</code>, <code>&quot;WEFEW&quot;</code>, <code>&quot;WEWFW&quot;</code>, <code>&quot;WEWFE&quot;</code>, <code>&quot;EWFWE&quot;</code>, or <code>&quot;EWEWE&quot;</code>.</w></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is one of <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, or <code>&#39;E&#39;</code>.</li> </ul>
String; Dynamic Programming
Java
class Solution { private int n; private char[] s; private int[] d = new int[26]; private Integer[][][] f; private final int mod = (int) 1e9 + 7; public int countWinningSequences(String s) { d['W' - 'A'] = 1; d['E' - 'A'] = 2; this.s = s.toCharArray(); n = this.s.length; f = new Integer[n][n + n + 1][4]; return dfs(0, n, 3); } private int dfs(int i, int j, int k) { if (n - i <= j - n) { return 0; } if (i >= n) { return j - n < 0 ? 1 : 0; } if (f[i][j][k] != null) { return f[i][j][k]; } int ans = 0; for (int l = 0; l < 3; ++l) { if (l == k) { continue; } ans = (ans + dfs(i + 1, j + calc(d[s[i] - 'A'], l), l)) % mod; } return f[i][j][k] = ans; } private int calc(int x, int y) { if (x == y) { return 0; } if (x < y) { return x == 0 && y == 2 ? 1 : -1; } return x == 2 && y == 0 ? -1 : 1; } }
3,320
Count The Number of Winning Sequences
Hard
<p>Alice and Bob are playing a fantasy battle game consisting of <code>n</code> rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players <strong>simultaneously</strong> summon their creature and are awarded points as follows:</p> <ul> <li>If one player summons a Fire Dragon and the other summons an Earth Golem, the player who summoned the <strong>Fire Dragon</strong> is awarded a point.</li> <li>If one player summons a Water Serpent and the other summons a Fire Dragon, the player who summoned the <strong>Water Serpent</strong> is awarded a point.</li> <li>If one player summons an Earth Golem and the other summons a Water Serpent, the player who summoned the <strong>Earth Golem</strong> is awarded a point.</li> <li>If both players summon the same creature, no player is awarded a point.</li> </ul> <p>You are given a string <code>s</code> consisting of <code>n</code> characters <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, and <code>&#39;E&#39;</code>, representing the sequence of creatures Alice will summon in each round:</p> <ul> <li>If <code>s[i] == &#39;F&#39;</code>, Alice summons a Fire Dragon.</li> <li>If <code>s[i] == &#39;W&#39;</code>, Alice summons a Water Serpent.</li> <li>If <code>s[i] == &#39;E&#39;</code>, Alice summons an Earth Golem.</li> </ul> <p>Bob&rsquo;s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob <em>beats</em> Alice if the total number of points awarded to Bob after <code>n</code> rounds is <strong>strictly greater</strong> than the points awarded to Alice.</p> <p>Return the number of distinct sequences Bob can use to beat Alice.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FFF&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;WFW&quot;</code>, <code>&quot;FWF&quot;</code>, or <code>&quot;WEW&quot;</code>. Note that other winning sequences like <code>&quot;WWE&quot;</code> or <code>&quot;EWW&quot;</code> are invalid since Bob cannot make the same move twice in a row.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;FWEFW&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p><w>Bob can beat Alice by making one of the following sequences of moves: <code>&quot;FWFWF&quot;</code>, <code>&quot;FWFWE&quot;</code>, <code>&quot;FWEFE&quot;</code>, <code>&quot;FWEWE&quot;</code>, <code>&quot;FEFWF&quot;</code>, <code>&quot;FEFWE&quot;</code>, <code>&quot;FEFEW&quot;</code>, <code>&quot;FEWFE&quot;</code>, <code>&quot;WFEFE&quot;</code>, <code>&quot;WFEWE&quot;</code>, <code>&quot;WEFWF&quot;</code>, <code>&quot;WEFWE&quot;</code>, <code>&quot;WEFEF&quot;</code>, <code>&quot;WEFEW&quot;</code>, <code>&quot;WEWFW&quot;</code>, <code>&quot;WEWFE&quot;</code>, <code>&quot;EWFWE&quot;</code>, or <code>&quot;EWEWE&quot;</code>.</w></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s[i]</code> is one of <code>&#39;F&#39;</code>, <code>&#39;W&#39;</code>, or <code>&#39;E&#39;</code>.</li> </ul>
String; Dynamic Programming
Python
class Solution: def countWinningSequences(self, s: str) -> int: def calc(x: int, y: int) -> int: if x == y: return 0 if x < y: return 1 if x == 0 and y == 2 else -1 return -1 if x == 2 and y == 0 else 1 @cache def dfs(i: int, j: int, k: int) -> int: if len(s) - i <= j: return 0 if i >= len(s): return int(j < 0) res = 0 for l in range(3): if l == k: continue res = (res + dfs(i + 1, j + calc(d[s[i]], l), l)) % mod return res mod = 10**9 + 7 d = {"F": 0, "W": 1, "E": 2} ans = dfs(0, 0, -1) dfs.cache_clear() return ans
3,321
Find X-Sum of All K-Long Subarrays II
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p> <p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p> <ul> <li>Count the occurrences of all elements in the array.</li> <li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li> <li>Calculate the sum of the resulting array.</li> </ul> <p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p> <p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p> <p>&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,2,2,3,4,2,3], k = 6, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li> <li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li> <li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p> <p><strong>Explanation:</strong></p> <p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == n</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= x &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
C++
class Solution { public: vector<long long> findXSum(vector<int>& nums, int k, int x) { using pii = pair<int, int>; set<pii> l, r; long long s = 0; unordered_map<int, int> cnt; auto add = [&](int v) { if (cnt[v] == 0) { return; } pii p = {cnt[v], v}; if (!l.empty() && p > *l.begin()) { s += 1LL * p.first * p.second; l.insert(p); } else { r.insert(p); } }; auto remove = [&](int v) { if (cnt[v] == 0) { return; } pii p = {cnt[v], v}; auto it = l.find(p); if (it != l.end()) { s -= 1LL * p.first * p.second; l.erase(it); } else { r.erase(p); } }; vector<long long> ans; for (int i = 0; i < nums.size(); ++i) { remove(nums[i]); ++cnt[nums[i]]; add(nums[i]); int j = i - k + 1; if (j < 0) { continue; } while (!r.empty() && l.size() < x) { pii p = *r.rbegin(); s += 1LL * p.first * p.second; r.erase(p); l.insert(p); } while (l.size() > x) { pii p = *l.begin(); s -= 1LL * p.first * p.second; l.erase(p); r.insert(p); } ans.push_back(s); remove(nums[j]); --cnt[nums[j]]; add(nums[j]); } return ans; } };
3,321
Find X-Sum of All K-Long Subarrays II
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p> <p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p> <ul> <li>Count the occurrences of all elements in the array.</li> <li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li> <li>Calculate the sum of the resulting array.</li> </ul> <p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p> <p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p> <p>&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,2,2,3,4,2,3], k = 6, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li> <li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li> <li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p> <p><strong>Explanation:</strong></p> <p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == n</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= x &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
Java
class Solution { private TreeSet<int[]> l = new TreeSet<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); private TreeSet<int[]> r = new TreeSet<>(l.comparator()); private Map<Integer, Integer> cnt = new HashMap<>(); private long s; public long[] findXSum(int[] nums, int k, int x) { int n = nums.length; long[] ans = new long[n - k + 1]; for (int i = 0; i < n; ++i) { int v = nums[i]; remove(v); cnt.merge(v, 1, Integer::sum); add(v); int j = i - k + 1; if (j < 0) { continue; } while (!r.isEmpty() && l.size() < x) { var p = r.pollLast(); s += 1L * p[0] * p[1]; l.add(p); } while (l.size() > x) { var p = l.pollFirst(); s -= 1L * p[0] * p[1]; r.add(p); } ans[j] = s; remove(nums[j]); cnt.merge(nums[j], -1, Integer::sum); add(nums[j]); } return ans; } private void remove(int v) { if (!cnt.containsKey(v)) { return; } var p = new int[] {cnt.get(v), v}; if (l.contains(p)) { l.remove(p); s -= 1L * p[0] * p[1]; } else { r.remove(p); } } private void add(int v) { if (!cnt.containsKey(v)) { return; } var p = new int[] {cnt.get(v), v}; if (!l.isEmpty() && l.comparator().compare(l.first(), p) < 0) { l.add(p); s += 1L * p[0] * p[1]; } else { r.add(p); } } }
3,321
Find X-Sum of All K-Long Subarrays II
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers and two integers <code>k</code> and <code>x</code>.</p> <p>The <strong>x-sum</strong> of an array is calculated by the following procedure:</p> <ul> <li>Count the occurrences of all elements in the array.</li> <li>Keep only the occurrences of the top <code>x</code> most frequent elements. If two elements have the same number of occurrences, the element with the <strong>bigger</strong> value is considered more frequent.</li> <li>Calculate the sum of the resulting array.</li> </ul> <p><strong>Note</strong> that if an array has less than <code>x</code> distinct elements, its <strong>x-sum</strong> is the sum of the array.</p> <p>Return an integer array <code>answer</code> of length <code>n - k + 1</code> where <code>answer[i]</code> is the <strong>x-sum</strong> of the <span data-keyword="subarray-nonempty">subarray</span> <code>nums[i..i + k - 1]</code>.</p> <p>&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,2,2,3,4,2,3], k = 6, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[6,10,12]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For subarray <code>[1, 1, 2, 2, 3, 4]</code>, only elements 1 and 2 will be kept in the resulting array. Hence, <code>answer[0] = 1 + 1 + 2 + 2</code>.</li> <li>For subarray <code>[1, 2, 2, 3, 4, 2]</code>, only elements 2 and 4 will be kept in the resulting array. Hence, <code>answer[1] = 2 + 2 + 2 + 4</code>. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.</li> <li>For subarray <code>[2, 2, 3, 4, 2, 3]</code>, only elements 2 and 3 are kept in the resulting array. Hence, <code>answer[2] = 2 + 2 + 2 + 3 + 3</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,8,7,8,7,5], k = 2, x = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[11,15,15,15,12]</span></p> <p><strong>Explanation:</strong></p> <p>Since <code>k == x</code>, <code>answer[i]</code> is equal to the sum of the subarray <code>nums[i..i + k - 1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == n</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= x &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
Python
class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: def add(v: int): if cnt[v] == 0: return p = (cnt[v], v) if l and p > l[0]: nonlocal s s += p[0] * p[1] l.add(p) else: r.add(p) def remove(v: int): if cnt[v] == 0: return p = (cnt[v], v) if p in l: nonlocal s s -= p[0] * p[1] l.remove(p) else: r.remove(p) l = SortedList() r = SortedList() cnt = Counter() s = 0 n = len(nums) ans = [0] * (n - k + 1) for i, v in enumerate(nums): remove(v) cnt[v] += 1 add(v) j = i - k + 1 if j < 0: continue while r and len(l) < x: p = r.pop() l.add(p) s += p[0] * p[1] while len(l) > x: p = l.pop(0) s -= p[0] * p[1] r.add(p) ans[j] = s remove(nums[j]) cnt[nums[j]] -= 1 add(nums[j]) return ans
3,322
Premier League Table Ranking III
Medium
<p>Table: <code>SeasonStats</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | season_id | int | | team_id | int | | team_name | varchar | | matches_played | int | | wins | int | | draws | int | | losses | int | | goals_for | int | | goals_against | int | +------------------+---------+ (season_id, team_id) is the unique key for this table. This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season. </pre> <p>Write a solution to calculate the <strong>points</strong>, <strong>goal difference</strong>, and <b>position&nbsp;</b>for <strong>each team</strong> in <strong>each season</strong>. The position ranking should be determined as follows:</p> <ul> <li>Teams are first ranked by their total points (highest to lowest)</li> <li>If points are tied, teams are then ranked by their goal difference (highest to lowest)</li> <li>If goal difference is also tied, teams are then ranked alphabetically by team name</li> </ul> <p>Points are calculated as follows:</p> <ul> <li><code>3</code> points for a <strong>win</strong></li> <li><code>1</code> point for a <strong>draw</strong></li> <li><code>0</code> points for a <strong>loss</strong></li> </ul> <p>Goal difference is calculated as: <code>goals_for - goals_against</code></p> <p>Return <em>the result table ordered&nbsp;by</em> <code>season_id</code> <em>in <strong>ascending</strong> order, then by</em>&nbsp;<font face="monospace">position&nbsp;</font><em>in <strong>ascending</strong> order, and finally by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p> <p>The query result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <p><strong>Input:</strong></p> <p><code>SeasonStats</code> table:</p> <pre> +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ | season_id | team_id | team_name | matches_played | wins | draws | losses | goals_for | goals_against | +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ | 2021 | 1 | Manchester City | 38 | 29 | 6 | 3 | 99 | 26 | | 2021 | 2 | Liverpool | 38 | 28 | 8 | 2 | 94 | 26 | | 2021 | 3 | Chelsea | 38 | 21 | 11 | 6 | 76 | 33 | | 2021 | 4 | Tottenham | 38 | 22 | 5 | 11 | 69 | 40 | | 2021 | 5 | Arsenal | 38 | 22 | 3 | 13 | 61 | 48 | | 2022 | 1 | Manchester City | 38 | 28 | 5 | 5 | 94 | 33 | | 2022 | 2 | Arsenal | 38 | 26 | 6 | 6 | 88 | 43 | | 2022 | 3 | Manchester United | 38 | 23 | 6 | 9 | 58 | 43 | | 2022 | 4 | Newcastle | 38 | 19 | 14 | 5 | 68 | 33 | | 2022 | 5 | Liverpool | 38 | 19 | 10 | 9 | 75 | 47 | +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ </pre> <p><strong>Output:</strong></p> <pre> +------------+---------+-------------------+--------+-----------------+----------+ | season_id | team_id | team_name | points | goal_difference | position | +------------+---------+-------------------+--------+-----------------+----------+ | 2021 | 1 | Manchester City | 93 | 73 | 1 | | 2021 | 2 | Liverpool | 92 | 68 | 2 | | 2021 | 3 | Chelsea | 74 | 43 | 3 | | 2021 | 4 | Tottenham | 71 | 29 | 4 | | 2021 | 5 | Arsenal | 69 | 13 | 5 | | 2022 | 1 | Manchester City | 89 | 61 | 1 | | 2022 | 2 | Arsenal | 84 | 45 | 2 | | 2022 | 3 | Manchester United | 75 | 15 | 3 | | 2022 | 4 | Newcastle | 71 | 35 | 4 | | 2022 | 5 | Liverpool | 67 | 28 | 5 | +------------+---------+-------------------+--------+-----------------+----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For the 2021 season: <ul> <li>Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).</li> <li>Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).</li> <li>Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).</li> <li>Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).</li> <li>Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).</li> </ul> </li> <li>For the 2022 season: <ul> <li>Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).</li> <li>Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).</li> <li>Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).</li> <li>Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).</li> <li>Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).</li> </ul> </li> <li>The teams are ranked first by points, then by goal difference, and finally by team name.</li> <li>The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.</li> </ul>
Database
Python
import pandas as pd def process_team_standings(season_stats: pd.DataFrame) -> pd.DataFrame: season_stats["points"] = season_stats["wins"] * 3 + season_stats["draws"] season_stats["goal_difference"] = ( season_stats["goals_for"] - season_stats["goals_against"] ) season_stats = season_stats.sort_values( ["season_id", "points", "goal_difference", "team_name"], ascending=[True, False, False, True], ) season_stats["position"] = season_stats.groupby("season_id").cumcount() + 1 return season_stats[ ["season_id", "team_id", "team_name", "points", "goal_difference", "position"] ]
3,322
Premier League Table Ranking III
Medium
<p>Table: <code>SeasonStats</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | season_id | int | | team_id | int | | team_name | varchar | | matches_played | int | | wins | int | | draws | int | | losses | int | | goals_for | int | | goals_against | int | +------------------+---------+ (season_id, team_id) is the unique key for this table. This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season. </pre> <p>Write a solution to calculate the <strong>points</strong>, <strong>goal difference</strong>, and <b>position&nbsp;</b>for <strong>each team</strong> in <strong>each season</strong>. The position ranking should be determined as follows:</p> <ul> <li>Teams are first ranked by their total points (highest to lowest)</li> <li>If points are tied, teams are then ranked by their goal difference (highest to lowest)</li> <li>If goal difference is also tied, teams are then ranked alphabetically by team name</li> </ul> <p>Points are calculated as follows:</p> <ul> <li><code>3</code> points for a <strong>win</strong></li> <li><code>1</code> point for a <strong>draw</strong></li> <li><code>0</code> points for a <strong>loss</strong></li> </ul> <p>Goal difference is calculated as: <code>goals_for - goals_against</code></p> <p>Return <em>the result table ordered&nbsp;by</em> <code>season_id</code> <em>in <strong>ascending</strong> order, then by</em>&nbsp;<font face="monospace">position&nbsp;</font><em>in <strong>ascending</strong> order, and finally by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p> <p>The query result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <p><strong>Input:</strong></p> <p><code>SeasonStats</code> table:</p> <pre> +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ | season_id | team_id | team_name | matches_played | wins | draws | losses | goals_for | goals_against | +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ | 2021 | 1 | Manchester City | 38 | 29 | 6 | 3 | 99 | 26 | | 2021 | 2 | Liverpool | 38 | 28 | 8 | 2 | 94 | 26 | | 2021 | 3 | Chelsea | 38 | 21 | 11 | 6 | 76 | 33 | | 2021 | 4 | Tottenham | 38 | 22 | 5 | 11 | 69 | 40 | | 2021 | 5 | Arsenal | 38 | 22 | 3 | 13 | 61 | 48 | | 2022 | 1 | Manchester City | 38 | 28 | 5 | 5 | 94 | 33 | | 2022 | 2 | Arsenal | 38 | 26 | 6 | 6 | 88 | 43 | | 2022 | 3 | Manchester United | 38 | 23 | 6 | 9 | 58 | 43 | | 2022 | 4 | Newcastle | 38 | 19 | 14 | 5 | 68 | 33 | | 2022 | 5 | Liverpool | 38 | 19 | 10 | 9 | 75 | 47 | +------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+ </pre> <p><strong>Output:</strong></p> <pre> +------------+---------+-------------------+--------+-----------------+----------+ | season_id | team_id | team_name | points | goal_difference | position | +------------+---------+-------------------+--------+-----------------+----------+ | 2021 | 1 | Manchester City | 93 | 73 | 1 | | 2021 | 2 | Liverpool | 92 | 68 | 2 | | 2021 | 3 | Chelsea | 74 | 43 | 3 | | 2021 | 4 | Tottenham | 71 | 29 | 4 | | 2021 | 5 | Arsenal | 69 | 13 | 5 | | 2022 | 1 | Manchester City | 89 | 61 | 1 | | 2022 | 2 | Arsenal | 84 | 45 | 2 | | 2022 | 3 | Manchester United | 75 | 15 | 3 | | 2022 | 4 | Newcastle | 71 | 35 | 4 | | 2022 | 5 | Liverpool | 67 | 28 | 5 | +------------+---------+-------------------+--------+-----------------+----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For the 2021 season: <ul> <li>Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).</li> <li>Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).</li> <li>Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).</li> <li>Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).</li> <li>Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).</li> </ul> </li> <li>For the 2022 season: <ul> <li>Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).</li> <li>Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).</li> <li>Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).</li> <li>Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).</li> <li>Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).</li> </ul> </li> <li>The teams are ranked first by points, then by goal difference, and finally by team name.</li> <li>The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.</li> </ul>
Database
SQL
SELECT season_id, team_id, team_name, wins * 3 + draws points, goals_for - goals_against goal_difference, RANK() OVER ( PARTITION BY season_id ORDER BY wins * 3 + draws DESC, goals_for - goals_against DESC, team_name ) position FROM SeasonStats ORDER BY 1, 6, 3;
3,323
Minimize Connected Groups by Inserting Interval
Medium
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p> <p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p> <ul> <li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li> <li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li> </ul> <p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p> <ul> <li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li> <li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li> </ul> <p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li> <li><code>1 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
C++
class Solution { public: int minConnectedGroups(vector<vector<int>>& intervals, int k) { sort(intervals.begin(), intervals.end()); vector<vector<int>> merged; for (const auto& interval : intervals) { int s = interval[0], e = interval[1]; if (merged.empty() || merged.back()[1] < s) { merged.emplace_back(interval); } else { merged.back()[1] = max(merged.back()[1], e); } } int ans = merged.size(); for (int i = 0; i < merged.size(); ++i) { auto& interval = merged[i]; int j = lower_bound(merged.begin(), merged.end(), vector<int>{interval[1] + k + 1, 0}) - merged.begin(); ans = min(ans, (int) merged.size() - (j - i - 1)); } return ans; } };
3,323
Minimize Connected Groups by Inserting Interval
Medium
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p> <p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p> <ul> <li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li> <li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li> </ul> <p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p> <ul> <li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li> <li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li> </ul> <p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li> <li><code>1 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Go
func minConnectedGroups(intervals [][]int, k int) int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) merged := [][]int{} for _, interval := range intervals { s, e := interval[0], interval[1] if len(merged) == 0 || merged[len(merged)-1][1] < s { merged = append(merged, interval) } else { merged[len(merged)-1][1] = max(merged[len(merged)-1][1], e) } } ans := len(merged) for i, interval := range merged { j := sort.Search(len(merged), func(j int) bool { return merged[j][0] >= interval[1]+k+1 }) ans = min(ans, len(merged)-(j-i-1)) } return ans }
3,323
Minimize Connected Groups by Inserting Interval
Medium
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p> <p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p> <ul> <li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li> <li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li> </ul> <p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p> <ul> <li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li> <li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li> </ul> <p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li> <li><code>1 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Java
class Solution { public int minConnectedGroups(int[][] intervals, int k) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); List<int[]> merged = new ArrayList<>(); merged.add(intervals[0]); for (int i = 1; i < intervals.length; i++) { int[] interval = intervals[i]; int[] last = merged.get(merged.size() - 1); if (last[1] < interval[0]) { merged.add(interval); } else { last[1] = Math.max(last[1], interval[1]); } } int ans = merged.size(); for (int i = 0; i < merged.size(); i++) { int[] interval = merged.get(i); int j = binarySearch(merged, interval[1] + k + 1); ans = Math.min(ans, merged.size() - (j - i - 1)); } return ans; } private int binarySearch(List<int[]> nums, int x) { int l = 0, r = nums.size(); while (l < r) { int mid = (l + r) >> 1; if (nums.get(mid)[0] >= x) { r = mid; } else { l = mid + 1; } } return l; } }
3,323
Minimize Connected Groups by Inserting Interval
Medium
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p> <p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p> <ul> <li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li> <li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li> </ul> <p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p> <ul> <li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li> <li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li> </ul> <p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li> <li><code>1 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Python
class Solution: def minConnectedGroups(self, intervals: List[List[int]], k: int) -> int: intervals.sort() merged = [intervals[0]] for s, e in intervals[1:]: if merged[-1][1] < s: merged.append([s, e]) else: merged[-1][1] = max(merged[-1][1], e) ans = len(merged) for i, (_, e) in enumerate(merged): j = bisect_left(merged, [e + k + 1, 0]) ans = min(ans, len(merged) - (j - i - 1)) return ans
3,323
Minimize Connected Groups by Inserting Interval
Medium
<p>You are given a 2D array <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represents the start and the end of interval <code>i</code>. You are also given an integer <code>k</code>.</p> <p>You must add <strong>exactly one</strong> new interval <code>[start<sub>new</sub>, end<sub>new</sub>]</code> to the array such that:</p> <ul> <li>The length of the new interval, <code>end<sub>new</sub> - start<sub>new</sub></code>, is at most <code>k</code>.</li> <li>After adding, the number of <strong>connected groups</strong> in <code>intervals</code> is <strong>minimized</strong>.</li> </ul> <p>A <strong>connected group</strong> of intervals is a maximal collection of intervals that, when considered together, cover a continuous range from the smallest point to the largest point with no gaps between them. Here are some examples:</p> <ul> <li>A group of intervals <code>[[1, 2], [2, 5], [3, 3]]</code> is connected because together they cover the range from 1 to 5 without any gaps.</li> <li>However, a group of intervals <code>[[1, 2], [3, 4]]</code> is not connected because the segment <code>(2, 3)</code> is not covered.</li> </ul> <p>Return the <strong>minimum</strong> number of connected groups after adding <strong>exactly one</strong> new interval to the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[1,3],[5,6],[8,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[3, 5]</code>, we have two connected groups: <code>[[1, 3], [3, 5], [5, 6]]</code> and <code>[[8, 10]]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">intervals = [[5,10],[1,1],[3,3]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>After adding the interval <code>[1, 1]</code>, we have three connected groups: <code>[[1, 1], [1, 1]]</code>, <code>[[3, 3]]</code>, and <code>[[5, 10]]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li> <li><code>intervals[i] == [start<sub>i</sub>, end<sub>i</sub>]</code></li> <li><code>1 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
TypeScript
function minConnectedGroups(intervals: number[][], k: number): number { intervals.sort((a, b) => a[0] - b[0]); const merged: number[][] = []; for (const interval of intervals) { const [s, e] = interval; if (merged.length === 0 || merged.at(-1)![1] < s) { merged.push(interval); } else { merged.at(-1)![1] = Math.max(merged.at(-1)![1], e); } } const search = (x: number): number => { let [l, r] = [0, merged.length]; while (l < r) { const mid = (l + r) >> 1; if (merged[mid][0] >= x) { r = mid; } else { l = mid + 1; } } return l; }; let ans = merged.length; for (let i = 0; i < merged.length; ++i) { const j = search(merged[i][1] + k + 1); ans = Math.min(ans, merged.length - (j - i - 1)); } return ans; }
3,324
Find the Sequence of Strings Appeared on the Screen
Medium
<p>You are given a string <code>target</code>.</p> <p>Alice is going to type <code>target</code> on her computer using a special keyboard that has <strong>only two</strong> keys:</p> <ul> <li>Key 1 appends the character <code>&quot;a&quot;</code> to the string on the screen.</li> <li>Key 2 changes the <strong>last</strong> character of the string on the screen to its <strong>next</strong> character in the English alphabet. For example, <code>&quot;c&quot;</code> changes to <code>&quot;d&quot;</code> and <code>&quot;z&quot;</code> changes to <code>&quot;a&quot;</code>.</li> </ul> <p><strong>Note</strong> that initially there is an <em>empty</em> string <code>&quot;&quot;</code> on the screen, so she can <strong>only</strong> press key 1.</p> <p>Return a list of <em>all</em> strings that appear on the screen as Alice types <code>target</code>, in the order they appear, using the <strong>minimum</strong> key presses.</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;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;aa&quot;,&quot;ab&quot;,&quot;aba&quot;,&quot;abb&quot;,&quot;abc&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The sequence of key presses done by Alice are:</p> <ul> <li>Press key 1, and the string on the screen becomes <code>&quot;a&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aa&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;ab&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aba&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abb&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abc&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;he&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;ha&quot;,&quot;hb&quot;,&quot;hc&quot;,&quot;hd&quot;,&quot;he&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 400</code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
String; Simulation
C++
class Solution { public: vector<string> stringSequence(string target) { vector<string> ans; for (char c : target) { string s = ans.empty() ? "" : ans.back(); for (char a = 'a'; a <= c; ++a) { string t = s + a; ans.push_back(t); } } return ans; } };
3,324
Find the Sequence of Strings Appeared on the Screen
Medium
<p>You are given a string <code>target</code>.</p> <p>Alice is going to type <code>target</code> on her computer using a special keyboard that has <strong>only two</strong> keys:</p> <ul> <li>Key 1 appends the character <code>&quot;a&quot;</code> to the string on the screen.</li> <li>Key 2 changes the <strong>last</strong> character of the string on the screen to its <strong>next</strong> character in the English alphabet. For example, <code>&quot;c&quot;</code> changes to <code>&quot;d&quot;</code> and <code>&quot;z&quot;</code> changes to <code>&quot;a&quot;</code>.</li> </ul> <p><strong>Note</strong> that initially there is an <em>empty</em> string <code>&quot;&quot;</code> on the screen, so she can <strong>only</strong> press key 1.</p> <p>Return a list of <em>all</em> strings that appear on the screen as Alice types <code>target</code>, in the order they appear, using the <strong>minimum</strong> key presses.</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;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;aa&quot;,&quot;ab&quot;,&quot;aba&quot;,&quot;abb&quot;,&quot;abc&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The sequence of key presses done by Alice are:</p> <ul> <li>Press key 1, and the string on the screen becomes <code>&quot;a&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aa&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;ab&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aba&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abb&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abc&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;he&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;ha&quot;,&quot;hb&quot;,&quot;hc&quot;,&quot;hd&quot;,&quot;he&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 400</code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
String; Simulation
Go
func stringSequence(target string) (ans []string) { for _, c := range target { s := "" if len(ans) > 0 { s = ans[len(ans)-1] } for a := 'a'; a <= c; a++ { t := s + string(a) ans = append(ans, t) } } return }
3,324
Find the Sequence of Strings Appeared on the Screen
Medium
<p>You are given a string <code>target</code>.</p> <p>Alice is going to type <code>target</code> on her computer using a special keyboard that has <strong>only two</strong> keys:</p> <ul> <li>Key 1 appends the character <code>&quot;a&quot;</code> to the string on the screen.</li> <li>Key 2 changes the <strong>last</strong> character of the string on the screen to its <strong>next</strong> character in the English alphabet. For example, <code>&quot;c&quot;</code> changes to <code>&quot;d&quot;</code> and <code>&quot;z&quot;</code> changes to <code>&quot;a&quot;</code>.</li> </ul> <p><strong>Note</strong> that initially there is an <em>empty</em> string <code>&quot;&quot;</code> on the screen, so she can <strong>only</strong> press key 1.</p> <p>Return a list of <em>all</em> strings that appear on the screen as Alice types <code>target</code>, in the order they appear, using the <strong>minimum</strong> key presses.</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;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;aa&quot;,&quot;ab&quot;,&quot;aba&quot;,&quot;abb&quot;,&quot;abc&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The sequence of key presses done by Alice are:</p> <ul> <li>Press key 1, and the string on the screen becomes <code>&quot;a&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aa&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;ab&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aba&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abb&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abc&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;he&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;ha&quot;,&quot;hb&quot;,&quot;hc&quot;,&quot;hd&quot;,&quot;he&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 400</code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
String; Simulation
Java
class Solution { public List<String> stringSequence(String target) { List<String> ans = new ArrayList<>(); for (char c : target.toCharArray()) { String s = ans.isEmpty() ? "" : ans.get(ans.size() - 1); for (char a = 'a'; a <= c; ++a) { String t = s + a; ans.add(t); } } return ans; } }
3,324
Find the Sequence of Strings Appeared on the Screen
Medium
<p>You are given a string <code>target</code>.</p> <p>Alice is going to type <code>target</code> on her computer using a special keyboard that has <strong>only two</strong> keys:</p> <ul> <li>Key 1 appends the character <code>&quot;a&quot;</code> to the string on the screen.</li> <li>Key 2 changes the <strong>last</strong> character of the string on the screen to its <strong>next</strong> character in the English alphabet. For example, <code>&quot;c&quot;</code> changes to <code>&quot;d&quot;</code> and <code>&quot;z&quot;</code> changes to <code>&quot;a&quot;</code>.</li> </ul> <p><strong>Note</strong> that initially there is an <em>empty</em> string <code>&quot;&quot;</code> on the screen, so she can <strong>only</strong> press key 1.</p> <p>Return a list of <em>all</em> strings that appear on the screen as Alice types <code>target</code>, in the order they appear, using the <strong>minimum</strong> key presses.</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;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;aa&quot;,&quot;ab&quot;,&quot;aba&quot;,&quot;abb&quot;,&quot;abc&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The sequence of key presses done by Alice are:</p> <ul> <li>Press key 1, and the string on the screen becomes <code>&quot;a&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aa&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;ab&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aba&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abb&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abc&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;he&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;ha&quot;,&quot;hb&quot;,&quot;hc&quot;,&quot;hd&quot;,&quot;he&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 400</code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
String; Simulation
Python
class Solution: def stringSequence(self, target: str) -> List[str]: ans = [] for c in target: s = ans[-1] if ans else "" for a in ascii_lowercase: t = s + a ans.append(t) if a == c: break return ans
3,324
Find the Sequence of Strings Appeared on the Screen
Medium
<p>You are given a string <code>target</code>.</p> <p>Alice is going to type <code>target</code> on her computer using a special keyboard that has <strong>only two</strong> keys:</p> <ul> <li>Key 1 appends the character <code>&quot;a&quot;</code> to the string on the screen.</li> <li>Key 2 changes the <strong>last</strong> character of the string on the screen to its <strong>next</strong> character in the English alphabet. For example, <code>&quot;c&quot;</code> changes to <code>&quot;d&quot;</code> and <code>&quot;z&quot;</code> changes to <code>&quot;a&quot;</code>.</li> </ul> <p><strong>Note</strong> that initially there is an <em>empty</em> string <code>&quot;&quot;</code> on the screen, so she can <strong>only</strong> press key 1.</p> <p>Return a list of <em>all</em> strings that appear on the screen as Alice types <code>target</code>, in the order they appear, using the <strong>minimum</strong> key presses.</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;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;aa&quot;,&quot;ab&quot;,&quot;aba&quot;,&quot;abb&quot;,&quot;abc&quot;]</span></p> <p><strong>Explanation:</strong></p> <p>The sequence of key presses done by Alice are:</p> <ul> <li>Press key 1, and the string on the screen becomes <code>&quot;a&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aa&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;ab&quot;</code>.</li> <li>Press key 1, and the string on the screen becomes <code>&quot;aba&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abb&quot;</code>.</li> <li>Press key 2, and the string on the screen becomes <code>&quot;abc&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;he&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;ha&quot;,&quot;hb&quot;,&quot;hc&quot;,&quot;hd&quot;,&quot;he&quot;]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target.length &lt;= 400</code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
String; Simulation
TypeScript
function stringSequence(target: string): string[] { const ans: string[] = []; for (const c of target) { let s = ans.length > 0 ? ans[ans.length - 1] : ''; for (let a = 'a'.charCodeAt(0); a <= c.charCodeAt(0); a++) { const t = s + String.fromCharCode(a); ans.push(t); } } return ans; }
3,325
Count Substrings With K-Frequency Characters I
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li><code>&quot;aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int numberOfSubstrings(string s, int k) { int n = s.size(); int ans = 0, l = 0; int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; while (cnt[c - 'a'] >= k) { --cnt[s[l++] - 'a']; } ans += l; } return ans; } };
3,325
Count Substrings With K-Frequency Characters I
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li><code>&quot;aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func numberOfSubstrings(s string, k int) (ans int) { l := 0 cnt := [26]int{} for _, c := range s { cnt[c-'a']++ for cnt[c-'a'] >= k { cnt[s[l]-'a']-- l++ } ans += l } return }
3,325
Count Substrings With K-Frequency Characters I
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li><code>&quot;aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int numberOfSubstrings(String s, int k) { int[] cnt = new int[26]; int ans = 0, l = 0; for (int r = 0; r < s.length(); ++r) { int c = s.charAt(r) - 'a'; ++cnt[c]; while (cnt[c] >= k) { --cnt[s.charAt(l) - 'a']; l++; } ans += l; } return ans; } }
3,325
Count Substrings With K-Frequency Characters I
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li><code>&quot;aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def numberOfSubstrings(self, s: str, k: int) -> int: cnt = Counter() ans = l = 0 for c in s: cnt[c] += 1 while cnt[c] >= k: cnt[s[l]] -= 1 l += 1 ans += l return ans
3,325
Count Substrings With K-Frequency Characters I
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li><code>&quot;aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function numberOfSubstrings(s: string, k: number): number { let [ans, l] = [0, 0]; const cnt: number[] = Array(26).fill(0); for (const c of s) { const x = c.charCodeAt(0) - 'a'.charCodeAt(0); ++cnt[x]; while (cnt[x] >= k) { --cnt[s[l++].charCodeAt(0) - 'a'.charCodeAt(0)]; } ans += l; } return ans; }
3,326
Minimum Division Operations to Make Array Non Decreasing
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Any <strong>positive</strong> divisor of a natural number <code>x</code> that is <strong>strictly less</strong> than <code>x</code> is called a <strong>proper divisor</strong> of <code>x</code>. For example, 2 is a <em>proper divisor</em> of 4, while 6 is not a <em>proper divisor</em> of 6.</p> <p>You are allowed to perform an <strong>operation</strong> any number of times on <code>nums</code>, where in each <strong>operation</strong> you select any <em>one</em> element from <code>nums</code> and divide it by its <strong>greatest</strong> <strong>proper divisor</strong>.</p> <p>Return the <strong>minimum</strong> number of <strong>operations</strong> required to make the array <strong>non-decreasing</strong>.</p> <p>If it is <strong>not</strong> possible to make the array <em>non-decreasing</em> using any number of operations, 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">nums = [25,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Using a single operation, 25 gets divided by 5 and <code>nums</code> becomes <code>[5, 7]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></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>6</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
C++
const int MX = 1e6; int LPF[MX + 1]; auto init = [] { for (int i = 2; i <= MX; i++) { if (LPF[i] == 0) { for (int j = i; j <= MX; j += i) { if (LPF[j] == 0) { LPF[j] = i; } } } } return 0; }(); class Solution { public: int minOperations(vector<int>& nums) { int ans = 0; for (int i = nums.size() - 2; i >= 0; i--) { if (nums[i] > nums[i + 1]) { nums[i] = LPF[nums[i]]; if (nums[i] > nums[i + 1]) { return -1; } ans++; } } return ans; } };
3,326
Minimum Division Operations to Make Array Non Decreasing
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Any <strong>positive</strong> divisor of a natural number <code>x</code> that is <strong>strictly less</strong> than <code>x</code> is called a <strong>proper divisor</strong> of <code>x</code>. For example, 2 is a <em>proper divisor</em> of 4, while 6 is not a <em>proper divisor</em> of 6.</p> <p>You are allowed to perform an <strong>operation</strong> any number of times on <code>nums</code>, where in each <strong>operation</strong> you select any <em>one</em> element from <code>nums</code> and divide it by its <strong>greatest</strong> <strong>proper divisor</strong>.</p> <p>Return the <strong>minimum</strong> number of <strong>operations</strong> required to make the array <strong>non-decreasing</strong>.</p> <p>If it is <strong>not</strong> possible to make the array <em>non-decreasing</em> using any number of operations, 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">nums = [25,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Using a single operation, 25 gets divided by 5 and <code>nums</code> becomes <code>[5, 7]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></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>6</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Go
const mx int = 1e6 var lpf = [mx + 1]int{} func init() { for i := 2; i <= mx; i++ { if lpf[i] == 0 { for j := i; j <= mx; j += i { if lpf[j] == 0 { lpf[j] = i } } } } } func minOperations(nums []int) (ans int) { for i := len(nums) - 2; i >= 0; i-- { if nums[i] > nums[i+1] { nums[i] = lpf[nums[i]] if nums[i] > nums[i+1] { return -1 } ans++ } } return }
3,326
Minimum Division Operations to Make Array Non Decreasing
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Any <strong>positive</strong> divisor of a natural number <code>x</code> that is <strong>strictly less</strong> than <code>x</code> is called a <strong>proper divisor</strong> of <code>x</code>. For example, 2 is a <em>proper divisor</em> of 4, while 6 is not a <em>proper divisor</em> of 6.</p> <p>You are allowed to perform an <strong>operation</strong> any number of times on <code>nums</code>, where in each <strong>operation</strong> you select any <em>one</em> element from <code>nums</code> and divide it by its <strong>greatest</strong> <strong>proper divisor</strong>.</p> <p>Return the <strong>minimum</strong> number of <strong>operations</strong> required to make the array <strong>non-decreasing</strong>.</p> <p>If it is <strong>not</strong> possible to make the array <em>non-decreasing</em> using any number of operations, 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">nums = [25,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Using a single operation, 25 gets divided by 5 and <code>nums</code> becomes <code>[5, 7]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></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>6</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Java
class Solution { private static final int MX = (int) 1e6 + 1; private static final int[] LPF = new int[MX + 1]; static { for (int i = 2; i <= MX; ++i) { for (int j = i; j <= MX; j += i) { if (LPF[j] == 0) { LPF[j] = i; } } } } public int minOperations(int[] nums) { int ans = 0; for (int i = nums.length - 2; i >= 0; i--) { if (nums[i] > nums[i + 1]) { nums[i] = LPF[nums[i]]; if (nums[i] > nums[i + 1]) { return -1; } ans++; } } return ans; } }
3,326
Minimum Division Operations to Make Array Non Decreasing
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Any <strong>positive</strong> divisor of a natural number <code>x</code> that is <strong>strictly less</strong> than <code>x</code> is called a <strong>proper divisor</strong> of <code>x</code>. For example, 2 is a <em>proper divisor</em> of 4, while 6 is not a <em>proper divisor</em> of 6.</p> <p>You are allowed to perform an <strong>operation</strong> any number of times on <code>nums</code>, where in each <strong>operation</strong> you select any <em>one</em> element from <code>nums</code> and divide it by its <strong>greatest</strong> <strong>proper divisor</strong>.</p> <p>Return the <strong>minimum</strong> number of <strong>operations</strong> required to make the array <strong>non-decreasing</strong>.</p> <p>If it is <strong>not</strong> possible to make the array <em>non-decreasing</em> using any number of operations, 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">nums = [25,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Using a single operation, 25 gets divided by 5 and <code>nums</code> becomes <code>[5, 7]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></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>6</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Python
mx = 10**6 + 1 lpf = [0] * (mx + 1) for i in range(2, mx + 1): if lpf[i] == 0: for j in range(i, mx + 1, i): if lpf[j] == 0: lpf[j] = i class Solution: def minOperations(self, nums: List[int]) -> int: ans = 0 for i in range(len(nums) - 2, -1, -1): if nums[i] > nums[i + 1]: nums[i] = lpf[nums[i]] if nums[i] > nums[i + 1]: return -1 ans += 1 return ans
3,326
Minimum Division Operations to Make Array Non Decreasing
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Any <strong>positive</strong> divisor of a natural number <code>x</code> that is <strong>strictly less</strong> than <code>x</code> is called a <strong>proper divisor</strong> of <code>x</code>. For example, 2 is a <em>proper divisor</em> of 4, while 6 is not a <em>proper divisor</em> of 6.</p> <p>You are allowed to perform an <strong>operation</strong> any number of times on <code>nums</code>, where in each <strong>operation</strong> you select any <em>one</em> element from <code>nums</code> and divide it by its <strong>greatest</strong> <strong>proper divisor</strong>.</p> <p>Return the <strong>minimum</strong> number of <strong>operations</strong> required to make the array <strong>non-decreasing</strong>.</p> <p>If it is <strong>not</strong> possible to make the array <em>non-decreasing</em> using any number of operations, 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">nums = [25,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Using a single operation, 25 gets divided by 5 and <code>nums</code> becomes <code>[5, 7]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></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>6</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
TypeScript
const mx = 10 ** 6; const lpf = Array(mx + 1).fill(0); for (let i = 2; i <= mx; ++i) { for (let j = i; j <= mx; j += i) { if (lpf[j] === 0) { lpf[j] = i; } } } function minOperations(nums: number[]): number { let ans = 0; for (let i = nums.length - 2; ~i; --i) { if (nums[i] > nums[i + 1]) { nums[i] = lpf[nums[i]]; if (nums[i] > nums[i + 1]) { return -1; } ++ans; } } return ans; }
3,327
Check if DFS Strings Are Palindromes
Hard
<p>You are given a tree rooted at node 0, consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>Consider an empty string <code>dfsStr</code>, and define a recursive function <code>dfs(int x)</code> that takes a node <code>x</code> as a parameter and performs the following steps in order:</p> <ul> <li>Iterate over each child <code>y</code> of <code>x</code> <strong>in increasing order of their numbers</strong>, and call <code>dfs(y)</code>.</li> <li>Add the character <code>s[x]</code> to the end of the string <code>dfsStr</code>.</li> </ul> <p><strong>Note</strong> that <code>dfsStr</code> is shared across all recursive calls of <code>dfs</code>.</p> <p>You need to find a boolean array <code>answer</code> of size <code>n</code>, where for each index <code>i</code> from <code>0</code> to <code>n - 1</code>, you do the following:</p> <ul> <li>Empty the string <code>dfsStr</code> and call <code>dfs(i)</code>.</li> <li>If the resulting string <code>dfsStr</code> is a <span data-keyword="palindrome-string">palindrome</span>, then set <code>answer[i]</code> to <code>true</code>. Otherwise, set <code>answer[i]</code> to <code>false</code>.</li> </ul> <p>Return the array <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree1drawio.png" style="width: 240px; height: 256px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,2], s = &quot;aababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,false,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Calling <code>dfs(0)</code> results in the string <code>dfsStr = &quot;abaaba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(1)</code> results in the string <code>dfsStr = &quot;aba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(2)</code> results in the string <code>dfsStr = &quot;ab&quot;</code>, which is <strong>not</strong> a palindrome.</li> <li>Calling <code>dfs(3)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(4)</code> results in the string <code>dfsStr = &quot;b&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(5)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree2drawio-1.png" style="width: 260px; height: 167px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,0,0], s = &quot;aabcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>Every call on <code>dfs(x)</code> results in a palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String; Hash Function
C++
class Hashing { private: vector<long long> p; vector<long long> h; long long mod; public: Hashing(string word, long long base, int mod) { int n = word.size(); p.resize(n + 1); h.resize(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[i - 1] - 'a') % mod; } } long long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } }; class Solution { public: vector<bool> findAnswer(vector<int>& parent, string s) { int n = s.size(); vector<int> g[n]; for (int i = 1; i < n; ++i) { g[parent[i]].push_back(i); } string dfsStr; vector<pair<int, int>> pos(n); auto dfs = [&](this auto&& dfs, int i) -> void { int l = dfsStr.size() + 1; for (int j : g[i]) { dfs(j); } dfsStr.push_back(s[i]); int r = dfsStr.size(); pos[i] = {l, r}; }; dfs(0); const int base = 13331; const int mod = 998244353; Hashing h1(dfsStr, base, mod); reverse(dfsStr.begin(), dfsStr.end()); Hashing h2(dfsStr, base, mod); vector<bool> ans(n); for (int i = 0; i < n; ++i) { auto [l, r] = pos[i]; int k = r - l + 1; long long v1 = h1.query(l, l + k / 2 - 1); long long v2 = h2.query(n - r + 1, n - r + 1 + k / 2 - 1); ans[i] = v1 == v2; } return ans; } };
3,327
Check if DFS Strings Are Palindromes
Hard
<p>You are given a tree rooted at node 0, consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>Consider an empty string <code>dfsStr</code>, and define a recursive function <code>dfs(int x)</code> that takes a node <code>x</code> as a parameter and performs the following steps in order:</p> <ul> <li>Iterate over each child <code>y</code> of <code>x</code> <strong>in increasing order of their numbers</strong>, and call <code>dfs(y)</code>.</li> <li>Add the character <code>s[x]</code> to the end of the string <code>dfsStr</code>.</li> </ul> <p><strong>Note</strong> that <code>dfsStr</code> is shared across all recursive calls of <code>dfs</code>.</p> <p>You need to find a boolean array <code>answer</code> of size <code>n</code>, where for each index <code>i</code> from <code>0</code> to <code>n - 1</code>, you do the following:</p> <ul> <li>Empty the string <code>dfsStr</code> and call <code>dfs(i)</code>.</li> <li>If the resulting string <code>dfsStr</code> is a <span data-keyword="palindrome-string">palindrome</span>, then set <code>answer[i]</code> to <code>true</code>. Otherwise, set <code>answer[i]</code> to <code>false</code>.</li> </ul> <p>Return the array <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree1drawio.png" style="width: 240px; height: 256px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,2], s = &quot;aababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,false,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Calling <code>dfs(0)</code> results in the string <code>dfsStr = &quot;abaaba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(1)</code> results in the string <code>dfsStr = &quot;aba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(2)</code> results in the string <code>dfsStr = &quot;ab&quot;</code>, which is <strong>not</strong> a palindrome.</li> <li>Calling <code>dfs(3)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(4)</code> results in the string <code>dfsStr = &quot;b&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(5)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree2drawio-1.png" style="width: 260px; height: 167px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,0,0], s = &quot;aabcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>Every call on <code>dfs(x)</code> results in a palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String; Hash Function
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 findAnswer(parent []int, s string) (ans []bool) { n := len(s) g := make([][]int, n) for i := 1; i < n; i++ { g[parent[i]] = append(g[parent[i]], i) } dfsStr := []byte{} pos := make([][2]int, n) var dfs func(int) dfs = func(i int) { l := len(dfsStr) + 1 for _, j := range g[i] { dfs(j) } dfsStr = append(dfsStr, s[i]) r := len(dfsStr) pos[i] = [2]int{l, r} } const base = 13331 const mod = 998244353 dfs(0) h1 := NewHashing(string(dfsStr), base, mod) for i, j := 0, len(dfsStr)-1; i < j; i, j = i+1, j-1 { dfsStr[i], dfsStr[j] = dfsStr[j], dfsStr[i] } h2 := NewHashing(string(dfsStr), base, mod) for i := 0; i < n; i++ { l, r := pos[i][0], pos[i][1] k := r - l + 1 v1 := h1.query(l, l+k/2-1) v2 := h2.query(n-r+1, n-r+1+k/2-1) ans = append(ans, v1 == v2) } return }
3,327
Check if DFS Strings Are Palindromes
Hard
<p>You are given a tree rooted at node 0, consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>Consider an empty string <code>dfsStr</code>, and define a recursive function <code>dfs(int x)</code> that takes a node <code>x</code> as a parameter and performs the following steps in order:</p> <ul> <li>Iterate over each child <code>y</code> of <code>x</code> <strong>in increasing order of their numbers</strong>, and call <code>dfs(y)</code>.</li> <li>Add the character <code>s[x]</code> to the end of the string <code>dfsStr</code>.</li> </ul> <p><strong>Note</strong> that <code>dfsStr</code> is shared across all recursive calls of <code>dfs</code>.</p> <p>You need to find a boolean array <code>answer</code> of size <code>n</code>, where for each index <code>i</code> from <code>0</code> to <code>n - 1</code>, you do the following:</p> <ul> <li>Empty the string <code>dfsStr</code> and call <code>dfs(i)</code>.</li> <li>If the resulting string <code>dfsStr</code> is a <span data-keyword="palindrome-string">palindrome</span>, then set <code>answer[i]</code> to <code>true</code>. Otherwise, set <code>answer[i]</code> to <code>false</code>.</li> </ul> <p>Return the array <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree1drawio.png" style="width: 240px; height: 256px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,2], s = &quot;aababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,false,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Calling <code>dfs(0)</code> results in the string <code>dfsStr = &quot;abaaba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(1)</code> results in the string <code>dfsStr = &quot;aba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(2)</code> results in the string <code>dfsStr = &quot;ab&quot;</code>, which is <strong>not</strong> a palindrome.</li> <li>Calling <code>dfs(3)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(4)</code> results in the string <code>dfsStr = &quot;b&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(5)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree2drawio-1.png" style="width: 260px; height: 167px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,0,0], s = &quot;aabcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>Every call on <code>dfs(x)</code> results in a palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String; Hash Function
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 { private char[] s; private int[][] pos; private List<Integer>[] g; private StringBuilder dfsStr = new StringBuilder(); public boolean[] findAnswer(int[] parent, String s) { this.s = s.toCharArray(); int n = s.length(); g = new List[n]; pos = new int[n][0]; Arrays.setAll(g, k -> new ArrayList<>()); for (int i = 1; i < n; ++i) { g[parent[i]].add(i); } dfs(0); final int base = 13331; final int mod = 998244353; Hashing h1 = new Hashing(dfsStr.toString(), base, mod); Hashing h2 = new Hashing(new StringBuilder(dfsStr).reverse().toString(), base, mod); boolean[] ans = new boolean[n]; for (int i = 0; i < n; ++i) { int l = pos[i][0], r = pos[i][1]; int k = r - l + 1; long v1 = h1.query(l, l + k / 2 - 1); long v2 = h2.query(n + 1 - r, n + 1 - r + k / 2 - 1); ans[i] = v1 == v2; } return ans; } private void dfs(int i) { int l = dfsStr.length() + 1; for (int j : g[i]) { dfs(j); } dfsStr.append(s[i]); int r = dfsStr.length(); pos[i] = new int[] {l, r}; } }
3,327
Check if DFS Strings Are Palindromes
Hard
<p>You are given a tree rooted at node 0, consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>Consider an empty string <code>dfsStr</code>, and define a recursive function <code>dfs(int x)</code> that takes a node <code>x</code> as a parameter and performs the following steps in order:</p> <ul> <li>Iterate over each child <code>y</code> of <code>x</code> <strong>in increasing order of their numbers</strong>, and call <code>dfs(y)</code>.</li> <li>Add the character <code>s[x]</code> to the end of the string <code>dfsStr</code>.</li> </ul> <p><strong>Note</strong> that <code>dfsStr</code> is shared across all recursive calls of <code>dfs</code>.</p> <p>You need to find a boolean array <code>answer</code> of size <code>n</code>, where for each index <code>i</code> from <code>0</code> to <code>n - 1</code>, you do the following:</p> <ul> <li>Empty the string <code>dfsStr</code> and call <code>dfs(i)</code>.</li> <li>If the resulting string <code>dfsStr</code> is a <span data-keyword="palindrome-string">palindrome</span>, then set <code>answer[i]</code> to <code>true</code>. Otherwise, set <code>answer[i]</code> to <code>false</code>.</li> </ul> <p>Return the array <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree1drawio.png" style="width: 240px; height: 256px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,2], s = &quot;aababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,false,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Calling <code>dfs(0)</code> results in the string <code>dfsStr = &quot;abaaba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(1)</code> results in the string <code>dfsStr = &quot;aba&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(2)</code> results in the string <code>dfsStr = &quot;ab&quot;</code>, which is <strong>not</strong> a palindrome.</li> <li>Calling <code>dfs(3)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(4)</code> results in the string <code>dfsStr = &quot;b&quot;</code>, which is a palindrome.</li> <li>Calling <code>dfs(5)</code> results in the string <code>dfsStr = &quot;a&quot;</code>, which is a palindrome.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3327.Check%20if%20DFS%20Strings%20Are%20Palindromes/images/tree2drawio-1.png" style="width: 260px; height: 167px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,0,0], s = &quot;aabcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[true,true,true,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>Every call on <code>dfs(x)</code> results in a palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String; Hash Function
Python
class Hashing: __slots__ = ["mod", "h", "p"] def __init__(self, s: List[str], base: int, mod: int): self.mod = mod self.h = [0] * (len(s) + 1) self.p = [1] * (len(s) + 1) for i in range(1, len(s) + 1): self.h[i] = (self.h[i - 1] * base + ord(s[i - 1])) % mod self.p[i] = (self.p[i - 1] * base) % mod def query(self, l: int, r: int) -> int: return (self.h[r] - self.h[l - 1] * self.p[r - l + 1]) % self.mod class Solution: def findAnswer(self, parent: List[int], s: str) -> List[bool]: def dfs(i: int): l = len(dfsStr) + 1 for j in g[i]: dfs(j) dfsStr.append(s[i]) r = len(dfsStr) pos[i] = (l, r) n = len(s) g = [[] for _ in range(n)] for i in range(1, n): g[parent[i]].append(i) dfsStr = [] pos = {} dfs(0) base, mod = 13331, 998244353 h1 = Hashing(dfsStr, base, mod) h2 = Hashing(dfsStr[::-1], base, mod) ans = [] for i in range(n): l, r = pos[i] k = r - l + 1 v1 = h1.query(l, l + k // 2 - 1) v2 = h2.query(n - r + 1, n - r + 1 + k // 2 - 1) ans.append(v1 == v2) return ans
3,328
Find Cities in Each State II
Medium
<p>Table: <code>cities</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | state | varchar | | city | varchar | +-------------+---------+ (state, city) is the combination of columns with unique values for this table. Each row of this table contains the state name and the city name within that state. </pre> <p>Write a solution to find <strong>all the cities</strong> in <strong>each state</strong> and analyze them based on the following requirements:</p> <ul> <li>Combine all cities into a <strong>comma-separated</strong> string for each state.</li> <li>Only include states that have <strong>at least</strong> <code>3</code> cities.</li> <li>Only include states where <strong>at least one city</strong> starts with the <strong>same letter as the state name</strong>.</li> </ul> <p>Return <em>the result table ordered by</em> <em>the count of matching-letter cities in <strong>descending</strong> order</em>&nbsp;<em>and then by state name 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>cities table:</p> <pre class="example-io"> +--------------+---------------+ | state | city | +--------------+---------------+ | New York | New York City | | New York | Newark | | New York | Buffalo | | New York | Rochester | | California | San Francisco | | California | Sacramento | | California | San Diego | | California | Los Angeles | | Texas | Tyler | | Texas | Temple | | Texas | Taylor | | Texas | Dallas | | Pennsylvania | Philadelphia | | Pennsylvania | Pittsburgh | | Pennsylvania | Pottstown | +--------------+---------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+-------------------------------------------+-----------------------+ | state | cities | matching_letter_count | +-------------+-------------------------------------------+-----------------------+ | Pennsylvania| Philadelphia, Pittsburgh, Pottstown | 3 | | Texas | Dallas, Taylor, Temple, Tyler | 3 | | New York | Buffalo, Newark, New York City, Rochester | 2 | +-------------+-------------------------------------------+-----------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Pennsylvania</strong>: <ul> <li>Has 3 cities (meets minimum requirement)</li> <li>All 3 cities start with &#39;P&#39; (same as state)</li> <li>matching_letter_count = 3</li> </ul> </li> <li><strong>Texas</strong>: <ul> <li>Has 4 cities (meets minimum requirement)</li> <li>3 cities (Taylor, Temple, Tyler) start with &#39;T&#39; (same as state)</li> <li>matching_letter_count = 3</li> </ul> </li> <li><strong>New York</strong>: <ul> <li>Has 4 cities (meets minimum requirement)</li> <li>2 cities (Newark, New York City) start with &#39;N&#39; (same as state)</li> <li>matching_letter_count = 2</li> </ul> </li> <li><strong>California</strong> is not included in the output because: <ul> <li>Although it has 4 cities (meets minimum requirement)</li> <li>No cities start with &#39;C&#39; (doesn&#39;t meet the matching letter requirement)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>Results are ordered by matching_letter_count in descending order</li> <li>When matching_letter_count is the same (Texas and New York both have 2), they are ordered by state name alphabetically</li> <li>Cities in each row are ordered alphabetically</li> </ul> </div>
Database
Python
import pandas as pd def state_city_analysis(cities: pd.DataFrame) -> pd.DataFrame: cities["matching_letter"] = cities["city"].str[0] == cities["state"].str[0] result = ( cities.groupby("state") .agg( cities=("city", lambda x: ", ".join(sorted(x))), matching_letter_count=("matching_letter", "sum"), city_count=("city", "count"), ) .reset_index() ) result = result[(result["city_count"] >= 3) & (result["matching_letter_count"] > 0)] result = result.sort_values( by=["matching_letter_count", "state"], ascending=[False, True] ) result = result.drop(columns=["city_count"]) return result
3,328
Find Cities in Each State II
Medium
<p>Table: <code>cities</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | state | varchar | | city | varchar | +-------------+---------+ (state, city) is the combination of columns with unique values for this table. Each row of this table contains the state name and the city name within that state. </pre> <p>Write a solution to find <strong>all the cities</strong> in <strong>each state</strong> and analyze them based on the following requirements:</p> <ul> <li>Combine all cities into a <strong>comma-separated</strong> string for each state.</li> <li>Only include states that have <strong>at least</strong> <code>3</code> cities.</li> <li>Only include states where <strong>at least one city</strong> starts with the <strong>same letter as the state name</strong>.</li> </ul> <p>Return <em>the result table ordered by</em> <em>the count of matching-letter cities in <strong>descending</strong> order</em>&nbsp;<em>and then by state name 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>cities table:</p> <pre class="example-io"> +--------------+---------------+ | state | city | +--------------+---------------+ | New York | New York City | | New York | Newark | | New York | Buffalo | | New York | Rochester | | California | San Francisco | | California | Sacramento | | California | San Diego | | California | Los Angeles | | Texas | Tyler | | Texas | Temple | | Texas | Taylor | | Texas | Dallas | | Pennsylvania | Philadelphia | | Pennsylvania | Pittsburgh | | Pennsylvania | Pottstown | +--------------+---------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+-------------------------------------------+-----------------------+ | state | cities | matching_letter_count | +-------------+-------------------------------------------+-----------------------+ | Pennsylvania| Philadelphia, Pittsburgh, Pottstown | 3 | | Texas | Dallas, Taylor, Temple, Tyler | 3 | | New York | Buffalo, Newark, New York City, Rochester | 2 | +-------------+-------------------------------------------+-----------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Pennsylvania</strong>: <ul> <li>Has 3 cities (meets minimum requirement)</li> <li>All 3 cities start with &#39;P&#39; (same as state)</li> <li>matching_letter_count = 3</li> </ul> </li> <li><strong>Texas</strong>: <ul> <li>Has 4 cities (meets minimum requirement)</li> <li>3 cities (Taylor, Temple, Tyler) start with &#39;T&#39; (same as state)</li> <li>matching_letter_count = 3</li> </ul> </li> <li><strong>New York</strong>: <ul> <li>Has 4 cities (meets minimum requirement)</li> <li>2 cities (Newark, New York City) start with &#39;N&#39; (same as state)</li> <li>matching_letter_count = 2</li> </ul> </li> <li><strong>California</strong> is not included in the output because: <ul> <li>Although it has 4 cities (meets minimum requirement)</li> <li>No cities start with &#39;C&#39; (doesn&#39;t meet the matching letter requirement)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>Results are ordered by matching_letter_count in descending order</li> <li>When matching_letter_count is the same (Texas and New York both have 2), they are ordered by state name alphabetically</li> <li>Cities in each row are ordered alphabetically</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT state, GROUP_CONCAT(city ORDER BY city SEPARATOR ', ') AS cities, COUNT( CASE WHEN LEFT(city, 1) = LEFT(state, 1) THEN 1 END ) AS matching_letter_count FROM cities GROUP BY 1 HAVING COUNT(city) >= 3 AND matching_letter_count > 0 ORDER BY 3 DESC, 1;
3,329
Count Substrings With K-Frequency Characters II
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li>&quot;<code>aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: long long numberOfSubstrings(string s, int k) { int n = s.size(); long long ans = 0, l = 0; int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; while (cnt[c - 'a'] >= k) { --cnt[s[l++] - 'a']; } ans += l; } return ans; } };
3,329
Count Substrings With K-Frequency Characters II
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li>&quot;<code>aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func numberOfSubstrings(s string, k int) (ans int64) { l := 0 cnt := [26]int{} for _, c := range s { cnt[c-'a']++ for cnt[c-'a'] >= k { cnt[s[l]-'a']-- l++ } ans += int64(l) } return }
3,329
Count Substrings With K-Frequency Characters II
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li>&quot;<code>aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public long numberOfSubstrings(String s, int k) { int[] cnt = new int[26]; long ans = 0; for (int l = 0, r = 0; r < s.length(); ++r) { int c = s.charAt(r) - 'a'; ++cnt[c]; while (cnt[c] >= k) { --cnt[s.charAt(l) - 'a']; l++; } ans += l; } return ans; } }
3,329
Count Substrings With K-Frequency Characters II
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li>&quot;<code>aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def numberOfSubstrings(self, s: str, k: int) -> int: cnt = Counter() ans = l = 0 for c in s: cnt[c] += 1 while cnt[c] >= k: cnt[s[l]] -= 1 l += 1 ans += l return ans
3,329
Count Substrings With K-Frequency Characters II
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, return the total number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> where <strong>at least one</strong> character appears <strong>at least</strong> <code>k</code> times.</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;abacb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The valid substrings are:</p> <ul> <li>&quot;<code>aba&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abac&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;abacb&quot;</code> (character <code>&#39;a&#39;</code> appears 2 times).</li> <li><code>&quot;bacb&quot;</code> (character <code>&#39;b&#39;</code> appears 2 times).</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;abcde&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>All substrings are valid because every character appears at least once.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function numberOfSubstrings(s: string, k: number): number { let [ans, l] = [0, 0]; const cnt: number[] = Array(26).fill(0); for (const c of s) { const x = c.charCodeAt(0) - 97; ++cnt[x]; while (cnt[x] >= k) { --cnt[s[l++].charCodeAt(0) - 97]; } ans += l; } return ans; }
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
C++
class Solution { public: int possibleStringCount(string word) { int f = 1; for (int i = 1; i < word.size(); ++i) { f += word[i] == word[i - 1]; } return f; } };
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
Go
func possibleStringCount(word string) int { f := 1 for i := 1; i < len(word); i++ { if word[i] == word[i-1] { f++ } } return f }
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
Java
class Solution { public int possibleStringCount(String word) { int f = 1; for (int i = 1; i < word.length(); ++i) { if (word.charAt(i) == word.charAt(i - 1)) { ++f; } } return f; } }
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
Python
class Solution: def possibleStringCount(self, word: str) -> int: return 1 + sum(x == y for x, y in pairwise(word))
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
Rust
impl Solution { pub fn possible_string_count(word: String) -> i32 { 1 + word.as_bytes().windows(2).filter(|w| w[0] == w[1]).count() as i32 } }
3,330
Find the Original Typed String I
Easy
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>Although Alice tried to focus on her typing, she is aware that she may still have done this <strong>at most</strong> <em>once</em>.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abbcccc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;abbcccc&quot;</code>, <code>&quot;abbccc&quot;</code>, <code>&quot;abbcc&quot;</code>, <code>&quot;abbc&quot;</code>, and <code>&quot;abcccc&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;abcd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;abcd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String
TypeScript
function possibleStringCount(word: string): number { let f = 1; for (let i = 1; i < word.length; ++i) { f += word[i] === word[i - 1] ? 1 : 0; } return f; }
3,331
Find Subtree Sizes After Changes
Medium
<p>You are given a tree rooted at node 0 that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>We make the following changes on the tree <strong>one</strong> time <strong>simultaneously</strong> for all nodes <code>x</code> from <code>1</code> to <code>n - 1</code>:</p> <ul> <li>Find the <strong>closest</strong> node <code>y</code> to node <code>x</code> such that <code>y</code> is an ancestor of <code>x</code>, and <code>s[x] == s[y]</code>.</li> <li>If node <code>y</code> does not exist, do nothing.</li> <li>Otherwise, <strong>remove</strong> the edge between <code>x</code> and its current parent and make node <code>y</code> the new parent of <code>x</code> by adding an edge between them.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>size</strong> of the <span data-keyword="subtree">subtree</span> rooted at node <code>i</code> in the <strong>final</strong> tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,1], s = &quot;abaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[6,3,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/graphex1drawio.png" style="width: 230px; height: 277px;" /> <p>The parent of node 3 will change from node 1 to node 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,4,0,1], s = &quot;abbba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[5,2,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/exgraph2drawio.png" style="width: 160px; height: 308px;" /> <p>The following changes will happen at the same time:</p> <ul> <li>The parent of node 4 will change from node 1 to node 0.</li> <li>The parent of node 2 will change from node 4 to node 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String
C++
class Solution { public: vector<int> findSubtreeSizes(vector<int>& parent, string s) { int n = s.size(); vector<int> g[n]; vector<int> d[26]; for (int i = 1; i < n; ++i) { g[parent[i]].push_back(i); } vector<int> ans(n); auto dfs = [&](this auto&& dfs, int i, int fa) -> void { ans[i] = 1; int idx = s[i] - 'a'; d[idx].push_back(i); for (int j : g[i]) { dfs(j, i); } int k = d[idx].size() > 1 ? d[idx][d[idx].size() - 2] : fa; if (k >= 0) { ans[k] += ans[i]; } d[idx].pop_back(); }; dfs(0, -1); return ans; } };
3,331
Find Subtree Sizes After Changes
Medium
<p>You are given a tree rooted at node 0 that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>We make the following changes on the tree <strong>one</strong> time <strong>simultaneously</strong> for all nodes <code>x</code> from <code>1</code> to <code>n - 1</code>:</p> <ul> <li>Find the <strong>closest</strong> node <code>y</code> to node <code>x</code> such that <code>y</code> is an ancestor of <code>x</code>, and <code>s[x] == s[y]</code>.</li> <li>If node <code>y</code> does not exist, do nothing.</li> <li>Otherwise, <strong>remove</strong> the edge between <code>x</code> and its current parent and make node <code>y</code> the new parent of <code>x</code> by adding an edge between them.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>size</strong> of the <span data-keyword="subtree">subtree</span> rooted at node <code>i</code> in the <strong>final</strong> tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,1], s = &quot;abaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[6,3,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/graphex1drawio.png" style="width: 230px; height: 277px;" /> <p>The parent of node 3 will change from node 1 to node 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,4,0,1], s = &quot;abbba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[5,2,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/exgraph2drawio.png" style="width: 160px; height: 308px;" /> <p>The following changes will happen at the same time:</p> <ul> <li>The parent of node 4 will change from node 1 to node 0.</li> <li>The parent of node 2 will change from node 4 to node 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String
Go
func findSubtreeSizes(parent []int, s string) []int { n := len(s) g := make([][]int, n) for i := 1; i < n; i++ { g[parent[i]] = append(g[parent[i]], i) } d := [26][]int{} ans := make([]int, n) var dfs func(int, int) dfs = func(i, fa int) { ans[i] = 1 idx := int(s[i] - 'a') d[idx] = append(d[idx], i) for _, j := range g[i] { dfs(j, i) } k := fa if len(d[idx]) > 1 { k = d[idx][len(d[idx])-2] } if k != -1 { ans[k] += ans[i] } d[idx] = d[idx][:len(d[idx])-1] } dfs(0, -1) return ans }
3,331
Find Subtree Sizes After Changes
Medium
<p>You are given a tree rooted at node 0 that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>We make the following changes on the tree <strong>one</strong> time <strong>simultaneously</strong> for all nodes <code>x</code> from <code>1</code> to <code>n - 1</code>:</p> <ul> <li>Find the <strong>closest</strong> node <code>y</code> to node <code>x</code> such that <code>y</code> is an ancestor of <code>x</code>, and <code>s[x] == s[y]</code>.</li> <li>If node <code>y</code> does not exist, do nothing.</li> <li>Otherwise, <strong>remove</strong> the edge between <code>x</code> and its current parent and make node <code>y</code> the new parent of <code>x</code> by adding an edge between them.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>size</strong> of the <span data-keyword="subtree">subtree</span> rooted at node <code>i</code> in the <strong>final</strong> tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,1], s = &quot;abaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[6,3,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/graphex1drawio.png" style="width: 230px; height: 277px;" /> <p>The parent of node 3 will change from node 1 to node 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,4,0,1], s = &quot;abbba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[5,2,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/exgraph2drawio.png" style="width: 160px; height: 308px;" /> <p>The following changes will happen at the same time:</p> <ul> <li>The parent of node 4 will change from node 1 to node 0.</li> <li>The parent of node 2 will change from node 4 to node 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String
Java
class Solution { private List<Integer>[] g; private List<Integer>[] d; private char[] s; private int[] ans; public int[] findSubtreeSizes(int[] parent, String s) { int n = s.length(); g = new List[n]; d = new List[26]; this.s = s.toCharArray(); Arrays.setAll(g, k -> new ArrayList<>()); Arrays.setAll(d, k -> new ArrayList<>()); for (int i = 1; i < n; ++i) { g[parent[i]].add(i); } ans = new int[n]; dfs(0, -1); return ans; } private void dfs(int i, int fa) { ans[i] = 1; int idx = s[i] - 'a'; d[idx].add(i); for (int j : g[i]) { dfs(j, i); } int k = d[idx].size() > 1 ? d[idx].get(d[idx].size() - 2) : fa; if (k >= 0) { ans[k] += ans[i]; } d[idx].remove(d[idx].size() - 1); } }
3,331
Find Subtree Sizes After Changes
Medium
<p>You are given a tree rooted at node 0 that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>We make the following changes on the tree <strong>one</strong> time <strong>simultaneously</strong> for all nodes <code>x</code> from <code>1</code> to <code>n - 1</code>:</p> <ul> <li>Find the <strong>closest</strong> node <code>y</code> to node <code>x</code> such that <code>y</code> is an ancestor of <code>x</code>, and <code>s[x] == s[y]</code>.</li> <li>If node <code>y</code> does not exist, do nothing.</li> <li>Otherwise, <strong>remove</strong> the edge between <code>x</code> and its current parent and make node <code>y</code> the new parent of <code>x</code> by adding an edge between them.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>size</strong> of the <span data-keyword="subtree">subtree</span> rooted at node <code>i</code> in the <strong>final</strong> tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,1], s = &quot;abaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[6,3,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/graphex1drawio.png" style="width: 230px; height: 277px;" /> <p>The parent of node 3 will change from node 1 to node 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,4,0,1], s = &quot;abbba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[5,2,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/exgraph2drawio.png" style="width: 160px; height: 308px;" /> <p>The following changes will happen at the same time:</p> <ul> <li>The parent of node 4 will change from node 1 to node 0.</li> <li>The parent of node 2 will change from node 4 to node 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String
Python
class Solution: def findSubtreeSizes(self, parent: List[int], s: str) -> List[int]: def dfs(i: int, fa: int): ans[i] = 1 d[s[i]].append(i) for j in g[i]: dfs(j, i) k = fa if len(d[s[i]]) > 1: k = d[s[i]][-2] if k != -1: ans[k] += ans[i] d[s[i]].pop() n = len(s) g = [[] for _ in range(n)] for i in range(1, n): g[parent[i]].append(i) d = defaultdict(list) ans = [0] * n dfs(0, -1) return ans
3,331
Find Subtree Sizes After Changes
Medium
<p>You are given a tree rooted at node 0 that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The tree is represented by an array <code>parent</code> of size <code>n</code>, where <code>parent[i]</code> is the parent of node <code>i</code>. Since node 0 is the root, <code>parent[0] == -1</code>.</p> <p>You are also given a string <code>s</code> of length <code>n</code>, where <code>s[i]</code> is the character assigned to node <code>i</code>.</p> <p>We make the following changes on the tree <strong>one</strong> time <strong>simultaneously</strong> for all nodes <code>x</code> from <code>1</code> to <code>n - 1</code>:</p> <ul> <li>Find the <strong>closest</strong> node <code>y</code> to node <code>x</code> such that <code>y</code> is an ancestor of <code>x</code>, and <code>s[x] == s[y]</code>.</li> <li>If node <code>y</code> does not exist, do nothing.</li> <li>Otherwise, <strong>remove</strong> the edge between <code>x</code> and its current parent and make node <code>y</code> the new parent of <code>x</code> by adding an edge between them.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>size</strong> of the <span data-keyword="subtree">subtree</span> rooted at node <code>i</code> in the <strong>final</strong> tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,0,1,1,1], s = &quot;abaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[6,3,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/graphex1drawio.png" style="width: 230px; height: 277px;" /> <p>The parent of node 3 will change from node 1 to node 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">parent = [-1,0,4,0,1], s = &quot;abbba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">[5,2,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3331.Find%20Subtree%20Sizes%20After%20Changes/images/exgraph2drawio.png" style="width: 160px; height: 308px;" /> <p>The following changes will happen at the same time:</p> <ul> <li>The parent of node 4 will change from node 1 to node 0.</li> <li>The parent of node 2 will change from node 4 to node 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == parent.length == s.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= parent[i] &lt;= n - 1</code> for all <code>i &gt;= 1</code>.</li> <li><code>parent[0] == -1</code></li> <li><code>parent</code> represents a valid tree.</li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Tree; Depth-First Search; Array; Hash Table; String
TypeScript
function findSubtreeSizes(parent: number[], s: string): number[] { const n = parent.length; const g: number[][] = Array.from({ length: n }, () => []); const d: number[][] = Array.from({ length: 26 }, () => []); for (let i = 1; i < n; ++i) { g[parent[i]].push(i); } const ans: number[] = Array(n).fill(1); const dfs = (i: number, fa: number): void => { const idx = s.charCodeAt(i) - 97; d[idx].push(i); for (const j of g[i]) { dfs(j, i); } const k = d[idx].length > 1 ? d[idx].at(-2)! : fa; if (k >= 0) { ans[k] += ans[i]; } d[idx].pop(); }; dfs(0, -1); return ans; }
3,332
Maximum Points Tourist Can Earn
Medium
<p>You are given two integers, <code>n</code> and <code>k</code>, along with two 2D integer arrays, <code>stayScore</code> and <code>travelScore</code>.</p> <p>A tourist is visiting a country with <code>n</code> cities, where each city is <strong>directly</strong> connected to every other city. The tourist&#39;s journey consists of <strong>exactly</strong> <code>k</code> <strong>0-indexed</strong> days, and they can choose <strong>any</strong> city as their starting point.</p> <p>Each day, the tourist has two choices:</p> <ul> <li><strong>Stay in the current city</strong>: If the tourist stays in their current city <code>curr</code> during day <code>i</code>, they will earn <code>stayScore[i][curr]</code> points.</li> <li><strong>Move to another city</strong>: If the tourist moves from their current city <code>curr</code> to city <code>dest</code>, they will earn <code>travelScore[curr][dest]</code> points.</li> </ul> <p>Return the <strong>maximum</strong> possible points the tourist can earn.</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 = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1 and staying in that city.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>n == travelScore.length == travelScore[i].length == stayScore[i].length</code></li> <li><code>k == stayScore.length</code></li> <li><code>1 &lt;= stayScore[i][j] &lt;= 100</code></li> <li><code>0 &lt;= travelScore[i][j] &lt;= 100</code></li> <li><code>travelScore[i][i] == 0</code></li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maxScore(int n, int k, vector<vector<int>>& stayScore, vector<vector<int>>& travelScore) { int f[k + 1][n]; memset(f, 0xc0, sizeof(f)); memset(f[0], 0, sizeof(f[0])); for (int i = 1; i <= k; ++i) { for (int j = 0; j < n; ++j) { for (int h = 0; h < n; ++h) { f[i][j] = max(f[i][j], f[i - 1][h] + (j == h ? stayScore[i - 1][j] : travelScore[h][j])); } } } return *max_element(f[k], f[k] + n); } };
3,332
Maximum Points Tourist Can Earn
Medium
<p>You are given two integers, <code>n</code> and <code>k</code>, along with two 2D integer arrays, <code>stayScore</code> and <code>travelScore</code>.</p> <p>A tourist is visiting a country with <code>n</code> cities, where each city is <strong>directly</strong> connected to every other city. The tourist&#39;s journey consists of <strong>exactly</strong> <code>k</code> <strong>0-indexed</strong> days, and they can choose <strong>any</strong> city as their starting point.</p> <p>Each day, the tourist has two choices:</p> <ul> <li><strong>Stay in the current city</strong>: If the tourist stays in their current city <code>curr</code> during day <code>i</code>, they will earn <code>stayScore[i][curr]</code> points.</li> <li><strong>Move to another city</strong>: If the tourist moves from their current city <code>curr</code> to city <code>dest</code>, they will earn <code>travelScore[curr][dest]</code> points.</li> </ul> <p>Return the <strong>maximum</strong> possible points the tourist can earn.</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 = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1 and staying in that city.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>n == travelScore.length == travelScore[i].length == stayScore[i].length</code></li> <li><code>k == stayScore.length</code></li> <li><code>1 &lt;= stayScore[i][j] &lt;= 100</code></li> <li><code>0 &lt;= travelScore[i][j] &lt;= 100</code></li> <li><code>travelScore[i][i] == 0</code></li> </ul>
Array; Dynamic Programming; Matrix
Go
func maxScore(n int, k int, stayScore [][]int, travelScore [][]int) (ans int) { f := make([][]int, k+1) for i := range f { f[i] = make([]int, n) for j := range f[i] { f[i][j] = math.MinInt32 } } for j := 0; j < n; j++ { f[0][j] = 0 } for i := 1; i <= k; i++ { for j := 0; j < n; j++ { f[i][j] = f[i-1][j] + stayScore[i-1][j] for h := 0; h < n; h++ { if h != j { f[i][j] = max(f[i][j], f[i-1][h]+travelScore[h][j]) } } } } for j := 0; j < n; j++ { ans = max(ans, f[k][j]) } return }
3,332
Maximum Points Tourist Can Earn
Medium
<p>You are given two integers, <code>n</code> and <code>k</code>, along with two 2D integer arrays, <code>stayScore</code> and <code>travelScore</code>.</p> <p>A tourist is visiting a country with <code>n</code> cities, where each city is <strong>directly</strong> connected to every other city. The tourist&#39;s journey consists of <strong>exactly</strong> <code>k</code> <strong>0-indexed</strong> days, and they can choose <strong>any</strong> city as their starting point.</p> <p>Each day, the tourist has two choices:</p> <ul> <li><strong>Stay in the current city</strong>: If the tourist stays in their current city <code>curr</code> during day <code>i</code>, they will earn <code>stayScore[i][curr]</code> points.</li> <li><strong>Move to another city</strong>: If the tourist moves from their current city <code>curr</code> to city <code>dest</code>, they will earn <code>travelScore[curr][dest]</code> points.</li> </ul> <p>Return the <strong>maximum</strong> possible points the tourist can earn.</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 = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1 and staying in that city.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>n == travelScore.length == travelScore[i].length == stayScore[i].length</code></li> <li><code>k == stayScore.length</code></li> <li><code>1 &lt;= stayScore[i][j] &lt;= 100</code></li> <li><code>0 &lt;= travelScore[i][j] &lt;= 100</code></li> <li><code>travelScore[i][i] == 0</code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int maxScore(int n, int k, int[][] stayScore, int[][] travelScore) { int[][] f = new int[k + 1][n]; for (var g : f) { Arrays.fill(g, Integer.MIN_VALUE); } Arrays.fill(f[0], 0); for (int i = 1; i <= k; ++i) { for (int j = 0; j < n; ++j) { for (int h = 0; h < n; ++h) { f[i][j] = Math.max( f[i][j], f[i - 1][h] + (j == h ? stayScore[i - 1][j] : travelScore[h][j])); } } } return Arrays.stream(f[k]).max().getAsInt(); } }
3,332
Maximum Points Tourist Can Earn
Medium
<p>You are given two integers, <code>n</code> and <code>k</code>, along with two 2D integer arrays, <code>stayScore</code> and <code>travelScore</code>.</p> <p>A tourist is visiting a country with <code>n</code> cities, where each city is <strong>directly</strong> connected to every other city. The tourist&#39;s journey consists of <strong>exactly</strong> <code>k</code> <strong>0-indexed</strong> days, and they can choose <strong>any</strong> city as their starting point.</p> <p>Each day, the tourist has two choices:</p> <ul> <li><strong>Stay in the current city</strong>: If the tourist stays in their current city <code>curr</code> during day <code>i</code>, they will earn <code>stayScore[i][curr]</code> points.</li> <li><strong>Move to another city</strong>: If the tourist moves from their current city <code>curr</code> to city <code>dest</code>, they will earn <code>travelScore[curr][dest]</code> points.</li> </ul> <p>Return the <strong>maximum</strong> possible points the tourist can earn.</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 = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1 and staying in that city.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>n == travelScore.length == travelScore[i].length == stayScore[i].length</code></li> <li><code>k == stayScore.length</code></li> <li><code>1 &lt;= stayScore[i][j] &lt;= 100</code></li> <li><code>0 &lt;= travelScore[i][j] &lt;= 100</code></li> <li><code>travelScore[i][i] == 0</code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maxScore( self, n: int, k: int, stayScore: List[List[int]], travelScore: List[List[int]] ) -> int: f = [[-inf] * n for _ in range(k + 1)] f[0] = [0] * n for i in range(1, k + 1): for j in range(n): for h in range(n): f[i][j] = max( f[i][j], f[i - 1][h] + (stayScore[i - 1][j] if j == h else travelScore[h][j]), ) return max(f[k])
3,332
Maximum Points Tourist Can Earn
Medium
<p>You are given two integers, <code>n</code> and <code>k</code>, along with two 2D integer arrays, <code>stayScore</code> and <code>travelScore</code>.</p> <p>A tourist is visiting a country with <code>n</code> cities, where each city is <strong>directly</strong> connected to every other city. The tourist&#39;s journey consists of <strong>exactly</strong> <code>k</code> <strong>0-indexed</strong> days, and they can choose <strong>any</strong> city as their starting point.</p> <p>Each day, the tourist has two choices:</p> <ul> <li><strong>Stay in the current city</strong>: If the tourist stays in their current city <code>curr</code> during day <code>i</code>, they will earn <code>stayScore[i][curr]</code> points.</li> <li><strong>Move to another city</strong>: If the tourist moves from their current city <code>curr</code> to city <code>dest</code>, they will earn <code>travelScore[curr][dest]</code> points.</li> </ul> <p>Return the <strong>maximum</strong> possible points the tourist can earn.</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 = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1 and staying in that city.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>n == travelScore.length == travelScore[i].length == stayScore[i].length</code></li> <li><code>k == stayScore.length</code></li> <li><code>1 &lt;= stayScore[i][j] &lt;= 100</code></li> <li><code>0 &lt;= travelScore[i][j] &lt;= 100</code></li> <li><code>travelScore[i][i] == 0</code></li> </ul>
Array; Dynamic Programming; Matrix
TypeScript
function maxScore(n: number, k: number, stayScore: number[][], travelScore: number[][]): number { const f: number[][] = Array.from({ length: k + 1 }, () => Array(n).fill(-Infinity)); f[0].fill(0); for (let i = 1; i <= k; ++i) { for (let j = 0; j < n; ++j) { for (let h = 0; h < n; ++h) { f[i][j] = Math.max( f[i][j], f[i - 1][h] + (j == h ? stayScore[i - 1][j] : travelScore[h][j]), ); } } } return Math.max(...f[k]); }
3,333
Find the Original Typed String II
Hard
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen. You are also given a <strong>positive</strong> integer <code>k</code>.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type, if she was trying to type a string of size <strong>at least</strong> <code>k</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">word = &quot;aabbccdd&quot;, k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;aabbccdd&quot;</code>, <code>&quot;aabbccd&quot;</code>, <code>&quot;aabbcdd&quot;</code>, <code>&quot;aabccdd&quot;</code>, and <code>&quot;abbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aabbccdd&quot;, k = 8</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;aabbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaabbb&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 2000</code></li> </ul>
String; Dynamic Programming; Prefix Sum
C++
class Solution { public: int possibleStringCount(string word, int k) { const int mod = 1e9 + 7; vector<int> nums; long long ans = 1; int cur = 0; int n = word.size(); for (int i = 0; i < n; ++i) { cur++; if (i == n - 1 || word[i] != word[i + 1]) { if (cur > 1) { if (k > 0) { nums.push_back(cur - 1); } ans = ans * cur % mod; } cur = 0; k--; } } if (k < 1) { return ans; } int m = nums.size(); vector<vector<int>> f(m + 1, vector<int>(k, 0)); f[0][0] = 1; for (int i = 1; i <= m; ++i) { int x = nums[i - 1]; vector<long long> s(k + 1, 0); for (int j = 0; j < k; ++j) { s[j + 1] = (s[j] + f[i - 1][j]) % mod; } for (int j = 0; j < k; ++j) { int l = max(0, j - x); f[i][j] = (s[j + 1] - s[l] + mod) % mod; } } long long sum = 0; for (int j = 0; j < k; ++j) { sum = (sum + f[m][j]) % mod; } return (ans - sum + mod) % mod; } };
3,333
Find the Original Typed String II
Hard
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen. You are also given a <strong>positive</strong> integer <code>k</code>.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type, if she was trying to type a string of size <strong>at least</strong> <code>k</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">word = &quot;aabbccdd&quot;, k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;aabbccdd&quot;</code>, <code>&quot;aabbccd&quot;</code>, <code>&quot;aabbcdd&quot;</code>, <code>&quot;aabccdd&quot;</code>, and <code>&quot;abbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aabbccdd&quot;, k = 8</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;aabbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaabbb&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 2000</code></li> </ul>
String; Dynamic Programming; Prefix Sum
Go
func possibleStringCount(word string, k int) int { const mod = 1_000_000_007 nums := []int{} ans := 1 cur := 0 n := len(word) for i := 0; i < n; i++ { cur++ if i == n-1 || word[i] != word[i+1] { if cur > 1 { if k > 0 { nums = append(nums, cur-1) } ans = ans * cur % mod } cur = 0 k-- } } if k < 1 { return ans } m := len(nums) f := make([][]int, m+1) for i := range f { f[i] = make([]int, k) } f[0][0] = 1 for i := 1; i <= m; i++ { x := nums[i-1] s := make([]int, k+1) for j := 0; j < k; j++ { s[j+1] = (s[j] + f[i-1][j]) % mod } for j := 0; j < k; j++ { l := j - x if l < 0 { l = 0 } f[i][j] = (s[j+1] - s[l] + mod) % mod } } sum := 0 for j := 0; j < k; j++ { sum = (sum + f[m][j]) % mod } return (ans - sum + mod) % mod }
3,333
Find the Original Typed String II
Hard
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen. You are also given a <strong>positive</strong> integer <code>k</code>.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type, if she was trying to type a string of size <strong>at least</strong> <code>k</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">word = &quot;aabbccdd&quot;, k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;aabbccdd&quot;</code>, <code>&quot;aabbccd&quot;</code>, <code>&quot;aabbcdd&quot;</code>, <code>&quot;aabccdd&quot;</code>, and <code>&quot;abbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aabbccdd&quot;, k = 8</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;aabbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaabbb&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 2000</code></li> </ul>
String; Dynamic Programming; Prefix Sum
Java
class Solution { public int possibleStringCount(String word, int k) { final int mod = (int) 1e9 + 7; List<Integer> nums = new ArrayList<>(); long ans = 1; int cur = 0; int n = word.length(); for (int i = 0; i < n; i++) { cur++; if (i == n - 1 || word.charAt(i) != word.charAt(i + 1)) { if (cur > 1) { if (k > 0) { nums.add(cur - 1); } ans = ans * cur % mod; } cur = 0; k--; } } if (k < 1) { return (int) ans; } int m = nums.size(); int[][] f = new int[m + 1][k]; f[0][0] = 1; for (int i = 1; i <= m; i++) { int x = nums.get(i - 1); long[] s = new long[k + 1]; for (int j = 0; j < k; j++) { s[j + 1] = (s[j] + f[i - 1][j]) % mod; } for (int j = 0; j < k; j++) { int l = Math.max(0, j - x); f[i][j] = (int) ((s[j + 1] - s[l] + mod) % mod); } } long sum = 0; for (int j = 0; j < k; j++) { sum = (sum + f[m][j]) % mod; } return (int) ((ans - sum + mod) % mod); } }
3,333
Find the Original Typed String II
Hard
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen. You are also given a <strong>positive</strong> integer <code>k</code>.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type, if she was trying to type a string of size <strong>at least</strong> <code>k</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">word = &quot;aabbccdd&quot;, k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;aabbccdd&quot;</code>, <code>&quot;aabbccd&quot;</code>, <code>&quot;aabbcdd&quot;</code>, <code>&quot;aabccdd&quot;</code>, and <code>&quot;abbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aabbccdd&quot;, k = 8</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;aabbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaabbb&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 2000</code></li> </ul>
String; Dynamic Programming; Prefix Sum
Python
class Solution: def possibleStringCount(self, word: str, k: int) -> int: mod = 10**9 + 7 nums = [] ans = 1 cur = 0 for i, c in enumerate(word): cur += 1 if i == len(word) - 1 or c != word[i + 1]: if cur > 1: if k > 0: nums.append(cur - 1) ans = ans * cur % mod cur = 0 k -= 1 if k < 1: return ans m = len(nums) f = [[0] * k for _ in range(m + 1)] f[0][0] = 1 for i, x in enumerate(nums, 1): s = list(accumulate(f[i - 1], initial=0)) for j in range(k): f[i][j] = (s[j + 1] - s[j - min(x, j)] + mod) % mod return (ans - sum(f[m][j] for j in range(k))) % mod
3,333
Find the Original Typed String II
Hard
<p>Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and <strong>may</strong> press a key for too long, resulting in a character being typed <strong>multiple</strong> times.</p> <p>You are given a string <code>word</code>, which represents the <strong>final</strong> output displayed on Alice&#39;s screen. You are also given a <strong>positive</strong> integer <code>k</code>.</p> <p>Return the total number of <em>possible</em> original strings that Alice <em>might</em> have intended to type, if she was trying to type a string of size <strong>at least</strong> <code>k</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">word = &quot;aabbccdd&quot;, k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The possible strings are: <code>&quot;aabbccdd&quot;</code>, <code>&quot;aabbccd&quot;</code>, <code>&quot;aabbcdd&quot;</code>, <code>&quot;aabccdd&quot;</code>, and <code>&quot;abbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aabbccdd&quot;, k = 8</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible string is <code>&quot;aabbccdd&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;aaabbb&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 2000</code></li> </ul>
String; Dynamic Programming; Prefix Sum
TypeScript
function possibleStringCount(word: string, k: number): number { const mod = 1_000_000_007; const nums: number[] = []; let ans = 1; let cur = 0; const n = word.length; for (let i = 0; i < n; i++) { cur++; if (i === n - 1 || word[i] !== word[i + 1]) { if (cur > 1) { if (k > 0) { nums.push(cur - 1); } ans = (ans * cur) % mod; } cur = 0; k--; } } if (k < 1) { return ans; } const m = nums.length; const f: number[][] = Array.from({ length: m + 1 }, () => Array(k).fill(0)); f[0][0] = 1; for (let i = 1; i <= m; i++) { const x = nums[i - 1]; const s: number[] = Array(k + 1).fill(0); for (let j = 0; j < k; j++) { s[j + 1] = (s[j] + f[i - 1][j]) % mod; } for (let j = 0; j < k; j++) { const l = Math.max(0, j - x); f[i][j] = (s[j + 1] - s[l] + mod) % mod; } } let sum = 0; for (let j = 0; j < k; j++) { sum = (sum + f[m][j]) % mod; } return (ans - sum + mod) % mod; }
3,334
Find the Maximum Factor Score of Array
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>The <strong>factor score</strong> of an array is defined as the <em>product</em> of the LCM and GCD of all elements of that array.</p> <p>Return the <strong>maximum factor score</strong> of <code>nums</code> after removing <strong>at most</strong> one element from it.</p> <p><strong>Note</strong> that <em>both</em> the <span data-keyword="lcm-function">LCM</span> and <span data-keyword="gcd-function">GCD</span> of a single number are the number itself, and the <em>factor score</em> of an <strong>empty</strong> array is 0.</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 = [2,4,8,16]</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of <code>4 * 16 = 64</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,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">60</span></p> <p><strong>Explanation:</strong></p> <p>The maximum factor score of 60 can be obtained without removing any elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3]</span></p> <p><strong>Output:</strong> 9</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Array; Math; Number Theory
C++
class Solution { public: long long maxScore(vector<int>& nums) { int n = nums.size(); vector<long long> sufGcd(n + 1, 0); vector<long long> sufLcm(n + 1, 1); for (int i = n - 1; i >= 0; --i) { sufGcd[i] = gcd(sufGcd[i + 1], nums[i]); sufLcm[i] = lcm(sufLcm[i + 1], nums[i]); } long long ans = sufGcd[0] * sufLcm[0]; long long preGcd = 0, preLcm = 1; for (int i = 0; i < n; ++i) { ans = max(ans, gcd(preGcd, sufGcd[i + 1]) * lcm(preLcm, sufLcm[i + 1])); preGcd = gcd(preGcd, nums[i]); preLcm = lcm(preLcm, nums[i]); } return ans; } };
3,334
Find the Maximum Factor Score of Array
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>The <strong>factor score</strong> of an array is defined as the <em>product</em> of the LCM and GCD of all elements of that array.</p> <p>Return the <strong>maximum factor score</strong> of <code>nums</code> after removing <strong>at most</strong> one element from it.</p> <p><strong>Note</strong> that <em>both</em> the <span data-keyword="lcm-function">LCM</span> and <span data-keyword="gcd-function">GCD</span> of a single number are the number itself, and the <em>factor score</em> of an <strong>empty</strong> array is 0.</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 = [2,4,8,16]</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of <code>4 * 16 = 64</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,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">60</span></p> <p><strong>Explanation:</strong></p> <p>The maximum factor score of 60 can be obtained without removing any elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3]</span></p> <p><strong>Output:</strong> 9</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Array; Math; Number Theory
Go
func maxScore(nums []int) int64 { n := len(nums) sufGcd := make([]int64, n+1) sufLcm := make([]int64, n+1) sufLcm[n] = 1 for i := n - 1; i >= 0; i-- { sufGcd[i] = gcd(sufGcd[i+1], int64(nums[i])) sufLcm[i] = lcm(sufLcm[i+1], int64(nums[i])) } ans := sufGcd[0] * sufLcm[0] preGcd, preLcm := int64(0), int64(1) for i := 0; i < n; i++ { ans = max(ans, gcd(preGcd, sufGcd[i+1])*lcm(preLcm, sufLcm[i+1])) preGcd = gcd(preGcd, int64(nums[i])) preLcm = lcm(preLcm, int64(nums[i])) } return ans } func gcd(a, b int64) int64 { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b int64) int64 { return a / gcd(a, b) * b }
3,334
Find the Maximum Factor Score of Array
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>The <strong>factor score</strong> of an array is defined as the <em>product</em> of the LCM and GCD of all elements of that array.</p> <p>Return the <strong>maximum factor score</strong> of <code>nums</code> after removing <strong>at most</strong> one element from it.</p> <p><strong>Note</strong> that <em>both</em> the <span data-keyword="lcm-function">LCM</span> and <span data-keyword="gcd-function">GCD</span> of a single number are the number itself, and the <em>factor score</em> of an <strong>empty</strong> array is 0.</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 = [2,4,8,16]</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of <code>4 * 16 = 64</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,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">60</span></p> <p><strong>Explanation:</strong></p> <p>The maximum factor score of 60 can be obtained without removing any elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3]</span></p> <p><strong>Output:</strong> 9</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Array; Math; Number Theory
Java
class Solution { public long maxScore(int[] nums) { int n = nums.length; long[] sufGcd = new long[n + 1]; long[] sufLcm = new long[n + 1]; sufLcm[n] = 1; for (int i = n - 1; i >= 0; --i) { sufGcd[i] = gcd(sufGcd[i + 1], nums[i]); sufLcm[i] = lcm(sufLcm[i + 1], nums[i]); } long ans = sufGcd[0] * sufLcm[0]; long preGcd = 0, preLcm = 1; for (int i = 0; i < n; ++i) { ans = Math.max(ans, gcd(preGcd, sufGcd[i + 1]) * lcm(preLcm, sufLcm[i + 1])); preGcd = gcd(preGcd, nums[i]); preLcm = lcm(preLcm, nums[i]); } return ans; } private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private long lcm(long a, long b) { return a / gcd(a, b) * b; } }
3,334
Find the Maximum Factor Score of Array
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>The <strong>factor score</strong> of an array is defined as the <em>product</em> of the LCM and GCD of all elements of that array.</p> <p>Return the <strong>maximum factor score</strong> of <code>nums</code> after removing <strong>at most</strong> one element from it.</p> <p><strong>Note</strong> that <em>both</em> the <span data-keyword="lcm-function">LCM</span> and <span data-keyword="gcd-function">GCD</span> of a single number are the number itself, and the <em>factor score</em> of an <strong>empty</strong> array is 0.</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 = [2,4,8,16]</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of <code>4 * 16 = 64</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,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">60</span></p> <p><strong>Explanation:</strong></p> <p>The maximum factor score of 60 can be obtained without removing any elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3]</span></p> <p><strong>Output:</strong> 9</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Array; Math; Number Theory
Python
class Solution: def maxScore(self, nums: List[int]) -> int: n = len(nums) suf_gcd = [0] * (n + 1) suf_lcm = [0] * n + [1] for i in range(n - 1, -1, -1): suf_gcd[i] = gcd(suf_gcd[i + 1], nums[i]) suf_lcm[i] = lcm(suf_lcm[i + 1], nums[i]) ans = suf_gcd[0] * suf_lcm[0] pre_gcd, pre_lcm = 0, 1 for i, x in enumerate(nums): ans = max(ans, gcd(pre_gcd, suf_gcd[i + 1]) * lcm(pre_lcm, suf_lcm[i + 1])) pre_gcd = gcd(pre_gcd, x) pre_lcm = lcm(pre_lcm, x) return ans
3,334
Find the Maximum Factor Score of Array
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>The <strong>factor score</strong> of an array is defined as the <em>product</em> of the LCM and GCD of all elements of that array.</p> <p>Return the <strong>maximum factor score</strong> of <code>nums</code> after removing <strong>at most</strong> one element from it.</p> <p><strong>Note</strong> that <em>both</em> the <span data-keyword="lcm-function">LCM</span> and <span data-keyword="gcd-function">GCD</span> of a single number are the number itself, and the <em>factor score</em> of an <strong>empty</strong> array is 0.</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 = [2,4,8,16]</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>On removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of <code>4 * 16 = 64</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,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">60</span></p> <p><strong>Explanation:</strong></p> <p>The maximum factor score of 60 can be obtained without removing any elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3]</span></p> <p><strong>Output:</strong> 9</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Array; Math; Number Theory
TypeScript
function maxScore(nums: number[]): number { const n = nums.length; const sufGcd: number[] = Array(n + 1).fill(0); const sufLcm: number[] = Array(n + 1).fill(1); for (let i = n - 1; i >= 0; i--) { sufGcd[i] = gcd(sufGcd[i + 1], nums[i]); sufLcm[i] = lcm(sufLcm[i + 1], nums[i]); } let ans = sufGcd[0] * sufLcm[0]; let preGcd = 0, preLcm = 1; for (let i = 0; i < n; i++) { ans = Math.max(ans, gcd(preGcd, sufGcd[i + 1]) * lcm(preLcm, sufLcm[i + 1])); preGcd = gcd(preGcd, nums[i]); preLcm = lcm(preLcm, nums[i]); } return ans; } function gcd(a: number, b: number): number { return b === 0 ? a : gcd(b, a % b); } function lcm(a: number, b: number): number { return (a / gcd(a, b)) * b; }
3,335
Total Characters in String After Transformations I
Medium
<p>You are given a string <code>s</code> and an integer <code>t</code>, representing the number of <strong>transformations</strong> to perform. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>If the character is <code>&#39;z&#39;</code>, replace it with the string <code>&quot;ab&quot;</code>.</li> <li>Otherwise, replace it with the <strong>next</strong> character in the alphabet. For example, <code>&#39;a&#39;</code> is replaced with <code>&#39;b&#39;</code>, <code>&#39;b&#39;</code> is replaced with <code>&#39;c&#39;</code>, and so on.</li> </ul> <p>Return the <strong>length</strong> of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong><!-- notionvc: eb142f2b-b818-4064-8be5-e5a36b07557a --> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</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;azbk&quot;, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;l&#39;</code></li> <li>String after the first transformation: <code>&quot;babcl&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;babcl&quot;</code>, which has 5 characters.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
C++
class Solution { public: int lengthAfterTransformations(string s, int t) { const int mod = 1e9 + 7; vector<vector<int>> f(t + 1, vector<int>(26, 0)); for (char c : s) { f[0][c - 'a']++; } for (int i = 1; i <= t; ++i) { f[i][0] = f[i - 1][25] % mod; f[i][1] = (f[i - 1][0] + f[i - 1][25]) % mod; for (int j = 2; j < 26; ++j) { f[i][j] = f[i - 1][j - 1] % mod; } } int ans = 0; for (int j = 0; j < 26; ++j) { ans = (ans + f[t][j]) % mod; } return ans; } };
3,335
Total Characters in String After Transformations I
Medium
<p>You are given a string <code>s</code> and an integer <code>t</code>, representing the number of <strong>transformations</strong> to perform. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>If the character is <code>&#39;z&#39;</code>, replace it with the string <code>&quot;ab&quot;</code>.</li> <li>Otherwise, replace it with the <strong>next</strong> character in the alphabet. For example, <code>&#39;a&#39;</code> is replaced with <code>&#39;b&#39;</code>, <code>&#39;b&#39;</code> is replaced with <code>&#39;c&#39;</code>, and so on.</li> </ul> <p>Return the <strong>length</strong> of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong><!-- notionvc: eb142f2b-b818-4064-8be5-e5a36b07557a --> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</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;azbk&quot;, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;l&#39;</code></li> <li>String after the first transformation: <code>&quot;babcl&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;babcl&quot;</code>, which has 5 characters.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Go
func lengthAfterTransformations(s string, t int) int { const mod = 1_000_000_007 f := make([][]int, t+1) for i := range f { f[i] = make([]int, 26) } for _, c := range s { f[0][c-'a']++ } for i := 1; i <= t; i++ { f[i][0] = f[i-1][25] % mod f[i][1] = (f[i-1][0] + f[i-1][25]) % mod for j := 2; j < 26; j++ { f[i][j] = f[i-1][j-1] % mod } } ans := 0 for j := 0; j < 26; j++ { ans = (ans + f[t][j]) % mod } return ans }
3,335
Total Characters in String After Transformations I
Medium
<p>You are given a string <code>s</code> and an integer <code>t</code>, representing the number of <strong>transformations</strong> to perform. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>If the character is <code>&#39;z&#39;</code>, replace it with the string <code>&quot;ab&quot;</code>.</li> <li>Otherwise, replace it with the <strong>next</strong> character in the alphabet. For example, <code>&#39;a&#39;</code> is replaced with <code>&#39;b&#39;</code>, <code>&#39;b&#39;</code> is replaced with <code>&#39;c&#39;</code>, and so on.</li> </ul> <p>Return the <strong>length</strong> of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong><!-- notionvc: eb142f2b-b818-4064-8be5-e5a36b07557a --> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</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;azbk&quot;, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;l&#39;</code></li> <li>String after the first transformation: <code>&quot;babcl&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;babcl&quot;</code>, which has 5 characters.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Java
class Solution { public int lengthAfterTransformations(String s, int t) { final int mod = (int) 1e9 + 7; int[][] f = new int[t + 1][26]; for (char c : s.toCharArray()) { f[0][c - 'a']++; } for (int i = 1; i <= t; ++i) { f[i][0] = f[i - 1][25] % mod; f[i][1] = (f[i - 1][0] + f[i - 1][25]) % mod; for (int j = 2; j < 26; j++) { f[i][j] = f[i - 1][j - 1] % mod; } } int ans = 0; for (int j = 0; j < 26; ++j) { ans = (ans + f[t][j]) % mod; } return ans; } }
3,335
Total Characters in String After Transformations I
Medium
<p>You are given a string <code>s</code> and an integer <code>t</code>, representing the number of <strong>transformations</strong> to perform. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>If the character is <code>&#39;z&#39;</code>, replace it with the string <code>&quot;ab&quot;</code>.</li> <li>Otherwise, replace it with the <strong>next</strong> character in the alphabet. For example, <code>&#39;a&#39;</code> is replaced with <code>&#39;b&#39;</code>, <code>&#39;b&#39;</code> is replaced with <code>&#39;c&#39;</code>, and so on.</li> </ul> <p>Return the <strong>length</strong> of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong><!-- notionvc: eb142f2b-b818-4064-8be5-e5a36b07557a --> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</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;azbk&quot;, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;l&#39;</code></li> <li>String after the first transformation: <code>&quot;babcl&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;babcl&quot;</code>, which has 5 characters.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Python
class Solution: def lengthAfterTransformations(self, s: str, t: int) -> int: f = [[0] * 26 for _ in range(t + 1)] for c in s: f[0][ord(c) - ord("a")] += 1 for i in range(1, t + 1): f[i][0] = f[i - 1][25] f[i][1] = f[i - 1][0] + f[i - 1][25] for j in range(2, 26): f[i][j] = f[i - 1][j - 1] mod = 10**9 + 7 return sum(f[t]) % mod
3,335
Total Characters in String After Transformations I
Medium
<p>You are given a string <code>s</code> and an integer <code>t</code>, representing the number of <strong>transformations</strong> to perform. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>If the character is <code>&#39;z&#39;</code>, replace it with the string <code>&quot;ab&quot;</code>.</li> <li>Otherwise, replace it with the <strong>next</strong> character in the alphabet. For example, <code>&#39;a&#39;</code> is replaced with <code>&#39;b&#39;</code>, <code>&#39;b&#39;</code> is replaced with <code>&#39;c&#39;</code>, and so on.</li> </ul> <p>Return the <strong>length</strong> of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong><!-- notionvc: eb142f2b-b818-4064-8be5-e5a36b07557a --> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</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;azbk&quot;, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>First Transformation (t = 1)</strong>: <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code></li> <li><code>&#39;z&#39;</code> becomes <code>&quot;ab&quot;</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;l&#39;</code></li> <li>String after the first transformation: <code>&quot;babcl&quot;</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>&quot;babcl&quot;</code>, which has 5 characters.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
TypeScript
function lengthAfterTransformations(s: string, t: number): number { const mod = 1_000_000_007; const f: number[][] = Array.from({ length: t + 1 }, () => Array(26).fill(0)); for (const c of s) { f[0][c.charCodeAt(0) - 'a'.charCodeAt(0)]++; } for (let i = 1; i <= t; i++) { f[i][0] = f[i - 1][25] % mod; f[i][1] = (f[i - 1][0] + f[i - 1][25]) % mod; for (let j = 2; j < 26; j++) { f[i][j] = f[i - 1][j - 1] % mod; } } let ans = 0; for (let j = 0; j < 26; j++) { ans = (ans + f[t][j]) % mod; } return ans; }
3,337
Total Characters in String After Transformations II
Hard
<p>You are given a string <code>s</code> consisting of lowercase English letters, an integer <code>t</code> representing the number of <strong>transformations</strong> to perform, and an array <code>nums</code> of size 26. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>Replace <code>s[i]</code> with the <strong>next</strong> <code>nums[s[i] - &#39;a&#39;]</code> consecutive characters in the alphabet. For example, if <code>s[i] = &#39;a&#39;</code> and <code>nums[0] = 3</code>, the character <code>&#39;a&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;bcd&quot;</code>.</li> <li>The transformation <strong>wraps</strong> around the alphabet if it exceeds <code>&#39;z&#39;</code>. For example, if <code>s[i] = &#39;y&#39;</code> and <code>nums[24] = 3</code>, the character <code>&#39;y&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;zab&quot;</code>.</li> </ul> <p>Return the length of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code> as <code>nums[0] == 1</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li> <p><strong>Second Transformation (t = 2):</strong></p> <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code> as <code>nums[3] == 1</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</p> </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;azbk&quot;, t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;bc&#39;</code> as <code>nums[0] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;cd&#39;</code> as <code>nums[1] == 2</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;lm&#39;</code> as <code>nums[10] == 2</code></li> <li>String after the first transformation: <code>&quot;bcabcdlm&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;bcabcdlm&quot;</code>, which has 8 characters.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">nums.length == 26</font></code></li> <li><code><font face="monospace">1 &lt;= nums[i] &lt;= 25</font></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
C++
class Solution { public: static constexpr int MOD = 1e9 + 7; static constexpr int M = 26; using Matrix = vector<vector<int>>; Matrix matmul(const Matrix& a, const Matrix& b) { int n = a.size(), p = b.size(), q = b[0].size(); Matrix res(n, vector<int>(q, 0)); for (int i = 0; i < n; ++i) { for (int k = 0; k < p; ++k) { if (a[i][k]) { for (int j = 0; j < q; ++j) { res[i][j] = (res[i][j] + 1LL * a[i][k] * b[k][j] % MOD) % MOD; } } } } return res; } Matrix matpow(Matrix mat, int power) { Matrix res(M, vector<int>(M, 0)); for (int i = 0; i < M; ++i) res[i][i] = 1; while (power) { if (power % 2) res = matmul(res, mat); mat = matmul(mat, mat); power /= 2; } return res; } int lengthAfterTransformations(string s, int t, vector<int>& nums) { vector<int> cnt(M, 0); for (char c : s) { cnt[c - 'a']++; } Matrix matrix(M, vector<int>(M, 0)); for (int i = 0; i < M; ++i) { for (int j = 1; j <= nums[i]; ++j) { matrix[i][(i + j) % M] = 1; } } Matrix cntMat(1, vector<int>(M)); for (int i = 0; i < M; ++i) cntMat[0][i] = cnt[i]; Matrix factor = matpow(matrix, t); Matrix result = matmul(cntMat, factor); int ans = 0; for (int x : result[0]) { ans = (ans + x) % MOD; } return ans; } };
3,337
Total Characters in String After Transformations II
Hard
<p>You are given a string <code>s</code> consisting of lowercase English letters, an integer <code>t</code> representing the number of <strong>transformations</strong> to perform, and an array <code>nums</code> of size 26. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>Replace <code>s[i]</code> with the <strong>next</strong> <code>nums[s[i] - &#39;a&#39;]</code> consecutive characters in the alphabet. For example, if <code>s[i] = &#39;a&#39;</code> and <code>nums[0] = 3</code>, the character <code>&#39;a&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;bcd&quot;</code>.</li> <li>The transformation <strong>wraps</strong> around the alphabet if it exceeds <code>&#39;z&#39;</code>. For example, if <code>s[i] = &#39;y&#39;</code> and <code>nums[24] = 3</code>, the character <code>&#39;y&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;zab&quot;</code>.</li> </ul> <p>Return the length of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code> as <code>nums[0] == 1</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li> <p><strong>Second Transformation (t = 2):</strong></p> <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code> as <code>nums[3] == 1</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</p> </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;azbk&quot;, t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;bc&#39;</code> as <code>nums[0] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;cd&#39;</code> as <code>nums[1] == 2</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;lm&#39;</code> as <code>nums[10] == 2</code></li> <li>String after the first transformation: <code>&quot;bcabcdlm&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;bcabcdlm&quot;</code>, which has 8 characters.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">nums.length == 26</font></code></li> <li><code><font face="monospace">1 &lt;= nums[i] &lt;= 25</font></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Go
func lengthAfterTransformations(s string, t int, nums []int) int { const MOD = 1e9 + 7 const M = 26 cnt := make([]int, M) for _, c := range s { cnt[int(c-'a')]++ } matrix := make([][]int, M) for i := 0; i < M; i++ { matrix[i] = make([]int, M) for j := 1; j <= nums[i]; j++ { matrix[i][(i+j)%M] = 1 } } matmul := func(a, b [][]int) [][]int { n, p, q := len(a), len(b), len(b[0]) res := make([][]int, n) for i := 0; i < n; i++ { res[i] = make([]int, q) for k := 0; k < p; k++ { if a[i][k] != 0 { for j := 0; j < q; j++ { res[i][j] = (res[i][j] + a[i][k]*b[k][j]%MOD) % MOD } } } } return res } matpow := func(mat [][]int, power int) [][]int { res := make([][]int, M) for i := 0; i < M; i++ { res[i] = make([]int, M) res[i][i] = 1 } for power > 0 { if power%2 == 1 { res = matmul(res, mat) } mat = matmul(mat, mat) power /= 2 } return res } cntMat := [][]int{make([]int, M)} copy(cntMat[0], cnt) factor := matpow(matrix, t) result := matmul(cntMat, factor) ans := 0 for _, v := range result[0] { ans = (ans + v) % MOD } return ans }
3,337
Total Characters in String After Transformations II
Hard
<p>You are given a string <code>s</code> consisting of lowercase English letters, an integer <code>t</code> representing the number of <strong>transformations</strong> to perform, and an array <code>nums</code> of size 26. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>Replace <code>s[i]</code> with the <strong>next</strong> <code>nums[s[i] - &#39;a&#39;]</code> consecutive characters in the alphabet. For example, if <code>s[i] = &#39;a&#39;</code> and <code>nums[0] = 3</code>, the character <code>&#39;a&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;bcd&quot;</code>.</li> <li>The transformation <strong>wraps</strong> around the alphabet if it exceeds <code>&#39;z&#39;</code>. For example, if <code>s[i] = &#39;y&#39;</code> and <code>nums[24] = 3</code>, the character <code>&#39;y&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;zab&quot;</code>.</li> </ul> <p>Return the length of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code> as <code>nums[0] == 1</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li> <p><strong>Second Transformation (t = 2):</strong></p> <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code> as <code>nums[3] == 1</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</p> </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;azbk&quot;, t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;bc&#39;</code> as <code>nums[0] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;cd&#39;</code> as <code>nums[1] == 2</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;lm&#39;</code> as <code>nums[10] == 2</code></li> <li>String after the first transformation: <code>&quot;bcabcdlm&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;bcabcdlm&quot;</code>, which has 8 characters.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">nums.length == 26</font></code></li> <li><code><font face="monospace">1 &lt;= nums[i] &lt;= 25</font></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Java
class Solution { private final int mod = (int) 1e9 + 7; public int lengthAfterTransformations(String s, int t, List<Integer> nums) { final int m = 26; int[] cnt = new int[m]; for (char c : s.toCharArray()) { cnt[c - 'a']++; } int[][] matrix = new int[m][m]; for (int i = 0; i < m; i++) { int num = nums.get(i); for (int j = 1; j <= num; j++) { matrix[i][(i + j) % m] = 1; } } int[][] factor = matpow(matrix, t, m); int[] result = vectorMatrixMultiply(cnt, factor); int ans = 0; for (int val : result) { ans = (ans + val) % mod; } return ans; } private int[][] matmul(int[][] a, int[][] b) { int n = a.length; int p = b.length; int q = b[0].length; int[][] res = new int[n][q]; for (int i = 0; i < n; i++) { for (int k = 0; k < p; k++) { if (a[i][k] == 0) continue; for (int j = 0; j < q; j++) { res[i][j] = (int) ((res[i][j] + 1L * a[i][k] * b[k][j]) % mod); } } } return res; } private int[][] matpow(int[][] mat, int power, int m) { int[][] res = new int[m][m]; for (int i = 0; i < m; i++) { res[i][i] = 1; } while (power > 0) { if ((power & 1) != 0) { res = matmul(res, mat); } mat = matmul(mat, mat); power >>= 1; } return res; } private int[] vectorMatrixMultiply(int[] vector, int[][] matrix) { int n = matrix.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { long sum = 0; for (int j = 0; j < n; j++) { sum = (sum + 1L * vector[j] * matrix[j][i]) % mod; } result[i] = (int) sum; } return result; } }
3,337
Total Characters in String After Transformations II
Hard
<p>You are given a string <code>s</code> consisting of lowercase English letters, an integer <code>t</code> representing the number of <strong>transformations</strong> to perform, and an array <code>nums</code> of size 26. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>Replace <code>s[i]</code> with the <strong>next</strong> <code>nums[s[i] - &#39;a&#39;]</code> consecutive characters in the alphabet. For example, if <code>s[i] = &#39;a&#39;</code> and <code>nums[0] = 3</code>, the character <code>&#39;a&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;bcd&quot;</code>.</li> <li>The transformation <strong>wraps</strong> around the alphabet if it exceeds <code>&#39;z&#39;</code>. For example, if <code>s[i] = &#39;y&#39;</code> and <code>nums[24] = 3</code>, the character <code>&#39;y&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;zab&quot;</code>.</li> </ul> <p>Return the length of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code> as <code>nums[0] == 1</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li> <p><strong>Second Transformation (t = 2):</strong></p> <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code> as <code>nums[3] == 1</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</p> </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;azbk&quot;, t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;bc&#39;</code> as <code>nums[0] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;cd&#39;</code> as <code>nums[1] == 2</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;lm&#39;</code> as <code>nums[10] == 2</code></li> <li>String after the first transformation: <code>&quot;bcabcdlm&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;bcabcdlm&quot;</code>, which has 8 characters.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">nums.length == 26</font></code></li> <li><code><font face="monospace">1 &lt;= nums[i] &lt;= 25</font></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
Python
class Solution: def lengthAfterTransformations(self, s: str, t: int, nums: List[int]) -> int: mod = 10**9 + 7 m = 26 cnt = [0] * m for c in s: cnt[ord(c) - ord("a")] += 1 matrix = [[0] * m for _ in range(m)] for i, x in enumerate(nums): for j in range(1, x + 1): matrix[i][(i + j) % m] = 1 def matmul(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: n, p, q = len(a), len(b), len(b[0]) res = [[0] * q for _ in range(n)] for i in range(n): for k in range(p): if a[i][k]: for j in range(q): res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % mod return res def matpow(mat: List[List[int]], power: int) -> List[List[int]]: res = [[int(i == j) for j in range(m)] for i in range(m)] while power: if power % 2: res = matmul(res, mat) mat = matmul(mat, mat) power //= 2 return res cnt = [cnt] factor = matpow(matrix, t) result = matmul(cnt, factor)[0] ans = sum(result) % mod return ans
3,337
Total Characters in String After Transformations II
Hard
<p>You are given a string <code>s</code> consisting of lowercase English letters, an integer <code>t</code> representing the number of <strong>transformations</strong> to perform, and an array <code>nums</code> of size 26. In one <strong>transformation</strong>, every character in <code>s</code> is replaced according to the following rules:</p> <ul> <li>Replace <code>s[i]</code> with the <strong>next</strong> <code>nums[s[i] - &#39;a&#39;]</code> consecutive characters in the alphabet. For example, if <code>s[i] = &#39;a&#39;</code> and <code>nums[0] = 3</code>, the character <code>&#39;a&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;bcd&quot;</code>.</li> <li>The transformation <strong>wraps</strong> around the alphabet if it exceeds <code>&#39;z&#39;</code>. For example, if <code>s[i] = &#39;y&#39;</code> and <code>nums[24] = 3</code>, the character <code>&#39;y&#39;</code> transforms into the next 3 consecutive characters ahead of it, which results in <code>&quot;zab&quot;</code>.</li> </ul> <p>Return the length of the resulting string after <strong>exactly</strong> <code>t</code> transformations.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">s = &quot;abcyy&quot;, t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;b&#39;</code> as <code>nums[0] == 1</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li><code>&#39;y&#39;</code> becomes <code>&#39;z&#39;</code> as <code>nums[24] == 1</code></li> <li>String after the first transformation: <code>&quot;bcdzz&quot;</code></li> </ul> </li> <li> <p><strong>Second Transformation (t = 2):</strong></p> <ul> <li><code>&#39;b&#39;</code> becomes <code>&#39;c&#39;</code> as <code>nums[1] == 1</code></li> <li><code>&#39;c&#39;</code> becomes <code>&#39;d&#39;</code> as <code>nums[2] == 1</code></li> <li><code>&#39;d&#39;</code> becomes <code>&#39;e&#39;</code> as <code>nums[3] == 1</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li>String after the second transformation: <code>&quot;cdeabab&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;cdeabab&quot;</code>, which has 7 characters.</p> </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;azbk&quot;, t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p><strong>First Transformation (t = 1):</strong></p> <ul> <li><code>&#39;a&#39;</code> becomes <code>&#39;bc&#39;</code> as <code>nums[0] == 2</code></li> <li><code>&#39;z&#39;</code> becomes <code>&#39;ab&#39;</code> as <code>nums[25] == 2</code></li> <li><code>&#39;b&#39;</code> becomes <code>&#39;cd&#39;</code> as <code>nums[1] == 2</code></li> <li><code>&#39;k&#39;</code> becomes <code>&#39;lm&#39;</code> as <code>nums[10] == 2</code></li> <li>String after the first transformation: <code>&quot;bcabcdlm&quot;</code></li> </ul> </li> <li> <p><strong>Final Length of the string:</strong> The string is <code>&quot;bcabcdlm&quot;</code>, which has 8 characters.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= t &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">nums.length == 26</font></code></li> <li><code><font face="monospace">1 &lt;= nums[i] &lt;= 25</font></code></li> </ul>
Hash Table; Math; String; Dynamic Programming; Counting
TypeScript
function lengthAfterTransformations(s: string, t: number, nums: number[]): number { const MOD = BigInt(1e9 + 7); const M = 26; const cnt: number[] = Array(M).fill(0); for (const c of s) { cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]++; } const matrix: number[][] = Array.from({ length: M }, () => Array(M).fill(0)); for (let i = 0; i < M; i++) { for (let j = 1; j <= nums[i]; j++) { matrix[i][(i + j) % M] = 1; } } const matmul = (a: number[][], b: number[][]): number[][] => { const n = a.length, p = b.length, q = b[0].length; const res: number[][] = Array.from({ length: n }, () => Array(q).fill(0)); for (let i = 0; i < n; i++) { for (let k = 0; k < p; k++) { const aik = BigInt(a[i][k]); if (aik !== BigInt(0)) { for (let j = 0; j < q; j++) { const product = aik * BigInt(b[k][j]); const sum = BigInt(res[i][j]) + product; res[i][j] = Number(sum % MOD); } } } } return res; }; const matpow = (mat: number[][], power: number): number[][] => { let res: number[][] = Array.from({ length: M }, (_, i) => Array.from({ length: M }, (_, j) => (i === j ? 1 : 0)), ); while (power > 0) { if (power % 2 === 1) res = matmul(res, mat); mat = matmul(mat, mat); power = Math.floor(power / 2); } return res; }; const cntMat: number[][] = [cnt.slice()]; const factor = matpow(matrix, t); const result = matmul(cntMat, factor); let ans = 0n; for (const v of result[0]) { ans = (ans + BigInt(v)) % MOD; } return Number(ans); }
3,338
Second Highest Salary II
Medium
<p>Table: <code>employees</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | emp_id | int | | salary | int | | dept | varchar | +------------------+---------+ emp_id is the unique key for this table. Each row of this table contains information about an employee including their ID, salary, and department. </pre> <p>Write a solution to find the employees who earn the <strong>second-highest salary</strong> in each department. If <strong>multiple employees have the second-highest salary</strong>, <strong>include</strong> <strong>all employees</strong> with <strong>that salary</strong>.</p> <p>Return <em>the result table</em> <em>ordered by</em> <code>emp_id</code> <em>in</em> <em><strong>ascending</strong></em> <em>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>employees table:</p> <pre class="example-io"> +--------+--------+-----------+ | emp_id | salary | dept | +--------+--------+-----------+ | 1 | 70000 | Sales | | 2 | 80000 | Sales | | 3 | 80000 | Sales | | 4 | 90000 | Sales | | 5 | 55000 | IT | | 6 | 65000 | IT | | 7 | 65000 | IT | | 8 | 50000 | Marketing | | 9 | 55000 | Marketing | | 10 | 55000 | HR | +--------+--------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +--------+-----------+ | emp_id | dept | +--------+-----------+ | 2 | Sales | | 3 | Sales | | 5 | IT | | 8 | Marketing | +--------+-----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Sales Department</strong>: <ul> <li>Highest salary is 90000 (emp_id: 4)</li> <li>Second-highest salary is 80000 (emp_id: 2, 3)</li> <li>Both employees with salary 80000 are included</li> </ul> </li> <li><strong>IT Department</strong>: <ul> <li>Highest salary is 65000 (emp_id: 6, 7)</li> <li>Second-highest salary is 55000 (emp_id: 5)</li> <li>Only emp_id 5 is included as they have the second-highest salary</li> </ul> </li> <li><strong>Marketing Department</strong>: <ul> <li>Highest salary is 55000 (emp_id: 9)</li> <li>Second-highest salary is 50000 (emp_id: 8)</li> <li>Employee 8&nbsp;is included</li> </ul> </li> <li><strong>HR Department</strong>: <ul> <li>Only has one employee</li> <li>Not included in the result as it has fewer than 2 employees</li> </ul> </li> </ul> </div>
Database
Python
import pandas as pd def find_second_highest_salary(employees: pd.DataFrame) -> pd.DataFrame: employees["rk"] = employees.groupby("dept")["salary"].rank( method="dense", ascending=False ) second_highest = employees[employees["rk"] == 2][["emp_id", "dept"]] return second_highest.sort_values(by="emp_id")
3,338
Second Highest Salary II
Medium
<p>Table: <code>employees</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | emp_id | int | | salary | int | | dept | varchar | +------------------+---------+ emp_id is the unique key for this table. Each row of this table contains information about an employee including their ID, salary, and department. </pre> <p>Write a solution to find the employees who earn the <strong>second-highest salary</strong> in each department. If <strong>multiple employees have the second-highest salary</strong>, <strong>include</strong> <strong>all employees</strong> with <strong>that salary</strong>.</p> <p>Return <em>the result table</em> <em>ordered by</em> <code>emp_id</code> <em>in</em> <em><strong>ascending</strong></em> <em>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>employees table:</p> <pre class="example-io"> +--------+--------+-----------+ | emp_id | salary | dept | +--------+--------+-----------+ | 1 | 70000 | Sales | | 2 | 80000 | Sales | | 3 | 80000 | Sales | | 4 | 90000 | Sales | | 5 | 55000 | IT | | 6 | 65000 | IT | | 7 | 65000 | IT | | 8 | 50000 | Marketing | | 9 | 55000 | Marketing | | 10 | 55000 | HR | +--------+--------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +--------+-----------+ | emp_id | dept | +--------+-----------+ | 2 | Sales | | 3 | Sales | | 5 | IT | | 8 | Marketing | +--------+-----------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Sales Department</strong>: <ul> <li>Highest salary is 90000 (emp_id: 4)</li> <li>Second-highest salary is 80000 (emp_id: 2, 3)</li> <li>Both employees with salary 80000 are included</li> </ul> </li> <li><strong>IT Department</strong>: <ul> <li>Highest salary is 65000 (emp_id: 6, 7)</li> <li>Second-highest salary is 55000 (emp_id: 5)</li> <li>Only emp_id 5 is included as they have the second-highest salary</li> </ul> </li> <li><strong>Marketing Department</strong>: <ul> <li>Highest salary is 55000 (emp_id: 9)</li> <li>Second-highest salary is 50000 (emp_id: 8)</li> <li>Employee 8&nbsp;is included</li> </ul> </li> <li><strong>HR Department</strong>: <ul> <li>Only has one employee</li> <li>Not included in the result as it has fewer than 2 employees</li> </ul> </li> </ul> </div>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT emp_id, dept, DENSE_RANK() OVER ( PARTITION BY dept ORDER BY salary DESC ) rk FROM Employees ) SELECT emp_id, dept FROM T WHERE rk = 2 ORDER BY 1;
3,339
Find the Number of K-Even Arrays
Medium
<p>You are given three integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>An array <code>arr</code> is called <strong>k-even</strong> if there are <strong>exactly</strong> <code>k</code> indices such that, for each of these indices <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>):</p> <ul> <li><code>(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]</code> is <em>even</em>.</li> </ul> <p>Return the number of possible <strong>k-even</strong> arrays of size <code>n</code> where all elements are in the range <code>[1, m]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">n = 3, m = 4, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The 8 possible 2-even arrays are:</p> <ul> <li><code>[2, 2, 2]</code></li> <li><code>[2, 2, 4]</code></li> <li><code>[2, 4, 2]</code></li> <li><code>[2, 4, 4]</code></li> <li><code>[4, 2, 2]</code></li> <li><code>[4, 2, 4]</code></li> <li><code>[4, 4, 2]</code></li> <li><code>[4, 4, 4]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 1, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only 0-even array is <code>[1, 1, 1, 1, 1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 7, m = 7, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5832</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 750</code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> <li><code>1 &lt;= m &lt;= 1000</code></li> </ul>
Dynamic Programming
C++
class Solution { public: int countOfArrays(int n, int m, int k) { int f[n][k + 1][2]; memset(f, -1, sizeof(f)); const int mod = 1e9 + 7; int cnt0 = m / 2; int cnt1 = m - cnt0; auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (j < 0) { return 0; } if (i >= n) { return j == 0 ? 1 : 0; } if (f[i][j][k] != -1) { return f[i][j][k]; } int a = 1LL * cnt1 * dfs(i + 1, j, 1) % mod; int b = 1LL * cnt0 * dfs(i + 1, j - (k & 1 ^ 1), 0) % mod; return f[i][j][k] = (a + b) % mod; }; return dfs(0, k, 1); } };
3,339
Find the Number of K-Even Arrays
Medium
<p>You are given three integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>An array <code>arr</code> is called <strong>k-even</strong> if there are <strong>exactly</strong> <code>k</code> indices such that, for each of these indices <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>):</p> <ul> <li><code>(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]</code> is <em>even</em>.</li> </ul> <p>Return the number of possible <strong>k-even</strong> arrays of size <code>n</code> where all elements are in the range <code>[1, m]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">n = 3, m = 4, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The 8 possible 2-even arrays are:</p> <ul> <li><code>[2, 2, 2]</code></li> <li><code>[2, 2, 4]</code></li> <li><code>[2, 4, 2]</code></li> <li><code>[2, 4, 4]</code></li> <li><code>[4, 2, 2]</code></li> <li><code>[4, 2, 4]</code></li> <li><code>[4, 4, 2]</code></li> <li><code>[4, 4, 4]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 1, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only 0-even array is <code>[1, 1, 1, 1, 1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 7, m = 7, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5832</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 750</code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> <li><code>1 &lt;= m &lt;= 1000</code></li> </ul>
Dynamic Programming
Go
func countOfArrays(n int, m int, k int) int { f := make([][][2]int, n) for i := range f { f[i] = make([][2]int, k+1) for j := range f[i] { f[i][j] = [2]int{-1, -1} } } const mod int = 1e9 + 7 cnt0 := m / 2 cnt1 := m - cnt0 var dfs func(int, int, int) int dfs = func(i, j, k int) int { if j < 0 { return 0 } if i >= n { if j == 0 { return 1 } return 0 } if f[i][j][k] != -1 { return f[i][j][k] } a := cnt1 * dfs(i+1, j, 1) % mod b := cnt0 * dfs(i+1, j-(k&1^1), 0) % mod f[i][j][k] = (a + b) % mod return f[i][j][k] } return dfs(0, k, 1) }
3,339
Find the Number of K-Even Arrays
Medium
<p>You are given three integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>An array <code>arr</code> is called <strong>k-even</strong> if there are <strong>exactly</strong> <code>k</code> indices such that, for each of these indices <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>):</p> <ul> <li><code>(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]</code> is <em>even</em>.</li> </ul> <p>Return the number of possible <strong>k-even</strong> arrays of size <code>n</code> where all elements are in the range <code>[1, m]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">n = 3, m = 4, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The 8 possible 2-even arrays are:</p> <ul> <li><code>[2, 2, 2]</code></li> <li><code>[2, 2, 4]</code></li> <li><code>[2, 4, 2]</code></li> <li><code>[2, 4, 4]</code></li> <li><code>[4, 2, 2]</code></li> <li><code>[4, 2, 4]</code></li> <li><code>[4, 4, 2]</code></li> <li><code>[4, 4, 4]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 1, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only 0-even array is <code>[1, 1, 1, 1, 1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 7, m = 7, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5832</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 750</code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> <li><code>1 &lt;= m &lt;= 1000</code></li> </ul>
Dynamic Programming
Java
class Solution { private Integer[][][] f; private long cnt0, cnt1; private final int mod = (int) 1e9 + 7; public int countOfArrays(int n, int m, int k) { f = new Integer[n][k + 1][2]; cnt0 = m / 2; cnt1 = m - cnt0; return dfs(0, k, 1); } private int dfs(int i, int j, int k) { if (j < 0) { return 0; } if (i >= f.length) { return j == 0 ? 1 : 0; } if (f[i][j][k] != null) { return f[i][j][k]; } int a = (int) (cnt1 * dfs(i + 1, j, 1) % mod); int b = (int) (cnt0 * dfs(i + 1, j - (k & 1 ^ 1), 0) % mod); return f[i][j][k] = (a + b) % mod; } }
3,339
Find the Number of K-Even Arrays
Medium
<p>You are given three integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>An array <code>arr</code> is called <strong>k-even</strong> if there are <strong>exactly</strong> <code>k</code> indices such that, for each of these indices <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>):</p> <ul> <li><code>(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]</code> is <em>even</em>.</li> </ul> <p>Return the number of possible <strong>k-even</strong> arrays of size <code>n</code> where all elements are in the range <code>[1, m]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">n = 3, m = 4, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The 8 possible 2-even arrays are:</p> <ul> <li><code>[2, 2, 2]</code></li> <li><code>[2, 2, 4]</code></li> <li><code>[2, 4, 2]</code></li> <li><code>[2, 4, 4]</code></li> <li><code>[4, 2, 2]</code></li> <li><code>[4, 2, 4]</code></li> <li><code>[4, 4, 2]</code></li> <li><code>[4, 4, 4]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 1, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only 0-even array is <code>[1, 1, 1, 1, 1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 7, m = 7, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5832</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 750</code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> <li><code>1 &lt;= m &lt;= 1000</code></li> </ul>
Dynamic Programming
Python
class Solution: def countOfArrays(self, n: int, m: int, k: int) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if j < 0: return 0 if i >= n: return int(j == 0) return ( cnt1 * dfs(i + 1, j, 1) + cnt0 * dfs(i + 1, j - (k & 1 ^ 1), 0) ) % mod cnt0 = m // 2 cnt1 = m - cnt0 mod = 10**9 + 7 ans = dfs(0, k, 1) dfs.cache_clear() return ans
3,339
Find the Number of K-Even Arrays
Medium
<p>You are given three integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>An array <code>arr</code> is called <strong>k-even</strong> if there are <strong>exactly</strong> <code>k</code> indices such that, for each of these indices <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>):</p> <ul> <li><code>(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]</code> is <em>even</em>.</li> </ul> <p>Return the number of possible <strong>k-even</strong> arrays of size <code>n</code> where all elements are in the range <code>[1, m]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">n = 3, m = 4, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>The 8 possible 2-even arrays are:</p> <ul> <li><code>[2, 2, 2]</code></li> <li><code>[2, 2, 4]</code></li> <li><code>[2, 4, 2]</code></li> <li><code>[2, 4, 4]</code></li> <li><code>[4, 2, 2]</code></li> <li><code>[4, 2, 4]</code></li> <li><code>[4, 4, 2]</code></li> <li><code>[4, 4, 4]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 1, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only 0-even array is <code>[1, 1, 1, 1, 1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 7, m = 7, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5832</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 750</code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> <li><code>1 &lt;= m &lt;= 1000</code></li> </ul>
Dynamic Programming
TypeScript
function countOfArrays(n: number, m: number, k: number): number { const f = Array.from({ length: n }, () => Array.from({ length: k + 1 }, () => Array(2).fill(-1)), ); const mod = 1e9 + 7; const cnt0 = Math.floor(m / 2); const cnt1 = m - cnt0; const dfs = (i: number, j: number, k: number): number => { if (j < 0) { return 0; } if (i >= n) { return j === 0 ? 1 : 0; } if (f[i][j][k] !== -1) { return f[i][j][k]; } const a = (cnt1 * dfs(i + 1, j, 1)) % mod; const b = (cnt0 * dfs(i + 1, j - ((k & 1) ^ 1), 0)) % mod; return (f[i][j][k] = (a + b) % mod); }; return dfs(0, k, 1); }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
C++
class Solution { public: bool isBalanced(string num) { int f[2]{}; for (int i = 0; i < num.size(); ++i) { f[i & 1] += num[i] - '0'; } return f[0] == f[1]; } };
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
C#
public class Solution { public bool IsBalanced(string num) { int[] f = new int[2]; for (int i = 0; i < num.Length; ++i) { f[i & 1] += num[i] - '0'; } return f[0] == f[1]; } }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
Go
func isBalanced(num string) bool { f := [2]int{} for i, c := range num { f[i&1] += int(c - '0') } return f[0] == f[1] }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
Java
class Solution { public boolean isBalanced(String num) { int[] f = new int[2]; for (int i = 0; i < num.length(); ++i) { f[i & 1] += num.charAt(i) - '0'; } return f[0] == f[1]; } }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
JavaScript
/** * @param {string} num * @return {boolean} */ var isBalanced = function (num) { const f = [0, 0]; for (let i = 0; i < num.length; ++i) { f[i & 1] += +num[i]; } return f[0] === f[1]; };
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
PHP
class Solution { /** * @param String $num * @return Boolean */ function isBalanced($num) { $f = [0, 0]; foreach (str_split($num) as $i => $ch) { $f[$i & 1] += ord($ch) - 48; } return $f[0] == $f[1]; } }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
Python
class Solution: def isBalanced(self, num: str) -> bool: f = [0, 0] for i, x in enumerate(map(int, num)): f[i & 1] += x return f[0] == f[1]
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
Rust
impl Solution { pub fn is_balanced(num: String) -> bool { let mut f = [0; 2]; for (i, x) in num.as_bytes().iter().enumerate() { f[i & 1] += (x - b'0') as i32; } f[0] == f[1] } }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
Scala
object Solution { def isBalanced(num: String): Boolean = { val f = Array(0, 0) for (i <- num.indices) { f(i & 1) += num(i) - '0' } f(0) == f(1) } }
3,340
Check Balanced String
Easy
<p>You are given a string <code>num</code> consisting of only digits. A string of digits is called <b>balanced </b>if the sum of the digits at even indices is equal to the sum of digits at odd indices.</p> <p>Return <code>true</code> if <code>num</code> is <strong>balanced</strong>, otherwise return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;1234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>1 + 3 == 4</code>, and the sum of digits at odd indices is <code>2 + 4 == 6</code>.</li> <li>Since 4 is not equal to 6, <code>num</code> is not balanced.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> num<span class="example-io"> = &quot;24123&quot;</span></p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong></p> <ul> <li>The sum of digits at even indices is <code>2 + 1 + 3 == 6</code>, and the sum of digits at odd indices is <code>4 + 2 == 6</code>.</li> <li>Since both are equal the <code>num</code> is balanced.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 100</code></li> <li><code><font face="monospace">num</font></code> consists of digits only</li> </ul>
String
TypeScript
function isBalanced(num: string): boolean { const f = [0, 0]; for (let i = 0; i < num.length; ++i) { f[i & 1] += +num[i]; } return f[0] === f[1]; }
3,341
Find Minimum Time to Reach Last Room I
Medium
<p>There is a dungeon with <code>n x m</code> rooms arranged as a grid.</p> <p>You are given a 2D array <code>moveTime</code> of size <code>n x m</code>, where <code>moveTime[i][j]</code> represents the <strong>minimum</strong> time in seconds <strong>after</strong> which the room opens and can be moved to. You start from the room <code>(0, 0)</code> at time <code>t = 0</code> and can move to an <strong>adjacent</strong> room. Moving between adjacent rooms takes <em>exactly</em> one second.</p> <p>Return the <strong>minimum</strong> time to reach the room <code>(n - 1, m - 1)</code>.</p> <p>Two rooms are <strong>adjacent</strong> if they share a common wall, either <em>horizontally</em> or <em>vertically</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">moveTime = [[0,4],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 6 seconds.</p> <ul> <li>At time <code>t == 4</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 5</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,0,0],[0,0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 3 seconds.</p> <ul> <li>At time <code>t == 0</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 1</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> <li>At time <code>t == 2</code>, move from room <code>(1, 1)</code> to room <code>(1, 2)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == moveTime.length &lt;= 50</code></li> <li><code>2 &lt;= m == moveTime[i].length &lt;= 50</code></li> <li><code>0 &lt;= moveTime[i][j] &lt;= 10<sup>9</sup></code></li> </ul>
Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int minTimeToReach(vector<vector<int>>& moveTime) { int n = moveTime.size(); int m = moveTime[0].size(); vector<vector<int>> dist(n, vector<int>(m, INT_MAX)); dist[0][0] = 0; priority_queue<array<int, 3>, vector<array<int, 3>>, greater<>> pq; pq.push({0, 0, 0}); int dirs[5] = {-1, 0, 1, 0, -1}; while (1) { auto [d, i, j] = pq.top(); pq.pop(); if (i == n - 1 && j == m - 1) { return d; } if (d > dist[i][j]) { continue; } for (int k = 0; k < 4; ++k) { int x = i + dirs[k]; int y = j + dirs[k + 1]; if (x >= 0 && x < n && y >= 0 && y < m) { int t = max(moveTime[x][y], dist[i][j]) + 1; if (dist[x][y] > t) { dist[x][y] = t; pq.push({t, x, y}); } } } } } };
3,341
Find Minimum Time to Reach Last Room I
Medium
<p>There is a dungeon with <code>n x m</code> rooms arranged as a grid.</p> <p>You are given a 2D array <code>moveTime</code> of size <code>n x m</code>, where <code>moveTime[i][j]</code> represents the <strong>minimum</strong> time in seconds <strong>after</strong> which the room opens and can be moved to. You start from the room <code>(0, 0)</code> at time <code>t = 0</code> and can move to an <strong>adjacent</strong> room. Moving between adjacent rooms takes <em>exactly</em> one second.</p> <p>Return the <strong>minimum</strong> time to reach the room <code>(n - 1, m - 1)</code>.</p> <p>Two rooms are <strong>adjacent</strong> if they share a common wall, either <em>horizontally</em> or <em>vertically</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">moveTime = [[0,4],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 6 seconds.</p> <ul> <li>At time <code>t == 4</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 5</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,0,0],[0,0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 3 seconds.</p> <ul> <li>At time <code>t == 0</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 1</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> <li>At time <code>t == 2</code>, move from room <code>(1, 1)</code> to room <code>(1, 2)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == moveTime.length &lt;= 50</code></li> <li><code>2 &lt;= m == moveTime[i].length &lt;= 50</code></li> <li><code>0 &lt;= moveTime[i][j] &lt;= 10<sup>9</sup></code></li> </ul>
Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Go
func minTimeToReach(moveTime [][]int) int { n, m := len(moveTime), len(moveTime[0]) dist := make([][]int, n) for i := range dist { dist[i] = make([]int, m) for j := range dist[i] { dist[i][j] = math.MaxInt32 } } dist[0][0] = 0 pq := &hp{} heap.Init(pq) heap.Push(pq, tuple{0, 0, 0}) dirs := []int{-1, 0, 1, 0, -1} for { p := heap.Pop(pq).(tuple) d, i, j := p.dis, p.x, p.y if i == n-1 && j == m-1 { return d } if d > dist[i][j] { continue } for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < n && y >= 0 && y < m { t := max(moveTime[x][y], dist[i][j]) + 1 if dist[x][y] > t { dist[x][y] = t heap.Push(pq, tuple{t, x, y}) } } } } } type tuple struct{ dis, x, y int } type hp []tuple func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].dis < h[j].dis } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
3,341
Find Minimum Time to Reach Last Room I
Medium
<p>There is a dungeon with <code>n x m</code> rooms arranged as a grid.</p> <p>You are given a 2D array <code>moveTime</code> of size <code>n x m</code>, where <code>moveTime[i][j]</code> represents the <strong>minimum</strong> time in seconds <strong>after</strong> which the room opens and can be moved to. You start from the room <code>(0, 0)</code> at time <code>t = 0</code> and can move to an <strong>adjacent</strong> room. Moving between adjacent rooms takes <em>exactly</em> one second.</p> <p>Return the <strong>minimum</strong> time to reach the room <code>(n - 1, m - 1)</code>.</p> <p>Two rooms are <strong>adjacent</strong> if they share a common wall, either <em>horizontally</em> or <em>vertically</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">moveTime = [[0,4],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 6 seconds.</p> <ul> <li>At time <code>t == 4</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 5</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,0,0],[0,0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 3 seconds.</p> <ul> <li>At time <code>t == 0</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 1</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> <li>At time <code>t == 2</code>, move from room <code>(1, 1)</code> to room <code>(1, 2)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == moveTime.length &lt;= 50</code></li> <li><code>2 &lt;= m == moveTime[i].length &lt;= 50</code></li> <li><code>0 &lt;= moveTime[i][j] &lt;= 10<sup>9</sup></code></li> </ul>
Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int minTimeToReach(int[][] moveTime) { int n = moveTime.length; int m = moveTime[0].length; int[][] dist = new int[n][m]; for (var row : dist) { Arrays.fill(row, Integer.MAX_VALUE); } dist[0][0] = 0; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); pq.offer(new int[] {0, 0, 0}); int[] dirs = {-1, 0, 1, 0, -1}; while (true) { int[] p = pq.poll(); int d = p[0], i = p[1], j = p[2]; if (i == n - 1 && j == m - 1) { return d; } if (d > dist[i][j]) { continue; } for (int k = 0; k < 4; k++) { int x = i + dirs[k]; int y = j + dirs[k + 1]; if (x >= 0 && x < n && y >= 0 && y < m) { int t = Math.max(moveTime[x][y], dist[i][j]) + 1; if (dist[x][y] > t) { dist[x][y] = t; pq.offer(new int[] {t, x, y}); } } } } } }
3,341
Find Minimum Time to Reach Last Room I
Medium
<p>There is a dungeon with <code>n x m</code> rooms arranged as a grid.</p> <p>You are given a 2D array <code>moveTime</code> of size <code>n x m</code>, where <code>moveTime[i][j]</code> represents the <strong>minimum</strong> time in seconds <strong>after</strong> which the room opens and can be moved to. You start from the room <code>(0, 0)</code> at time <code>t = 0</code> and can move to an <strong>adjacent</strong> room. Moving between adjacent rooms takes <em>exactly</em> one second.</p> <p>Return the <strong>minimum</strong> time to reach the room <code>(n - 1, m - 1)</code>.</p> <p>Two rooms are <strong>adjacent</strong> if they share a common wall, either <em>horizontally</em> or <em>vertically</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">moveTime = [[0,4],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 6 seconds.</p> <ul> <li>At time <code>t == 4</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 5</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,0,0],[0,0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The minimum time required is 3 seconds.</p> <ul> <li>At time <code>t == 0</code>, move from room <code>(0, 0)</code> to room <code>(1, 0)</code> in one second.</li> <li>At time <code>t == 1</code>, move from room <code>(1, 0)</code> to room <code>(1, 1)</code> in one second.</li> <li>At time <code>t == 2</code>, move from room <code>(1, 1)</code> to room <code>(1, 2)</code> in one second.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">moveTime = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == moveTime.length &lt;= 50</code></li> <li><code>2 &lt;= m == moveTime[i].length &lt;= 50</code></li> <li><code>0 &lt;= moveTime[i][j] &lt;= 10<sup>9</sup></code></li> </ul>
Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Python
class Solution: def minTimeToReach(self, moveTime: List[List[int]]) -> int: n, m = len(moveTime), len(moveTime[0]) dist = [[inf] * m for _ in range(n)] dist[0][0] = 0 pq = [(0, 0, 0)] dirs = (-1, 0, 1, 0, -1) while 1: d, i, j = heappop(pq) if i == n - 1 and j == m - 1: return d if d > dist[i][j]: continue for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < n and 0 <= y < m: t = max(moveTime[x][y], dist[i][j]) + 1 if dist[x][y] > t: dist[x][y] = t heappush(pq, (t, x, y))