id
int64 1
3.63k
| 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,612 |
Process String with Special Operations I
|
Medium
|
<p>You are given a string <code>s</code> consisting of lowercase English letters and the special characters: <code>*</code>, <code>#</code>, and <code>%</code>.</p>
<p>Build a new string <code>result</code> by processing <code>s</code> according to the following rules from left to right:</p>
<ul>
<li>If the letter is a <strong>lowercase</strong> English letter append it to <code>result</code>.</li>
<li>A <code>'*'</code> <strong>removes</strong> the last character from <code>result</code>, if it exists.</li>
<li>A <code>'#'</code> <strong>duplicates</strong> the current <code>result</code> and <strong>appends</strong> it to itself.</li>
<li>A <code>'%'</code> <strong>reverses</strong> the current <code>result</code>.</li>
</ul>
<p>Return the final string <code>result</code> after processing all characters in <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a#b%*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"ba"</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<thead>
<tr>
<th style="border: 1px solid black;"><code>i</code></th>
<th style="border: 1px solid black;"><code>s[i]</code></th>
<th style="border: 1px solid black;">Operation</th>
<th style="border: 1px solid black;">Current <code>result</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">Append <code>'a'</code></td>
<td style="border: 1px solid black;"><code>"a"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;"><code>'#'</code></td>
<td style="border: 1px solid black;">Duplicate <code>result</code></td>
<td style="border: 1px solid black;"><code>"aa"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">Append <code>'b'</code></td>
<td style="border: 1px solid black;"><code>"aab"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;"><code>'%'</code></td>
<td style="border: 1px solid black;">Reverse <code>result</code></td>
<td style="border: 1px solid black;"><code>"baa"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;"><code>'*'</code></td>
<td style="border: 1px solid black;">Remove the last character</td>
<td style="border: 1px solid black;"><code>"ba"</code></td>
</tr>
</tbody>
</table>
<p>Thus, the final <code>result</code> is <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "z*#"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<thead>
<tr>
<th style="border: 1px solid black;"><code>i</code></th>
<th style="border: 1px solid black;"><code>s[i]</code></th>
<th style="border: 1px solid black;">Operation</th>
<th style="border: 1px solid black;">Current <code>result</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">Append <code>'z'</code></td>
<td style="border: 1px solid black;"><code>"z"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;"><code>'*'</code></td>
<td style="border: 1px solid black;">Remove the last character</td>
<td style="border: 1px solid black;"><code>""</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;"><code>'#'</code></td>
<td style="border: 1px solid black;">Duplicate the string</td>
<td style="border: 1px solid black;"><code>""</code></td>
</tr>
</tbody>
</table>
<p>Thus, the final <code>result</code> is <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only lowercase English letters and special characters <code>*</code>, <code>#</code>, and <code>%</code>.</li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def processStr(self, s: str) -> str:
result = []
for c in s:
if c.isalpha():
result.append(c)
elif c == "*" and result:
result.pop()
elif c == "#":
result.extend(result)
elif c == "%":
result.reverse()
return "".join(result)
|
3,612 |
Process String with Special Operations I
|
Medium
|
<p>You are given a string <code>s</code> consisting of lowercase English letters and the special characters: <code>*</code>, <code>#</code>, and <code>%</code>.</p>
<p>Build a new string <code>result</code> by processing <code>s</code> according to the following rules from left to right:</p>
<ul>
<li>If the letter is a <strong>lowercase</strong> English letter append it to <code>result</code>.</li>
<li>A <code>'*'</code> <strong>removes</strong> the last character from <code>result</code>, if it exists.</li>
<li>A <code>'#'</code> <strong>duplicates</strong> the current <code>result</code> and <strong>appends</strong> it to itself.</li>
<li>A <code>'%'</code> <strong>reverses</strong> the current <code>result</code>.</li>
</ul>
<p>Return the final string <code>result</code> after processing all characters in <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a#b%*"</span></p>
<p><strong>Output:</strong> <span class="example-io">"ba"</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<thead>
<tr>
<th style="border: 1px solid black;"><code>i</code></th>
<th style="border: 1px solid black;"><code>s[i]</code></th>
<th style="border: 1px solid black;">Operation</th>
<th style="border: 1px solid black;">Current <code>result</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">Append <code>'a'</code></td>
<td style="border: 1px solid black;"><code>"a"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;"><code>'#'</code></td>
<td style="border: 1px solid black;">Duplicate <code>result</code></td>
<td style="border: 1px solid black;"><code>"aa"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">Append <code>'b'</code></td>
<td style="border: 1px solid black;"><code>"aab"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;"><code>'%'</code></td>
<td style="border: 1px solid black;">Reverse <code>result</code></td>
<td style="border: 1px solid black;"><code>"baa"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;"><code>'*'</code></td>
<td style="border: 1px solid black;">Remove the last character</td>
<td style="border: 1px solid black;"><code>"ba"</code></td>
</tr>
</tbody>
</table>
<p>Thus, the final <code>result</code> is <code>"ba"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "z*#"</span></p>
<p><strong>Output:</strong> <span class="example-io">""</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<thead>
<tr>
<th style="border: 1px solid black;"><code>i</code></th>
<th style="border: 1px solid black;"><code>s[i]</code></th>
<th style="border: 1px solid black;">Operation</th>
<th style="border: 1px solid black;">Current <code>result</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">Append <code>'z'</code></td>
<td style="border: 1px solid black;"><code>"z"</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;"><code>'*'</code></td>
<td style="border: 1px solid black;">Remove the last character</td>
<td style="border: 1px solid black;"><code>""</code></td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;"><code>'#'</code></td>
<td style="border: 1px solid black;">Duplicate the string</td>
<td style="border: 1px solid black;"><code>""</code></td>
</tr>
</tbody>
</table>
<p>Thus, the final <code>result</code> is <code>""</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 20</code></li>
<li><code>s</code> consists of only lowercase English letters and special characters <code>*</code>, <code>#</code>, and <code>%</code>.</li>
</ul>
|
String; Simulation
|
TypeScript
|
function processStr(s: string): string {
const result: string[] = [];
for (const c of s) {
if (/[a-zA-Z]/.test(c)) {
result.push(c);
} else if (c === '*') {
if (result.length > 0) {
result.pop();
}
} else if (c === '#') {
result.push(...result);
} else if (c === '%') {
result.reverse();
}
}
return result.join('');
}
|
3,613 |
Minimize Maximum Component Cost
|
Medium
|
<p data-end="331" data-start="85">You are given an undirected connected graph with <code data-end="137" data-start="134">n</code> nodes labeled from 0 to <code data-end="171" data-start="164">n - 1</code> and a 2D integer array <code data-end="202" data-start="195">edges</code> where <code data-end="234" data-start="209">edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> denotes an undirected edge between node <code data-end="279" data-start="275">u<sub>i</sub></code> and node <code data-end="293" data-start="289">v<sub>i</sub></code> with weight <code data-end="310" data-start="306">w<sub>i</sub></code>, and an integer <code data-end="330" data-start="327">k</code>.</p>
<p data-end="461" data-start="333">You are allowed to remove any number of edges from the graph such that the resulting graph has <strong>at most</strong> <code data-end="439" data-start="436">k</code> connected components.</p>
<p data-end="589" data-start="463">The <strong>cost</strong> of a component is defined as the <strong>maximum</strong> edge weight in that component. If a component has no edges, its cost is 0.</p>
<p data-end="760" data-start="661">Return the <strong>minimum</strong> possible value of the <strong>maximum</strong> cost among all components <strong data-end="759" data-start="736">after such removals</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minimizemaximumm.jpg" style="width: 535px; height: 225px;" /></p>
<ul>
<li data-end="1070" data-start="1021">Remove the edge between nodes 3 and 4 (weight 6).</li>
<li data-end="1141" data-start="1073">The resulting components have costs of 0 and 4, so the overall maximum cost is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minmax2.jpg" style="width: 315px; height: 55px;" /></p>
<ul>
<li data-end="1315" data-start="1251">No edge can be removed, since allowing only one component (<code>k = 1</code>) requires the graph to stay fully connected.</li>
<li data-end="1389" data-start="1318">That single component’s cost equals its largest edge weight, which is 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>1 <= w<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li>The input graph is connected.</li>
</ul>
|
Sort; Union Find; Graph; Binary Search
|
C++
|
class Solution {
public:
int minCost(int n, vector<vector<int>>& edges, int k) {
if (k == n) {
return 0;
}
vector<int> p(n);
ranges::iota(p, 0);
ranges::sort(edges, {}, [](const auto& e) { return e[2]; });
auto find = [&](this auto&& find, int x) -> int {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
int cnt = n;
for (const auto& e : edges) {
int u = e[0], v = e[1], w = e[2];
int pu = find(u), pv = find(v);
if (pu != pv) {
p[pu] = pv;
if (--cnt <= k) {
return w;
}
}
}
return 0;
}
};
|
3,613 |
Minimize Maximum Component Cost
|
Medium
|
<p data-end="331" data-start="85">You are given an undirected connected graph with <code data-end="137" data-start="134">n</code> nodes labeled from 0 to <code data-end="171" data-start="164">n - 1</code> and a 2D integer array <code data-end="202" data-start="195">edges</code> where <code data-end="234" data-start="209">edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> denotes an undirected edge between node <code data-end="279" data-start="275">u<sub>i</sub></code> and node <code data-end="293" data-start="289">v<sub>i</sub></code> with weight <code data-end="310" data-start="306">w<sub>i</sub></code>, and an integer <code data-end="330" data-start="327">k</code>.</p>
<p data-end="461" data-start="333">You are allowed to remove any number of edges from the graph such that the resulting graph has <strong>at most</strong> <code data-end="439" data-start="436">k</code> connected components.</p>
<p data-end="589" data-start="463">The <strong>cost</strong> of a component is defined as the <strong>maximum</strong> edge weight in that component. If a component has no edges, its cost is 0.</p>
<p data-end="760" data-start="661">Return the <strong>minimum</strong> possible value of the <strong>maximum</strong> cost among all components <strong data-end="759" data-start="736">after such removals</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minimizemaximumm.jpg" style="width: 535px; height: 225px;" /></p>
<ul>
<li data-end="1070" data-start="1021">Remove the edge between nodes 3 and 4 (weight 6).</li>
<li data-end="1141" data-start="1073">The resulting components have costs of 0 and 4, so the overall maximum cost is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minmax2.jpg" style="width: 315px; height: 55px;" /></p>
<ul>
<li data-end="1315" data-start="1251">No edge can be removed, since allowing only one component (<code>k = 1</code>) requires the graph to stay fully connected.</li>
<li data-end="1389" data-start="1318">That single component’s cost equals its largest edge weight, which is 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>1 <= w<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li>The input graph is connected.</li>
</ul>
|
Sort; Union Find; Graph; Binary Search
|
Go
|
func minCost(n int, edges [][]int, k int) int {
p := make([]int, n)
for i := range p {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
if k == n {
return 0
}
slices.SortFunc(edges, func(a, b []int) int {
return a[2] - b[2]
})
cnt := n
for _, e := range edges {
u, v, w := e[0], e[1], e[2]
pu, pv := find(u), find(v)
if pu != pv {
p[pu] = pv
if cnt--; cnt <= k {
return w
}
}
}
return 0
}
|
3,613 |
Minimize Maximum Component Cost
|
Medium
|
<p data-end="331" data-start="85">You are given an undirected connected graph with <code data-end="137" data-start="134">n</code> nodes labeled from 0 to <code data-end="171" data-start="164">n - 1</code> and a 2D integer array <code data-end="202" data-start="195">edges</code> where <code data-end="234" data-start="209">edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> denotes an undirected edge between node <code data-end="279" data-start="275">u<sub>i</sub></code> and node <code data-end="293" data-start="289">v<sub>i</sub></code> with weight <code data-end="310" data-start="306">w<sub>i</sub></code>, and an integer <code data-end="330" data-start="327">k</code>.</p>
<p data-end="461" data-start="333">You are allowed to remove any number of edges from the graph such that the resulting graph has <strong>at most</strong> <code data-end="439" data-start="436">k</code> connected components.</p>
<p data-end="589" data-start="463">The <strong>cost</strong> of a component is defined as the <strong>maximum</strong> edge weight in that component. If a component has no edges, its cost is 0.</p>
<p data-end="760" data-start="661">Return the <strong>minimum</strong> possible value of the <strong>maximum</strong> cost among all components <strong data-end="759" data-start="736">after such removals</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minimizemaximumm.jpg" style="width: 535px; height: 225px;" /></p>
<ul>
<li data-end="1070" data-start="1021">Remove the edge between nodes 3 and 4 (weight 6).</li>
<li data-end="1141" data-start="1073">The resulting components have costs of 0 and 4, so the overall maximum cost is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minmax2.jpg" style="width: 315px; height: 55px;" /></p>
<ul>
<li data-end="1315" data-start="1251">No edge can be removed, since allowing only one component (<code>k = 1</code>) requires the graph to stay fully connected.</li>
<li data-end="1389" data-start="1318">That single component’s cost equals its largest edge weight, which is 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>1 <= w<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li>The input graph is connected.</li>
</ul>
|
Sort; Union Find; Graph; Binary Search
|
Java
|
class Solution {
private int[] p;
public int minCost(int n, int[][] edges, int k) {
if (k == n) {
return 0;
}
p = new int[n];
Arrays.setAll(p, i -> i);
Arrays.sort(edges, Comparator.comparingInt(a -> a[2]));
int cnt = n;
for (var e : edges) {
int u = e[0], v = e[1], w = e[2];
int pu = find(u), pv = find(v);
if (pu != pv) {
p[pu] = pv;
if (--cnt <= k) {
return w;
}
}
}
return 0;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
|
3,613 |
Minimize Maximum Component Cost
|
Medium
|
<p data-end="331" data-start="85">You are given an undirected connected graph with <code data-end="137" data-start="134">n</code> nodes labeled from 0 to <code data-end="171" data-start="164">n - 1</code> and a 2D integer array <code data-end="202" data-start="195">edges</code> where <code data-end="234" data-start="209">edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> denotes an undirected edge between node <code data-end="279" data-start="275">u<sub>i</sub></code> and node <code data-end="293" data-start="289">v<sub>i</sub></code> with weight <code data-end="310" data-start="306">w<sub>i</sub></code>, and an integer <code data-end="330" data-start="327">k</code>.</p>
<p data-end="461" data-start="333">You are allowed to remove any number of edges from the graph such that the resulting graph has <strong>at most</strong> <code data-end="439" data-start="436">k</code> connected components.</p>
<p data-end="589" data-start="463">The <strong>cost</strong> of a component is defined as the <strong>maximum</strong> edge weight in that component. If a component has no edges, its cost is 0.</p>
<p data-end="760" data-start="661">Return the <strong>minimum</strong> possible value of the <strong>maximum</strong> cost among all components <strong data-end="759" data-start="736">after such removals</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minimizemaximumm.jpg" style="width: 535px; height: 225px;" /></p>
<ul>
<li data-end="1070" data-start="1021">Remove the edge between nodes 3 and 4 (weight 6).</li>
<li data-end="1141" data-start="1073">The resulting components have costs of 0 and 4, so the overall maximum cost is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minmax2.jpg" style="width: 315px; height: 55px;" /></p>
<ul>
<li data-end="1315" data-start="1251">No edge can be removed, since allowing only one component (<code>k = 1</code>) requires the graph to stay fully connected.</li>
<li data-end="1389" data-start="1318">That single component’s cost equals its largest edge weight, which is 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>1 <= w<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li>The input graph is connected.</li>
</ul>
|
Sort; Union Find; Graph; Binary Search
|
Python
|
class Solution:
def minCost(self, n: int, edges: List[List[int]], k: int) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
if k == n:
return 0
edges.sort(key=lambda x: x[2])
cnt = n
p = list(range(n))
for u, v, w in edges:
pu, pv = find(u), find(v)
if pu != pv:
p[pu] = pv
cnt -= 1
if cnt <= k:
return w
return 0
|
3,613 |
Minimize Maximum Component Cost
|
Medium
|
<p data-end="331" data-start="85">You are given an undirected connected graph with <code data-end="137" data-start="134">n</code> nodes labeled from 0 to <code data-end="171" data-start="164">n - 1</code> and a 2D integer array <code data-end="202" data-start="195">edges</code> where <code data-end="234" data-start="209">edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> denotes an undirected edge between node <code data-end="279" data-start="275">u<sub>i</sub></code> and node <code data-end="293" data-start="289">v<sub>i</sub></code> with weight <code data-end="310" data-start="306">w<sub>i</sub></code>, and an integer <code data-end="330" data-start="327">k</code>.</p>
<p data-end="461" data-start="333">You are allowed to remove any number of edges from the graph such that the resulting graph has <strong>at most</strong> <code data-end="439" data-start="436">k</code> connected components.</p>
<p data-end="589" data-start="463">The <strong>cost</strong> of a component is defined as the <strong>maximum</strong> edge weight in that component. If a component has no edges, its cost is 0.</p>
<p data-end="760" data-start="661">Return the <strong>minimum</strong> possible value of the <strong>maximum</strong> cost among all components <strong data-end="759" data-start="736">after such removals</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minimizemaximumm.jpg" style="width: 535px; height: 225px;" /></p>
<ul>
<li data-end="1070" data-start="1021">Remove the edge between nodes 3 and 4 (weight 6).</li>
<li data-end="1141" data-start="1073">The resulting components have costs of 0 and 4, so the overall maximum cost is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3613.Minimize%20Maximum%20Component%20Cost/images/minmax2.jpg" style="width: 315px; height: 55px;" /></p>
<ul>
<li data-end="1315" data-start="1251">No edge can be removed, since allowing only one component (<code>k = 1</code>) requires the graph to stay fully connected.</li>
<li data-end="1389" data-start="1318">That single component’s cost equals its largest edge weight, which is 5.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
<li><code>1 <= w<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
<li>The input graph is connected.</li>
</ul>
|
Sort; Union Find; Graph; Binary Search
|
TypeScript
|
function minCost(n: number, edges: number[][], k: number): number {
const p: number[] = Array.from({ length: n }, (_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
if (k === n) {
return 0;
}
edges.sort((a, b) => a[2] - b[2]);
let cnt = n;
for (const [u, v, w] of edges) {
const pu = find(u),
pv = find(v);
if (pu !== pv) {
p[pu] = pv;
if (--cnt <= k) {
return w;
}
}
}
return 0;
}
|
3,616 |
Number of Student Replacements
|
Medium
|
<p>You are given an integer array <code>ranks</code> where <code>ranks[i]</code> represents the rank of the <code>i<sup>th</sup></code> student arriving <strong>in order</strong>. A lower number indicates a <strong>better</strong> rank.</p>
<p>Initially, the first student is <strong>selected</strong> by default.</p>
<p>A <strong>replacement</strong> occurs when a student with a <strong>strictly</strong> better rank arrives and <strong>replaces</strong> the current selection.</p>
<p>Return the total number of replacements made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [4,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 4</code> is initially selected.</li>
<li>The second student with <code>ranks[1] = 1</code> is better than the current selection, so a replacement occurs.</li>
<li>The third student has a worse rank, so no replacement occurs.</li>
<li>Thus, the number of replacements is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 2</code> is initially selected.</li>
<li>Neither of <code>ranks[1] = 2</code> or <code>ranks[2] = 3</code> is better than the current selection.</li>
<li>Thus, the number of replacements is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup>βββββββ</code></li>
<li><code>1 <= ranks[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
int totalReplacements(vector<int>& ranks) {
int ans = 0;
int cur = ranks[0];
for (int x : ranks) {
if (x < cur) {
cur = x;
++ans;
}
}
return ans;
}
};
|
3,616 |
Number of Student Replacements
|
Medium
|
<p>You are given an integer array <code>ranks</code> where <code>ranks[i]</code> represents the rank of the <code>i<sup>th</sup></code> student arriving <strong>in order</strong>. A lower number indicates a <strong>better</strong> rank.</p>
<p>Initially, the first student is <strong>selected</strong> by default.</p>
<p>A <strong>replacement</strong> occurs when a student with a <strong>strictly</strong> better rank arrives and <strong>replaces</strong> the current selection.</p>
<p>Return the total number of replacements made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [4,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 4</code> is initially selected.</li>
<li>The second student with <code>ranks[1] = 1</code> is better than the current selection, so a replacement occurs.</li>
<li>The third student has a worse rank, so no replacement occurs.</li>
<li>Thus, the number of replacements is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 2</code> is initially selected.</li>
<li>Neither of <code>ranks[1] = 2</code> or <code>ranks[2] = 3</code> is better than the current selection.</li>
<li>Thus, the number of replacements is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup>βββββββ</code></li>
<li><code>1 <= ranks[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Simulation
|
Go
|
func totalReplacements(ranks []int) (ans int) {
cur := ranks[0]
for _, x := range ranks {
if x < cur {
cur = x
ans++
}
}
return
}
|
3,616 |
Number of Student Replacements
|
Medium
|
<p>You are given an integer array <code>ranks</code> where <code>ranks[i]</code> represents the rank of the <code>i<sup>th</sup></code> student arriving <strong>in order</strong>. A lower number indicates a <strong>better</strong> rank.</p>
<p>Initially, the first student is <strong>selected</strong> by default.</p>
<p>A <strong>replacement</strong> occurs when a student with a <strong>strictly</strong> better rank arrives and <strong>replaces</strong> the current selection.</p>
<p>Return the total number of replacements made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [4,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 4</code> is initially selected.</li>
<li>The second student with <code>ranks[1] = 1</code> is better than the current selection, so a replacement occurs.</li>
<li>The third student has a worse rank, so no replacement occurs.</li>
<li>Thus, the number of replacements is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 2</code> is initially selected.</li>
<li>Neither of <code>ranks[1] = 2</code> or <code>ranks[2] = 3</code> is better than the current selection.</li>
<li>Thus, the number of replacements is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup>βββββββ</code></li>
<li><code>1 <= ranks[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int totalReplacements(int[] ranks) {
int ans = 0;
int cur = ranks[0];
for (int x : ranks) {
if (x < cur) {
cur = x;
++ans;
}
}
return ans;
}
}
|
3,616 |
Number of Student Replacements
|
Medium
|
<p>You are given an integer array <code>ranks</code> where <code>ranks[i]</code> represents the rank of the <code>i<sup>th</sup></code> student arriving <strong>in order</strong>. A lower number indicates a <strong>better</strong> rank.</p>
<p>Initially, the first student is <strong>selected</strong> by default.</p>
<p>A <strong>replacement</strong> occurs when a student with a <strong>strictly</strong> better rank arrives and <strong>replaces</strong> the current selection.</p>
<p>Return the total number of replacements made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [4,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 4</code> is initially selected.</li>
<li>The second student with <code>ranks[1] = 1</code> is better than the current selection, so a replacement occurs.</li>
<li>The third student has a worse rank, so no replacement occurs.</li>
<li>Thus, the number of replacements is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 2</code> is initially selected.</li>
<li>Neither of <code>ranks[1] = 2</code> or <code>ranks[2] = 3</code> is better than the current selection.</li>
<li>Thus, the number of replacements is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup>βββββββ</code></li>
<li><code>1 <= ranks[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def totalReplacements(self, ranks: List[int]) -> int:
ans, cur = 0, ranks[0]
for x in ranks:
if x < cur:
cur = x
ans += 1
return ans
|
3,616 |
Number of Student Replacements
|
Medium
|
<p>You are given an integer array <code>ranks</code> where <code>ranks[i]</code> represents the rank of the <code>i<sup>th</sup></code> student arriving <strong>in order</strong>. A lower number indicates a <strong>better</strong> rank.</p>
<p>Initially, the first student is <strong>selected</strong> by default.</p>
<p>A <strong>replacement</strong> occurs when a student with a <strong>strictly</strong> better rank arrives and <strong>replaces</strong> the current selection.</p>
<p>Return the total number of replacements made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [4,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 4</code> is initially selected.</li>
<li>The second student with <code>ranks[1] = 1</code> is better than the current selection, so a replacement occurs.</li>
<li>The third student has a worse rank, so no replacement occurs.</li>
<li>Thus, the number of replacements is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">ranks = [2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The first student with <code>ranks[0] = 2</code> is initially selected.</li>
<li>Neither of <code>ranks[1] = 2</code> or <code>ranks[2] = 3</code> is better than the current selection.</li>
<li>Thus, the number of replacements is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup>βββββββ</code></li>
<li><code>1 <= ranks[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Simulation
|
TypeScript
|
function totalReplacements(ranks: number[]): number {
let [ans, cur] = [0, ranks[0]];
for (const x of ranks) {
if (x < cur) {
cur = x;
ans++;
}
}
return ans;
}
|
3,617 |
Find Students with Study Spiral Pattern
|
Hard
|
<p>Table: <code>students</code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| major | varchar |
+--------------+---------+
student_id is the unique identifier for this table.
Each row contains information about a student and their academic major.
</pre>
<p>Table: <code>study_sessions</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| session_id | int |
| student_id | int |
| subject | varchar |
| session_date | date |
| hours_studied | decimal |
+---------------+---------+
session_id is the unique identifier for this table.
Each row represents a study session by a student for a specific subject.
</pre>
<p>Write a solution to find students who follow the <strong>Study Spiral Pattern</strong> - students who consistently study multiple subjects in a rotating cycle.</p>
<ul>
<li>A Study Spiral Pattern means a student studies at least <code>3</code><strong> different subjects</strong> in a repeating sequence</li>
<li>The pattern must repeat for <strong>at least </strong><code>2</code><strong> complete cycles</strong> (minimum <code>6</code> study sessions)</li>
<li>Sessions must be <strong>consecutive dates</strong> with no gaps longer than <code>2</code> days between sessions</li>
<li>Calculate the <strong>cycle length</strong> (number of different subjects in the pattern)</li>
<li>Calculate the <strong>total study hours</strong> across all sessions in the pattern</li>
<li>Only include students with cycle length of <strong>at least </strong><code>3</code><strong> subjects</strong></li>
</ul>
<p>Return <em>the result table ordered by cycle length in <strong>descending</strong> order, then by total study hours in <strong>descending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>students table:</p>
<pre class="example-io">
+------------+--------------+------------------+
| student_id | student_name | major |
+------------+--------------+------------------+
| 1 | Alice Chen | Computer Science |
| 2 | Bob Johnson | Mathematics |
| 3 | Carol Davis | Physics |
| 4 | David Wilson | Chemistry |
| 5 | Emma Brown | Biology |
+------------+--------------+------------------+
</pre>
<p>study_sessions table:</p>
<pre class="example-io">
+------------+------------+------------+--------------+---------------+
| session_id | student_id | subject | session_date | hours_studied |
+------------+------------+------------+--------------+---------------+
| 1 | 1 | Math | 2023-10-01 | 2.5 |
| 2 | 1 | Physics | 2023-10-02 | 3.0 |
| 3 | 1 | Chemistry | 2023-10-03 | 2.0 |
| 4 | 1 | Math | 2023-10-04 | 2.5 |
| 5 | 1 | Physics | 2023-10-05 | 3.0 |
| 6 | 1 | Chemistry | 2023-10-06 | 2.0 |
| 7 | 2 | Algebra | 2023-10-01 | 4.0 |
| 8 | 2 | Calculus | 2023-10-02 | 3.5 |
| 9 | 2 | Statistics | 2023-10-03 | 2.5 |
| 10 | 2 | Geometry | 2023-10-04 | 3.0 |
| 11 | 2 | Algebra | 2023-10-05 | 4.0 |
| 12 | 2 | Calculus | 2023-10-06 | 3.5 |
| 13 | 2 | Statistics | 2023-10-07 | 2.5 |
| 14 | 2 | Geometry | 2023-10-08 | 3.0 |
| 15 | 3 | Biology | 2023-10-01 | 2.0 |
| 16 | 3 | Chemistry | 2023-10-02 | 2.5 |
| 17 | 3 | Biology | 2023-10-03 | 2.0 |
| 18 | 3 | Chemistry | 2023-10-04 | 2.5 |
| 19 | 4 | Organic | 2023-10-01 | 3.0 |
| 20 | 4 | Physical | 2023-10-05 | 2.5 |
+------------+------------+------------+--------------+---------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+--------------+------------------+--------------+-------------------+
| student_id | student_name | major | cycle_length | total_study_hours |
+------------+--------------+------------------+--------------+-------------------+
| 2 | Bob Johnson | Mathematics | 4 | 26.0 |
| 1 | Alice Chen | Computer Science | 3 | 15.0 |
+------------+--------------+------------------+--------------+-------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Alice Chen (student_id = 1):</strong>
<ul>
<li>Study sequence: Math → Physics → Chemistry → Math → Physics → Chemistry</li>
<li>Pattern: 3 subjects (Math, Physics, Chemistry) repeating for 2 complete cycles</li>
<li>Consecutive dates: Oct 1-6 with no gaps > 2 days</li>
<li>Cycle length: 3 subjects</li>
<li>Total hours: 2.5 + 3.0 + 2.0 + 2.5 + 3.0 + 2.0 = 15.0 hours</li>
</ul>
</li>
<li><strong>Bob Johnson (student_id = 2):</strong>
<ul>
<li>Study sequence: Algebra → Calculus → Statistics → Geometry → Algebra → Calculus → Statistics → Geometry</li>
<li>Pattern: 4 subjects (Algebra, Calculus, Statistics, Geometry) repeating for 2 complete cycles</li>
<li>Consecutive dates: Oct 1-8 with no gaps > 2 days</li>
<li>Cycle length: 4 subjects</li>
<li>Total hours: 4.0 + 3.5 + 2.5 + 3.0 + 4.0 + 3.5 + 2.5 + 3.0 = 26.0 hours</li>
</ul>
</li>
<li><strong>Students not included:</strong>
<ul>
<li>Carol Davis (student_id = 3): Only 2 subjects (Biology, Chemistry) - doesn't meet minimum 3 subjects requirement</li>
<li>David Wilson (student_id = 4): Only 2 study sessions with a 4-day gap - doesn't meet consecutive dates requirement</li>
<li>Emma Brown (student_id = 5): No study sessions recorded</li>
</ul>
</li>
</ul>
<p>The result table is ordered by cycle_length in descending order, then by total_study_hours in descending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
from datetime import timedelta
def find_study_spiral_pattern(
students: pd.DataFrame, study_sessions: pd.DataFrame
) -> pd.DataFrame:
# Convert session_date to datetime
study_sessions["session_date"] = pd.to_datetime(study_sessions["session_date"])
result = []
# Group study sessions by student
for student_id, group in study_sessions.groupby("student_id"):
# Sort sessions by date
group = group.sort_values("session_date").reset_index(drop=True)
temp = [] # Holds current contiguous segment
last_date = None
for idx, row in group.iterrows():
if not temp:
temp.append(row)
else:
delta = (row["session_date"] - last_date).days
if delta <= 2:
temp.append(row)
else:
# Check the previous contiguous segment
if len(temp) >= 6:
_check_pattern(student_id, temp, result)
temp = [row]
last_date = row["session_date"]
# Check the final segment
if len(temp) >= 6:
_check_pattern(student_id, temp, result)
# Build result DataFrame
df_result = pd.DataFrame(
result, columns=["student_id", "cycle_length", "total_study_hours"]
)
if df_result.empty:
return pd.DataFrame(
columns=[
"student_id",
"student_name",
"major",
"cycle_length",
"total_study_hours",
]
)
# Join with students table to get name and major
df_result = df_result.merge(students, on="student_id")
df_result = df_result[
["student_id", "student_name", "major", "cycle_length", "total_study_hours"]
]
return df_result.sort_values(
by=["cycle_length", "total_study_hours"], ascending=[False, False]
).reset_index(drop=True)
def _check_pattern(student_id, sessions, result):
subjects = [row["subject"] for row in sessions]
hours = sum(row["hours_studied"] for row in sessions)
n = len(subjects)
# Try possible cycle lengths from 3 up to half of the sequence
for cycle_len in range(3, n // 2 + 1):
if n % cycle_len != 0:
continue
# Extract the first cycle
first_cycle = subjects[:cycle_len]
is_pattern = True
# Compare each following cycle with the first
for i in range(1, n // cycle_len):
if subjects[i * cycle_len : (i + 1) * cycle_len] != first_cycle:
is_pattern = False
break
# If a repeated cycle is detected, store the result
if is_pattern:
result.append(
{
"student_id": student_id,
"cycle_length": cycle_len,
"total_study_hours": hours,
}
)
break # Stop at the first valid cycle found
|
3,617 |
Find Students with Study Spiral Pattern
|
Hard
|
<p>Table: <code>students</code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| major | varchar |
+--------------+---------+
student_id is the unique identifier for this table.
Each row contains information about a student and their academic major.
</pre>
<p>Table: <code>study_sessions</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| session_id | int |
| student_id | int |
| subject | varchar |
| session_date | date |
| hours_studied | decimal |
+---------------+---------+
session_id is the unique identifier for this table.
Each row represents a study session by a student for a specific subject.
</pre>
<p>Write a solution to find students who follow the <strong>Study Spiral Pattern</strong> - students who consistently study multiple subjects in a rotating cycle.</p>
<ul>
<li>A Study Spiral Pattern means a student studies at least <code>3</code><strong> different subjects</strong> in a repeating sequence</li>
<li>The pattern must repeat for <strong>at least </strong><code>2</code><strong> complete cycles</strong> (minimum <code>6</code> study sessions)</li>
<li>Sessions must be <strong>consecutive dates</strong> with no gaps longer than <code>2</code> days between sessions</li>
<li>Calculate the <strong>cycle length</strong> (number of different subjects in the pattern)</li>
<li>Calculate the <strong>total study hours</strong> across all sessions in the pattern</li>
<li>Only include students with cycle length of <strong>at least </strong><code>3</code><strong> subjects</strong></li>
</ul>
<p>Return <em>the result table ordered by cycle length in <strong>descending</strong> order, then by total study hours in <strong>descending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>students table:</p>
<pre class="example-io">
+------------+--------------+------------------+
| student_id | student_name | major |
+------------+--------------+------------------+
| 1 | Alice Chen | Computer Science |
| 2 | Bob Johnson | Mathematics |
| 3 | Carol Davis | Physics |
| 4 | David Wilson | Chemistry |
| 5 | Emma Brown | Biology |
+------------+--------------+------------------+
</pre>
<p>study_sessions table:</p>
<pre class="example-io">
+------------+------------+------------+--------------+---------------+
| session_id | student_id | subject | session_date | hours_studied |
+------------+------------+------------+--------------+---------------+
| 1 | 1 | Math | 2023-10-01 | 2.5 |
| 2 | 1 | Physics | 2023-10-02 | 3.0 |
| 3 | 1 | Chemistry | 2023-10-03 | 2.0 |
| 4 | 1 | Math | 2023-10-04 | 2.5 |
| 5 | 1 | Physics | 2023-10-05 | 3.0 |
| 6 | 1 | Chemistry | 2023-10-06 | 2.0 |
| 7 | 2 | Algebra | 2023-10-01 | 4.0 |
| 8 | 2 | Calculus | 2023-10-02 | 3.5 |
| 9 | 2 | Statistics | 2023-10-03 | 2.5 |
| 10 | 2 | Geometry | 2023-10-04 | 3.0 |
| 11 | 2 | Algebra | 2023-10-05 | 4.0 |
| 12 | 2 | Calculus | 2023-10-06 | 3.5 |
| 13 | 2 | Statistics | 2023-10-07 | 2.5 |
| 14 | 2 | Geometry | 2023-10-08 | 3.0 |
| 15 | 3 | Biology | 2023-10-01 | 2.0 |
| 16 | 3 | Chemistry | 2023-10-02 | 2.5 |
| 17 | 3 | Biology | 2023-10-03 | 2.0 |
| 18 | 3 | Chemistry | 2023-10-04 | 2.5 |
| 19 | 4 | Organic | 2023-10-01 | 3.0 |
| 20 | 4 | Physical | 2023-10-05 | 2.5 |
+------------+------------+------------+--------------+---------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+--------------+------------------+--------------+-------------------+
| student_id | student_name | major | cycle_length | total_study_hours |
+------------+--------------+------------------+--------------+-------------------+
| 2 | Bob Johnson | Mathematics | 4 | 26.0 |
| 1 | Alice Chen | Computer Science | 3 | 15.0 |
+------------+--------------+------------------+--------------+-------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Alice Chen (student_id = 1):</strong>
<ul>
<li>Study sequence: Math → Physics → Chemistry → Math → Physics → Chemistry</li>
<li>Pattern: 3 subjects (Math, Physics, Chemistry) repeating for 2 complete cycles</li>
<li>Consecutive dates: Oct 1-6 with no gaps > 2 days</li>
<li>Cycle length: 3 subjects</li>
<li>Total hours: 2.5 + 3.0 + 2.0 + 2.5 + 3.0 + 2.0 = 15.0 hours</li>
</ul>
</li>
<li><strong>Bob Johnson (student_id = 2):</strong>
<ul>
<li>Study sequence: Algebra → Calculus → Statistics → Geometry → Algebra → Calculus → Statistics → Geometry</li>
<li>Pattern: 4 subjects (Algebra, Calculus, Statistics, Geometry) repeating for 2 complete cycles</li>
<li>Consecutive dates: Oct 1-8 with no gaps > 2 days</li>
<li>Cycle length: 4 subjects</li>
<li>Total hours: 4.0 + 3.5 + 2.5 + 3.0 + 4.0 + 3.5 + 2.5 + 3.0 = 26.0 hours</li>
</ul>
</li>
<li><strong>Students not included:</strong>
<ul>
<li>Carol Davis (student_id = 3): Only 2 subjects (Biology, Chemistry) - doesn't meet minimum 3 subjects requirement</li>
<li>David Wilson (student_id = 4): Only 2 study sessions with a 4-day gap - doesn't meet consecutive dates requirement</li>
<li>Emma Brown (student_id = 5): No study sessions recorded</li>
</ul>
</li>
</ul>
<p>The result table is ordered by cycle_length in descending order, then by total_study_hours in descending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
ranked_sessions AS (
SELECT
s.student_id,
ss.session_date,
ss.subject,
ss.hours_studied,
ROW_NUMBER() OVER (
PARTITION BY s.student_id
ORDER BY ss.session_date
) AS rn
FROM
study_sessions ss
JOIN students s ON s.student_id = ss.student_id
),
grouped_sessions AS (
SELECT
*,
DATEDIFF(
session_date,
LAG(session_date) OVER (
PARTITION BY student_id
ORDER BY session_date
)
) AS date_diff
FROM ranked_sessions
),
session_groups AS (
SELECT
*,
SUM(
CASE
WHEN date_diff > 2
OR date_diff IS NULL THEN 1
ELSE 0
END
) OVER (
PARTITION BY student_id
ORDER BY session_date
) AS group_id
FROM grouped_sessions
),
valid_sequences AS (
SELECT
student_id,
group_id,
COUNT(*) AS session_count,
GROUP_CONCAT(subject ORDER BY session_date) AS subject_sequence,
SUM(hours_studied) AS total_hours
FROM session_groups
GROUP BY student_id, group_id
HAVING session_count >= 6
),
pattern_detected AS (
SELECT
vs.student_id,
vs.total_hours,
vs.subject_sequence,
COUNT(
DISTINCT
SUBSTRING_INDEX(SUBSTRING_INDEX(subject_sequence, ',', n), ',', -1)
) AS cycle_length
FROM
valid_sequences vs
JOIN (
SELECT a.N + b.N * 10 + 1 AS n
FROM
(
SELECT 0 AS N
UNION
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
UNION
SELECT 6
UNION
SELECT 7
UNION
SELECT 8
UNION
SELECT 9
) a,
(
SELECT 0 AS N
UNION
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
UNION
SELECT 6
UNION
SELECT 7
UNION
SELECT 8
UNION
SELECT 9
) b
) nums
ON n <= 10
WHERE
-- Check if the sequence repeats every `k` items, for some `k >= 3` and divides session_count exactly
-- We simplify by checking the start and middle halves are equal
LENGTH(subject_sequence) > 0
AND LOCATE(',', subject_sequence) > 0
AND (
-- For cycle length 3:
subject_sequence LIKE CONCAT(
SUBSTRING_INDEX(subject_sequence, ',', 3),
',',
SUBSTRING_INDEX(SUBSTRING_INDEX(subject_sequence, ',', 6), ',', -3),
'%'
)
OR subject_sequence LIKE CONCAT(
-- For cycle length 4:
SUBSTRING_INDEX(subject_sequence, ',', 4),
',',
SUBSTRING_INDEX(SUBSTRING_INDEX(subject_sequence, ',', 8), ',', -4),
'%'
)
)
GROUP BY vs.student_id, vs.total_hours, vs.subject_sequence
),
final_output AS (
SELECT
s.student_id,
s.student_name,
s.major,
pd.cycle_length,
pd.total_hours AS total_study_hours
FROM
pattern_detected pd
JOIN students s ON s.student_id = pd.student_id
WHERE pd.cycle_length >= 3
)
SELECT *
FROM final_output
ORDER BY cycle_length DESC, total_study_hours DESC;
|
3,618 |
Split Array by Prime Indices
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Split <code>nums</code> into two arrays <code>A</code> and <code>B</code> using the following rule:</p>
<ul>
<li>Elements at <strong><span data-keyword="prime-number">prime</span></strong> indices in <code>nums</code> must go into array <code>A</code>.</li>
<li>All other elements must go into array <code>B</code>.</li>
</ul>
<p>Return the <strong>absolute</strong> difference between the sums of the two arrays: <code>|sum(A) - sum(B)|</code>.</p>
<p><strong>Note:</strong> An empty array has a sum of 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The only prime index in the array is 2, so <code>nums[2] = 4</code> is placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = 2</code> and <code>nums[1] = 3</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 4</code>, <code>sum(B) = 2 + 3 = 5</code>.</li>
<li>The absolute difference is <code>|4 - 5| = 1</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 = [-1,5,7,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The prime indices in the array are 2 and 3, so <code>nums[2] = 7</code> and <code>nums[3] = 0</code> are placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = -1</code> and <code>nums[1] = 5</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 7 + 0 = 7</code>, <code>sum(B) = -1 + 5 = 4</code>.</li>
<li>The absolute difference is <code>|7 - 4| = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Number Theory
|
C++
|
const int M = 1e5 + 10;
bool primes[M];
auto init = [] {
memset(primes, true, sizeof(primes));
primes[0] = primes[1] = false;
for (int i = 2; i < M; ++i) {
if (primes[i]) {
for (int j = i + i; j < M; j += i) {
primes[j] = false;
}
}
}
return 0;
}();
class Solution {
public:
long long splitArray(vector<int>& nums) {
long long ans = 0;
for (int i = 0; i < nums.size(); ++i) {
ans += primes[i] ? nums[i] : -nums[i];
}
return abs(ans);
}
};
|
3,618 |
Split Array by Prime Indices
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Split <code>nums</code> into two arrays <code>A</code> and <code>B</code> using the following rule:</p>
<ul>
<li>Elements at <strong><span data-keyword="prime-number">prime</span></strong> indices in <code>nums</code> must go into array <code>A</code>.</li>
<li>All other elements must go into array <code>B</code>.</li>
</ul>
<p>Return the <strong>absolute</strong> difference between the sums of the two arrays: <code>|sum(A) - sum(B)|</code>.</p>
<p><strong>Note:</strong> An empty array has a sum of 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The only prime index in the array is 2, so <code>nums[2] = 4</code> is placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = 2</code> and <code>nums[1] = 3</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 4</code>, <code>sum(B) = 2 + 3 = 5</code>.</li>
<li>The absolute difference is <code>|4 - 5| = 1</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 = [-1,5,7,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The prime indices in the array are 2 and 3, so <code>nums[2] = 7</code> and <code>nums[3] = 0</code> are placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = -1</code> and <code>nums[1] = 5</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 7 + 0 = 7</code>, <code>sum(B) = -1 + 5 = 4</code>.</li>
<li>The absolute difference is <code>|7 - 4| = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Number Theory
|
Go
|
const M = 100000 + 10
var primes [M]bool
func init() {
for i := 0; i < M; i++ {
primes[i] = true
}
primes[0], primes[1] = false, false
for i := 2; i < M; i++ {
if primes[i] {
for j := i + i; j < M; j += i {
primes[j] = false
}
}
}
}
func splitArray(nums []int) (ans int64) {
for i, num := range nums {
if primes[i] {
ans += int64(num)
} else {
ans -= int64(num)
}
}
return max(ans, -ans)
}
|
3,618 |
Split Array by Prime Indices
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Split <code>nums</code> into two arrays <code>A</code> and <code>B</code> using the following rule:</p>
<ul>
<li>Elements at <strong><span data-keyword="prime-number">prime</span></strong> indices in <code>nums</code> must go into array <code>A</code>.</li>
<li>All other elements must go into array <code>B</code>.</li>
</ul>
<p>Return the <strong>absolute</strong> difference between the sums of the two arrays: <code>|sum(A) - sum(B)|</code>.</p>
<p><strong>Note:</strong> An empty array has a sum of 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The only prime index in the array is 2, so <code>nums[2] = 4</code> is placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = 2</code> and <code>nums[1] = 3</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 4</code>, <code>sum(B) = 2 + 3 = 5</code>.</li>
<li>The absolute difference is <code>|4 - 5| = 1</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 = [-1,5,7,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The prime indices in the array are 2 and 3, so <code>nums[2] = 7</code> and <code>nums[3] = 0</code> are placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = -1</code> and <code>nums[1] = 5</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 7 + 0 = 7</code>, <code>sum(B) = -1 + 5 = 4</code>.</li>
<li>The absolute difference is <code>|7 - 4| = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Number Theory
|
Java
|
class Solution {
private static final int M = 100000 + 10;
private static boolean[] primes = new boolean[M];
static {
for (int i = 0; i < M; i++) {
primes[i] = true;
}
primes[0] = primes[1] = false;
for (int i = 2; i < M; i++) {
if (primes[i]) {
for (int j = i + i; j < M; j += i) {
primes[j] = false;
}
}
}
}
public long splitArray(int[] nums) {
long ans = 0;
for (int i = 0; i < nums.length; ++i) {
ans += primes[i] ? nums[i] : -nums[i];
}
return Math.abs(ans);
}
}
|
3,618 |
Split Array by Prime Indices
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Split <code>nums</code> into two arrays <code>A</code> and <code>B</code> using the following rule:</p>
<ul>
<li>Elements at <strong><span data-keyword="prime-number">prime</span></strong> indices in <code>nums</code> must go into array <code>A</code>.</li>
<li>All other elements must go into array <code>B</code>.</li>
</ul>
<p>Return the <strong>absolute</strong> difference between the sums of the two arrays: <code>|sum(A) - sum(B)|</code>.</p>
<p><strong>Note:</strong> An empty array has a sum of 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The only prime index in the array is 2, so <code>nums[2] = 4</code> is placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = 2</code> and <code>nums[1] = 3</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 4</code>, <code>sum(B) = 2 + 3 = 5</code>.</li>
<li>The absolute difference is <code>|4 - 5| = 1</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 = [-1,5,7,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The prime indices in the array are 2 and 3, so <code>nums[2] = 7</code> and <code>nums[3] = 0</code> are placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = -1</code> and <code>nums[1] = 5</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 7 + 0 = 7</code>, <code>sum(B) = -1 + 5 = 4</code>.</li>
<li>The absolute difference is <code>|7 - 4| = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Number Theory
|
Python
|
m = 10**5 + 10
primes = [True] * m
primes[0] = primes[1] = False
for i in range(2, m):
if primes[i]:
for j in range(i + i, m, i):
primes[j] = False
class Solution:
def splitArray(self, nums: List[int]) -> int:
return abs(sum(x if primes[i] else -x for i, x in enumerate(nums)))
|
3,618 |
Split Array by Prime Indices
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Split <code>nums</code> into two arrays <code>A</code> and <code>B</code> using the following rule:</p>
<ul>
<li>Elements at <strong><span data-keyword="prime-number">prime</span></strong> indices in <code>nums</code> must go into array <code>A</code>.</li>
<li>All other elements must go into array <code>B</code>.</li>
</ul>
<p>Return the <strong>absolute</strong> difference between the sums of the two arrays: <code>|sum(A) - sum(B)|</code>.</p>
<p><strong>Note:</strong> An empty array has a sum of 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The only prime index in the array is 2, so <code>nums[2] = 4</code> is placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = 2</code> and <code>nums[1] = 3</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 4</code>, <code>sum(B) = 2 + 3 = 5</code>.</li>
<li>The absolute difference is <code>|4 - 5| = 1</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 = [-1,5,7,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The prime indices in the array are 2 and 3, so <code>nums[2] = 7</code> and <code>nums[3] = 0</code> are placed in array <code>A</code>.</li>
<li>The remaining elements, <code>nums[0] = -1</code> and <code>nums[1] = 5</code> are placed in array <code>B</code>.</li>
<li><code>sum(A) = 7 + 0 = 7</code>, <code>sum(B) = -1 + 5 = 4</code>.</li>
<li>The absolute difference is <code>|7 - 4| = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Number Theory
|
TypeScript
|
const M = 100000 + 10;
const primes: boolean[] = Array(M).fill(true);
const init = (() => {
primes[0] = primes[1] = false;
for (let i = 2; i < M; i++) {
if (primes[i]) {
for (let j = i + i; j < M; j += i) {
primes[j] = false;
}
}
}
})();
function splitArray(nums: number[]): number {
let ans = 0;
for (let i = 0; i < nums.length; i++) {
ans += primes[i] ? nums[i] : -nums[i];
}
return Math.abs(ans);
}
|
3,619 |
Count Islands With Total Value Divisible by K
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> and a positive integer <code>k</code>. An <strong>island</strong> is a group of <strong>positive</strong> integers (representing land) that are <strong>4-directionally</strong> connected (horizontally or vertically).</p>
<p>The <strong>total value</strong> of an island is the sum of the values of all cells in the island.</p>
<p>Return the number of islands with a total value <strong>divisible by</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example1griddrawio-1.png" style="width: 200px; height: 200px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example2griddrawio.png" style="width: 200px; height: 150px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains six islands, each with a total value that is divisible by 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 1000</code></li>
<li><code>1 <= m * n <= 10<sup>5</sup></code></li>
<li><code>0 <= grid[i][j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
C++
|
class Solution {
public:
int countIslands(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
vector<int> dirs = {-1, 0, 1, 0, -1};
auto dfs = [&](this auto&& dfs, int i, int j) -> long long {
long long s = grid[i][j];
grid[i][j] = 0;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) {
s += dfs(x, y);
}
}
return s;
};
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] && dfs(i, j) % k == 0) {
++ans;
}
}
}
return ans;
}
};
|
3,619 |
Count Islands With Total Value Divisible by K
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> and a positive integer <code>k</code>. An <strong>island</strong> is a group of <strong>positive</strong> integers (representing land) that are <strong>4-directionally</strong> connected (horizontally or vertically).</p>
<p>The <strong>total value</strong> of an island is the sum of the values of all cells in the island.</p>
<p>Return the number of islands with a total value <strong>divisible by</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example1griddrawio-1.png" style="width: 200px; height: 200px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example2griddrawio.png" style="width: 200px; height: 150px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains six islands, each with a total value that is divisible by 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 1000</code></li>
<li><code>1 <= m * n <= 10<sup>5</sup></code></li>
<li><code>0 <= grid[i][j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Go
|
func countIslands(grid [][]int, k int) (ans int) {
m, n := len(grid), len(grid[0])
dirs := []int{-1, 0, 1, 0, -1}
var dfs func(i, j int) int
dfs = func(i, j int) int {
s := grid[i][j]
grid[i][j] = 0
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0 {
s += dfs(x, y)
}
}
return s
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] > 0 && dfs(i, j)%k == 0 {
ans++
}
}
}
return
}
|
3,619 |
Count Islands With Total Value Divisible by K
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> and a positive integer <code>k</code>. An <strong>island</strong> is a group of <strong>positive</strong> integers (representing land) that are <strong>4-directionally</strong> connected (horizontally or vertically).</p>
<p>The <strong>total value</strong> of an island is the sum of the values of all cells in the island.</p>
<p>Return the number of islands with a total value <strong>divisible by</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example1griddrawio-1.png" style="width: 200px; height: 200px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example2griddrawio.png" style="width: 200px; height: 150px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains six islands, each with a total value that is divisible by 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 1000</code></li>
<li><code>1 <= m * n <= 10<sup>5</sup></code></li>
<li><code>0 <= grid[i][j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Java
|
class Solution {
private int m;
private int n;
private int[][] grid;
private final int[] dirs = {-1, 0, 1, 0, -1};
public int countIslands(int[][] grid, int k) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] > 0 && dfs(i, j) % k == 0) {
++ans;
}
}
}
return ans;
}
private long dfs(int i, int j) {
long s = grid[i][j];
grid[i][j] = 0;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) {
s += dfs(x, y);
}
}
return s;
}
}
|
3,619 |
Count Islands With Total Value Divisible by K
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> and a positive integer <code>k</code>. An <strong>island</strong> is a group of <strong>positive</strong> integers (representing land) that are <strong>4-directionally</strong> connected (horizontally or vertically).</p>
<p>The <strong>total value</strong> of an island is the sum of the values of all cells in the island.</p>
<p>Return the number of islands with a total value <strong>divisible by</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example1griddrawio-1.png" style="width: 200px; height: 200px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example2griddrawio.png" style="width: 200px; height: 150px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains six islands, each with a total value that is divisible by 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 1000</code></li>
<li><code>1 <= m * n <= 10<sup>5</sup></code></li>
<li><code>0 <= grid[i][j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
Python
|
class Solution:
def countIslands(self, grid: List[List[int]], k: int) -> int:
def dfs(i: int, j: int) -> int:
s = grid[i][j]
grid[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y]:
s += dfs(x, y)
return s
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] and dfs(i, j) % k == 0:
ans += 1
return ans
|
3,619 |
Count Islands With Total Value Divisible by K
|
Medium
|
<p>You are given an <code>m x n</code> matrix <code>grid</code> and a positive integer <code>k</code>. An <strong>island</strong> is a group of <strong>positive</strong> integers (representing land) that are <strong>4-directionally</strong> connected (horizontally or vertically).</p>
<p>The <strong>total value</strong> of an island is the sum of the values of all cells in the island.</p>
<p>Return the number of islands with a total value <strong>divisible by</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example1griddrawio-1.png" style="width: 200px; height: 200px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3619.Count%20Islands%20With%20Total%20Value%20Divisible%20by%20K/images/example2griddrawio.png" style="width: 200px; height: 150px;" />
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The grid contains six islands, each with a total value that is divisible by 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 1000</code></li>
<li><code>1 <= m * n <= 10<sup>5</sup></code></li>
<li><code>0 <= grid[i][j] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= 10<sup>6</sup></code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
|
TypeScript
|
function countIslands(grid: number[][], k: number): number {
const m = grid.length,
n = grid[0].length;
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): number => {
let s = grid[i][j];
grid[i][j] = 0;
for (let d = 0; d < 4; d++) {
const x = i + dirs[d],
y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) {
s += dfs(x, y);
}
}
return s;
};
let ans = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] > 0 && dfs(i, j) % k === 0) {
ans++;
}
}
}
return ans;
}
|
3,622 |
Check Divisibility by Digit Sum and Product
|
Easy
|
<p>You are given a positive integer <code>n</code>. Determine whether <code>n</code> is divisible by the <strong>sum </strong>of the following two values:</p>
<ul>
<li>
<p>The <strong>digit sum</strong> of <code>n</code> (the sum of its digits).</p>
</li>
<li>
<p>The <strong>digit</strong> <strong>product</strong> of <code>n</code> (the product of its digits).</p>
</li>
</ul>
<p>Return <code>true</code> if <code>n</code> is divisible by this sum; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 99</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
bool checkDivisibility(int n) {
int s = 0, p = 1;
int x = n;
while (x != 0) {
int v = x % 10;
x /= 10;
s += v;
p *= v;
}
return n % (s + p) == 0;
}
};
|
3,622 |
Check Divisibility by Digit Sum and Product
|
Easy
|
<p>You are given a positive integer <code>n</code>. Determine whether <code>n</code> is divisible by the <strong>sum </strong>of the following two values:</p>
<ul>
<li>
<p>The <strong>digit sum</strong> of <code>n</code> (the sum of its digits).</p>
</li>
<li>
<p>The <strong>digit</strong> <strong>product</strong> of <code>n</code> (the product of its digits).</p>
</li>
</ul>
<p>Return <code>true</code> if <code>n</code> is divisible by this sum; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 99</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
</ul>
|
Math
|
Go
|
func checkDivisibility(n int) bool {
s, p := 0, 1
x := n
for x != 0 {
v := x % 10
x /= 10
s += v
p *= v
}
return n%(s+p) == 0
}
|
3,622 |
Check Divisibility by Digit Sum and Product
|
Easy
|
<p>You are given a positive integer <code>n</code>. Determine whether <code>n</code> is divisible by the <strong>sum </strong>of the following two values:</p>
<ul>
<li>
<p>The <strong>digit sum</strong> of <code>n</code> (the sum of its digits).</p>
</li>
<li>
<p>The <strong>digit</strong> <strong>product</strong> of <code>n</code> (the product of its digits).</p>
</li>
</ul>
<p>Return <code>true</code> if <code>n</code> is divisible by this sum; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 99</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
</ul>
|
Math
|
Java
|
class Solution {
public boolean checkDivisibility(int n) {
int s = 0, p = 1;
int x = n;
while (x != 0) {
int v = x % 10;
x /= 10;
s += v;
p *= v;
}
return n % (s + p) == 0;
}
}
|
3,622 |
Check Divisibility by Digit Sum and Product
|
Easy
|
<p>You are given a positive integer <code>n</code>. Determine whether <code>n</code> is divisible by the <strong>sum </strong>of the following two values:</p>
<ul>
<li>
<p>The <strong>digit sum</strong> of <code>n</code> (the sum of its digits).</p>
</li>
<li>
<p>The <strong>digit</strong> <strong>product</strong> of <code>n</code> (the product of its digits).</p>
</li>
</ul>
<p>Return <code>true</code> if <code>n</code> is divisible by this sum; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 99</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
</ul>
|
Math
|
Python
|
class Solution:
def checkDivisibility(self, n: int) -> bool:
s, p = 0, 1
x = n
while x:
x, v = divmod(x, 10)
s += v
p *= v
return n % (s + p) == 0
|
3,622 |
Check Divisibility by Digit Sum and Product
|
Easy
|
<p>You are given a positive integer <code>n</code>. Determine whether <code>n</code> is divisible by the <strong>sum </strong>of the following two values:</p>
<ul>
<li>
<p>The <strong>digit sum</strong> of <code>n</code> (the sum of its digits).</p>
</li>
<li>
<p>The <strong>digit</strong> <strong>product</strong> of <code>n</code> (the product of its digits).</p>
</li>
</ul>
<p>Return <code>true</code> if <code>n</code> is divisible by this sum; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 99</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 99 is divisible by the sum (9 + 9 = 18) plus product (9 * 9 = 81) of its digits (total 99), the output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Since 23 is not divisible by the sum (2 + 3 = 5) plus product (2 * 3 = 6) of its digits (total 11), the output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
</ul>
|
Math
|
TypeScript
|
function checkDivisibility(n: number): boolean {
let [s, p] = [0, 1];
let x = n;
while (x !== 0) {
const v = x % 10;
x = Math.floor(x / 10);
s += v;
p *= v;
}
return n % (s + p) === 0;
}
|
3,626 |
Find Stores with Inventory Imbalance
|
Medium
|
<p>Table: <code>stores</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| store_id | int |
| store_name | varchar |
| location | varchar |
+-------------+---------+
store_id is the unique identifier for this table.
Each row contains information about a store and its location.
</pre>
<p>Table: <code>inventory</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| inventory_id| int |
| store_id | int |
| product_name| varchar |
| quantity | int |
| price | decimal |
+-------------+---------+
inventory_id is the unique identifier for this table.
Each row represents the inventory of a specific product at a specific store.
</pre>
<p>Write a solution to find stores that have <strong>inventory imbalance</strong> - stores where the most expensive product has lower stock than the cheapest product.</p>
<ul>
<li>For each store, identify the <strong>most expensive product</strong> (highest price) and its quantity</li>
<li>For each store, identify the <strong>cheapest product</strong> (lowest price) and its quantity</li>
<li>A store has inventory imbalance if the most expensive product's quantity is <strong>less than</strong> the cheapest product's quantity</li>
<li>Calculate the <strong>imbalance ratio</strong> as (cheapest_quantity / most_expensive_quantity)</li>
<li><strong>Round</strong> the imbalance ratio to <strong>2</strong> decimal places</li>
<li>Only include stores that have <strong>at least </strong><code>3</code><strong> different products</strong></li>
</ul>
<p>Return <em>the result table ordered by imbalance ratio in <strong>descending</strong> order, then by store name in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>stores table:</p>
<pre class="example-io">
+----------+----------------+-------------+
| store_id | store_name | location |
+----------+----------------+-------------+
| 1 | Downtown Tech | New York |
| 2 | Suburb Mall | Chicago |
| 3 | City Center | Los Angeles |
| 4 | Corner Shop | Miami |
| 5 | Plaza Store | Seattle |
+----------+----------------+-------------+
</pre>
<p>inventory table:</p>
<pre class="example-io">
+--------------+----------+--------------+----------+--------+
| inventory_id | store_id | product_name | quantity | price |
+--------------+----------+--------------+----------+--------+
| 1 | 1 | Laptop | 5 | 999.99 |
| 2 | 1 | Mouse | 50 | 19.99 |
| 3 | 1 | Keyboard | 25 | 79.99 |
| 4 | 1 | Monitor | 15 | 299.99 |
| 5 | 2 | Phone | 3 | 699.99 |
| 6 | 2 | Charger | 100 | 25.99 |
| 7 | 2 | Case | 75 | 15.99 |
| 8 | 2 | Headphones | 20 | 149.99 |
| 9 | 3 | Tablet | 2 | 499.99 |
| 10 | 3 | Stylus | 80 | 29.99 |
| 11 | 3 | Cover | 60 | 39.99 |
| 12 | 4 | Watch | 10 | 299.99 |
| 13 | 4 | Band | 25 | 49.99 |
| 14 | 5 | Camera | 8 | 599.99 |
| 15 | 5 | Lens | 12 | 199.99 |
+--------------+----------+--------------+----------+--------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+----------+----------------+-------------+------------------+--------------------+------------------+
| store_id | store_name | location | most_exp_product | cheapest_product | imbalance_ratio |
+----------+----------------+-------------+------------------+--------------------+------------------+
| 3 | City Center | Los Angeles | Tablet | Stylus | 40.00 |
| 1 | Downtown Tech | New York | Laptop | Mouse | 10.00 |
| 2 | Suburb Mall | Chicago | Phone | Case | 25.00 |
+----------+----------------+-------------+------------------+--------------------+------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Downtown Tech (store_id = 1):</strong>
<ul>
<li>Most expensive product: Laptop ($999.99) with quantity 5</li>
<li>Cheapest product: Mouse ($19.99) with quantity 50</li>
<li>Inventory imbalance: 5 < 50 (expensive product has lower stock)</li>
<li>Imbalance ratio: 50 / 5 = 10.00</li>
<li>Has 4 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>Suburb Mall (store_id = 2):</strong>
<ul>
<li>Most expensive product: Phone ($699.99) with quantity 3</li>
<li>Cheapest product: Case ($15.99) with quantity 75</li>
<li>Inventory imbalance: 3 < 75 (expensive product has lower stock)</li>
<li>Imbalance ratio: 75 / 3 = 25.00</li>
<li>Has 4 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>City Center (store_id = 3):</strong>
<ul>
<li>Most expensive product: Tablet ($499.99) with quantity 2</li>
<li>Cheapest product: Stylus ($29.99) with quantity 80</li>
<li>Inventory imbalance: 2 < 80 (expensive product has lower stock)</li>
<li>Imbalance ratio: 80 / 2 = 40.00</li>
<li>Has 3 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>Stores not included:</strong>
<ul>
<li>Corner Shop (store_id = 4): Only has 2 products (Watch, Band) - doesn't meet minimum 3 products requirement</li>
<li>Plaza Store (store_id = 5): Only has 2 products (Camera, Lens) - doesn't meet minimum 3 products requirement</li>
</ul>
</li>
</ul>
<p>The Results table is ordered by imbalance ratio in descending order, then by store name in ascending order</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_inventory_imbalance(
stores: pd.DataFrame, inventory: pd.DataFrame
) -> pd.DataFrame:
# Step 1: Identify stores with at least 3 products
store_counts = inventory["store_id"].value_counts()
valid_stores = store_counts[store_counts >= 3].index
# Step 2: Find most expensive product for each valid store
# Sort by price (descending) then quantity (descending) and take first record per store
most_expensive = (
inventory[inventory["store_id"].isin(valid_stores)]
.sort_values(["store_id", "price", "quantity"], ascending=[True, False, False])
.groupby("store_id")
.first()
.reset_index()
)
# Step 3: Find cheapest product for each store
# Sort by price (ascending) then quantity (descending) and take first record per store
cheapest = (
inventory.sort_values(
["store_id", "price", "quantity"], ascending=[True, True, False]
)
.groupby("store_id")
.first()
.reset_index()
)
# Step 4: Merge the two datasets on store_id
merged = pd.merge(
most_expensive, cheapest, on="store_id", suffixes=("_most", "_cheap")
)
# Step 5: Filter for cases where cheapest product has higher quantity than most expensive
result = merged[merged["quantity_most"] < merged["quantity_cheap"]].copy()
# Step 6: Calculate imbalance ratio (cheapest quantity / most expensive quantity)
result["imbalance_ratio"] = (
result["quantity_cheap"] / result["quantity_most"]
).round(2)
# Step 7: Merge with store information to get store names and locations
result = pd.merge(result, stores, on="store_id")
# Step 8: Select and rename columns for final output
result = result[
[
"store_id",
"store_name",
"location",
"product_name_most",
"product_name_cheap",
"imbalance_ratio",
]
].rename(
columns={
"product_name_most": "most_exp_product",
"product_name_cheap": "cheapest_product",
}
)
# Step 9: Sort by imbalance ratio (descending) then store name (ascending)
result = result.sort_values(
["imbalance_ratio", "store_name"], ascending=[False, True]
).reset_index(drop=True)
return result
|
3,626 |
Find Stores with Inventory Imbalance
|
Medium
|
<p>Table: <code>stores</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| store_id | int |
| store_name | varchar |
| location | varchar |
+-------------+---------+
store_id is the unique identifier for this table.
Each row contains information about a store and its location.
</pre>
<p>Table: <code>inventory</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| inventory_id| int |
| store_id | int |
| product_name| varchar |
| quantity | int |
| price | decimal |
+-------------+---------+
inventory_id is the unique identifier for this table.
Each row represents the inventory of a specific product at a specific store.
</pre>
<p>Write a solution to find stores that have <strong>inventory imbalance</strong> - stores where the most expensive product has lower stock than the cheapest product.</p>
<ul>
<li>For each store, identify the <strong>most expensive product</strong> (highest price) and its quantity</li>
<li>For each store, identify the <strong>cheapest product</strong> (lowest price) and its quantity</li>
<li>A store has inventory imbalance if the most expensive product's quantity is <strong>less than</strong> the cheapest product's quantity</li>
<li>Calculate the <strong>imbalance ratio</strong> as (cheapest_quantity / most_expensive_quantity)</li>
<li><strong>Round</strong> the imbalance ratio to <strong>2</strong> decimal places</li>
<li>Only include stores that have <strong>at least </strong><code>3</code><strong> different products</strong></li>
</ul>
<p>Return <em>the result table ordered by imbalance ratio in <strong>descending</strong> order, then by store name in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>stores table:</p>
<pre class="example-io">
+----------+----------------+-------------+
| store_id | store_name | location |
+----------+----------------+-------------+
| 1 | Downtown Tech | New York |
| 2 | Suburb Mall | Chicago |
| 3 | City Center | Los Angeles |
| 4 | Corner Shop | Miami |
| 5 | Plaza Store | Seattle |
+----------+----------------+-------------+
</pre>
<p>inventory table:</p>
<pre class="example-io">
+--------------+----------+--------------+----------+--------+
| inventory_id | store_id | product_name | quantity | price |
+--------------+----------+--------------+----------+--------+
| 1 | 1 | Laptop | 5 | 999.99 |
| 2 | 1 | Mouse | 50 | 19.99 |
| 3 | 1 | Keyboard | 25 | 79.99 |
| 4 | 1 | Monitor | 15 | 299.99 |
| 5 | 2 | Phone | 3 | 699.99 |
| 6 | 2 | Charger | 100 | 25.99 |
| 7 | 2 | Case | 75 | 15.99 |
| 8 | 2 | Headphones | 20 | 149.99 |
| 9 | 3 | Tablet | 2 | 499.99 |
| 10 | 3 | Stylus | 80 | 29.99 |
| 11 | 3 | Cover | 60 | 39.99 |
| 12 | 4 | Watch | 10 | 299.99 |
| 13 | 4 | Band | 25 | 49.99 |
| 14 | 5 | Camera | 8 | 599.99 |
| 15 | 5 | Lens | 12 | 199.99 |
+--------------+----------+--------------+----------+--------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+----------+----------------+-------------+------------------+--------------------+------------------+
| store_id | store_name | location | most_exp_product | cheapest_product | imbalance_ratio |
+----------+----------------+-------------+------------------+--------------------+------------------+
| 3 | City Center | Los Angeles | Tablet | Stylus | 40.00 |
| 1 | Downtown Tech | New York | Laptop | Mouse | 10.00 |
| 2 | Suburb Mall | Chicago | Phone | Case | 25.00 |
+----------+----------------+-------------+------------------+--------------------+------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Downtown Tech (store_id = 1):</strong>
<ul>
<li>Most expensive product: Laptop ($999.99) with quantity 5</li>
<li>Cheapest product: Mouse ($19.99) with quantity 50</li>
<li>Inventory imbalance: 5 < 50 (expensive product has lower stock)</li>
<li>Imbalance ratio: 50 / 5 = 10.00</li>
<li>Has 4 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>Suburb Mall (store_id = 2):</strong>
<ul>
<li>Most expensive product: Phone ($699.99) with quantity 3</li>
<li>Cheapest product: Case ($15.99) with quantity 75</li>
<li>Inventory imbalance: 3 < 75 (expensive product has lower stock)</li>
<li>Imbalance ratio: 75 / 3 = 25.00</li>
<li>Has 4 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>City Center (store_id = 3):</strong>
<ul>
<li>Most expensive product: Tablet ($499.99) with quantity 2</li>
<li>Cheapest product: Stylus ($29.99) with quantity 80</li>
<li>Inventory imbalance: 2 < 80 (expensive product has lower stock)</li>
<li>Imbalance ratio: 80 / 2 = 40.00</li>
<li>Has 3 products (≥ 3), so qualifies</li>
</ul>
</li>
<li><strong>Stores not included:</strong>
<ul>
<li>Corner Shop (store_id = 4): Only has 2 products (Watch, Band) - doesn't meet minimum 3 products requirement</li>
<li>Plaza Store (store_id = 5): Only has 2 products (Camera, Lens) - doesn't meet minimum 3 products requirement</li>
</ul>
</li>
</ul>
<p>The Results table is ordered by imbalance ratio in descending order, then by store name in ascending order</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
store_id,
product_name,
quantity,
RANK() OVER (
PARTITION BY store_id
ORDER BY price DESC, quantity DESC
) rk1,
RANK() OVER (
PARTITION BY store_id
ORDER BY price, quantity DESC
) rk2,
COUNT(1) OVER (PARTITION BY store_id) cnt
FROM inventory
),
P1 AS (
SELECT *
FROM T
WHERE rk1 = 1 AND cnt >= 3
),
P2 AS (
SELECT *
FROM T
WHERE rk2 = 1
)
SELECT
s.store_id store_id,
store_name,
location,
p1.product_name most_exp_product,
p2.product_name cheapest_product,
ROUND(p2.quantity / p1.quantity, 2) imbalance_ratio
FROM
P1 p1
JOIN P2 p2 ON p1.store_id = p2.store_id AND p1.quantity < p2.quantity
JOIN stores s ON p1.store_id = s.store_id
ORDER BY imbalance_ratio DESC, store_name;
|
3,627 |
Maximum Median Sum of Subsequences of Size 3
|
Medium
|
<p>You are given an integer array <code>nums</code> with a length divisible by 3.</p>
<p>You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their <strong>median</strong>, and remove the selected elements from the array.</p>
<p>The <strong>median</strong> of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.</p>
<p>Return the <strong>maximum</strong> possible sum of the medians computed from the selected elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 2, 4, and 5, which have a median 3. After removing these elements, <code>nums</code> becomes <code>[2, 1, 2]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 2. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">20</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 0, 2, and 3, which have a median 10. After removing these elements, <code>nums</code> becomes <code>[1, 10, 10]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 10. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>10 + 10 = 20</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>5</sup></code></li>
<li><code>nums.length % 3 == 0</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
C++
|
class Solution {
public:
long long maximumMedianSum(vector<int>& nums) {
ranges::sort(nums);
int n = nums.size();
long long ans = 0;
for (int i = n / 3; i < n; i += 2) {
ans += nums[i];
}
return ans;
}
};
|
|
3,627 |
Maximum Median Sum of Subsequences of Size 3
|
Medium
|
<p>You are given an integer array <code>nums</code> with a length divisible by 3.</p>
<p>You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their <strong>median</strong>, and remove the selected elements from the array.</p>
<p>The <strong>median</strong> of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.</p>
<p>Return the <strong>maximum</strong> possible sum of the medians computed from the selected elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 2, 4, and 5, which have a median 3. After removing these elements, <code>nums</code> becomes <code>[2, 1, 2]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 2. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">20</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 0, 2, and 3, which have a median 10. After removing these elements, <code>nums</code> becomes <code>[1, 10, 10]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 10. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>10 + 10 = 20</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>5</sup></code></li>
<li><code>nums.length % 3 == 0</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Go
|
func maximumMedianSum(nums []int) (ans int64) {
sort.Ints(nums)
n := len(nums)
for i := n / 3; i < n; i += 2 {
ans += int64(nums[i])
}
return
}
|
|
3,627 |
Maximum Median Sum of Subsequences of Size 3
|
Medium
|
<p>You are given an integer array <code>nums</code> with a length divisible by 3.</p>
<p>You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their <strong>median</strong>, and remove the selected elements from the array.</p>
<p>The <strong>median</strong> of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.</p>
<p>Return the <strong>maximum</strong> possible sum of the medians computed from the selected elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 2, 4, and 5, which have a median 3. After removing these elements, <code>nums</code> becomes <code>[2, 1, 2]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 2. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">20</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 0, 2, and 3, which have a median 10. After removing these elements, <code>nums</code> becomes <code>[1, 10, 10]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 10. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>10 + 10 = 20</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>5</sup></code></li>
<li><code>nums.length % 3 == 0</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Java
|
class Solution {
public long maximumMedianSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
long ans = 0;
for (int i = n / 3; i < n; i += 2) {
ans += nums[i];
}
return ans;
}
}
|
|
3,627 |
Maximum Median Sum of Subsequences of Size 3
|
Medium
|
<p>You are given an integer array <code>nums</code> with a length divisible by 3.</p>
<p>You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their <strong>median</strong>, and remove the selected elements from the array.</p>
<p>The <strong>median</strong> of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.</p>
<p>Return the <strong>maximum</strong> possible sum of the medians computed from the selected elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 2, 4, and 5, which have a median 3. After removing these elements, <code>nums</code> becomes <code>[2, 1, 2]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 2. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">20</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 0, 2, and 3, which have a median 10. After removing these elements, <code>nums</code> becomes <code>[1, 10, 10]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 10. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>10 + 10 = 20</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>5</sup></code></li>
<li><code>nums.length % 3 == 0</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Python
|
class Solution:
def maximumMedianSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[len(nums) // 3 :: 2])
|
|
3,627 |
Maximum Median Sum of Subsequences of Size 3
|
Medium
|
<p>You are given an integer array <code>nums</code> with a length divisible by 3.</p>
<p>You want to make the array empty in steps. In each step, you can select any three elements from the array, compute their <strong>median</strong>, and remove the selected elements from the array.</p>
<p>The <strong>median</strong> of an odd-length sequence is defined as the middle element of the sequence when it is sorted in non-decreasing order.</p>
<p>Return the <strong>maximum</strong> possible sum of the medians computed from the selected elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 2, 4, and 5, which have a median 3. After removing these elements, <code>nums</code> becomes <code>[2, 1, 2]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 2. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,10,10,10,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">20</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first step, select elements at indices 0, 2, and 3, which have a median 10. After removing these elements, <code>nums</code> becomes <code>[1, 10, 10]</code>.</li>
<li>In the second step, select elements at indices 0, 1, and 2, which have a median 10. After removing these elements, <code>nums</code> becomes empty.</li>
</ul>
<p>Hence, the sum of the medians is <code>10 + 10 = 20</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>5</sup></code></li>
<li><code>nums.length % 3 == 0</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
TypeScript
|
function maximumMedianSum(nums: number[]): number {
nums.sort((a, b) => a - b);
const n = nums.length;
let ans = 0;
for (let i = n / 3; i < n; i += 2) {
ans += nums[i];
}
return ans;
}
|
|
3,628 |
Maximum Number of Subsequences After One Inserting
|
Medium
|
<p>You are given a string <code>s</code> consisting of uppercase English letters.</p>
<p>You are allowed to insert <strong>at most one</strong> uppercase English letter at <strong>any</strong> position (including the beginning or end) of the string.</p>
<p>Return the <strong>maximum</strong> number of <code>"LCT"</code> <span data-keyword="subsequence-string-nonempty">subsequences</span> that can be formed in the resulting string after <strong>at most one insertion</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LMCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLMCT"</code>, which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LCCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLCCT"</code>, which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "L"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Since it is not possible to obtain the subsequence <code>"LCT"</code> by inserting a single letter, the result is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of uppercase English letters.</li>
</ul>
|
C++
|
class Solution {
public:
long long numOfSubsequences(string s) {
auto calc = [&](string t) {
long long cnt = 0, a = 0;
for (char c : s) {
if (c == t[1]) {
cnt += a;
}
a += (c == t[0]);
}
return cnt;
};
long long l = 0, r = count(s.begin(), s.end(), 'T');
long long ans = 0, mx = 0;
for (char c : s) {
r -= (c == 'T');
if (c == 'C') {
ans += l * r;
}
l += (c == 'L');
mx = max(mx, l * r);
}
mx = max(mx, calc("LC"));
mx = max(mx, calc("CT"));
ans += mx;
return ans;
}
};
|
|
3,628 |
Maximum Number of Subsequences After One Inserting
|
Medium
|
<p>You are given a string <code>s</code> consisting of uppercase English letters.</p>
<p>You are allowed to insert <strong>at most one</strong> uppercase English letter at <strong>any</strong> position (including the beginning or end) of the string.</p>
<p>Return the <strong>maximum</strong> number of <code>"LCT"</code> <span data-keyword="subsequence-string-nonempty">subsequences</span> that can be formed in the resulting string after <strong>at most one insertion</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LMCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLMCT"</code>, which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LCCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLCCT"</code>, which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "L"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Since it is not possible to obtain the subsequence <code>"LCT"</code> by inserting a single letter, the result is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of uppercase English letters.</li>
</ul>
|
Go
|
func numOfSubsequences(s string) int64 {
calc := func(t string) int64 {
cnt, a := int64(0), int64(0)
for _, c := range s {
if c == rune(t[1]) {
cnt += a
}
if c == rune(t[0]) {
a++
}
}
return cnt
}
l, r := int64(0), int64(0)
for _, c := range s {
if c == 'T' {
r++
}
}
ans, mx := int64(0), int64(0)
for _, c := range s {
if c == 'T' {
r--
}
if c == 'C' {
ans += l * r
}
if c == 'L' {
l++
}
mx = max(mx, l*r)
}
mx = max(mx, calc("LC"), calc("CT"))
ans += mx
return ans
}
|
|
3,628 |
Maximum Number of Subsequences After One Inserting
|
Medium
|
<p>You are given a string <code>s</code> consisting of uppercase English letters.</p>
<p>You are allowed to insert <strong>at most one</strong> uppercase English letter at <strong>any</strong> position (including the beginning or end) of the string.</p>
<p>Return the <strong>maximum</strong> number of <code>"LCT"</code> <span data-keyword="subsequence-string-nonempty">subsequences</span> that can be formed in the resulting string after <strong>at most one insertion</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LMCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLMCT"</code>, which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LCCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLCCT"</code>, which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "L"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Since it is not possible to obtain the subsequence <code>"LCT"</code> by inserting a single letter, the result is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of uppercase English letters.</li>
</ul>
|
Java
|
class Solution {
private char[] s;
public long numOfSubsequences(String S) {
s = S.toCharArray();
int l = 0, r = 0;
for (char c : s) {
if (c == 'T') {
++r;
}
}
long ans = 0, mx = 0;
for (char c : s) {
r -= c == 'T' ? 1 : 0;
if (c == 'C') {
ans += 1L * l * r;
}
l += c == 'L' ? 1 : 0;
mx = Math.max(mx, 1L * l * r);
}
mx = Math.max(mx, Math.max(calc("LC"), calc("CT")));
ans += mx;
return ans;
}
private long calc(String t) {
long cnt = 0;
int a = 0;
for (char c : s) {
if (c == t.charAt(1)) {
cnt += a;
}
a += c == t.charAt(0) ? 1 : 0;
}
return cnt;
}
}
|
|
3,628 |
Maximum Number of Subsequences After One Inserting
|
Medium
|
<p>You are given a string <code>s</code> consisting of uppercase English letters.</p>
<p>You are allowed to insert <strong>at most one</strong> uppercase English letter at <strong>any</strong> position (including the beginning or end) of the string.</p>
<p>Return the <strong>maximum</strong> number of <code>"LCT"</code> <span data-keyword="subsequence-string-nonempty">subsequences</span> that can be formed in the resulting string after <strong>at most one insertion</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LMCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLMCT"</code>, which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LCCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLCCT"</code>, which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "L"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Since it is not possible to obtain the subsequence <code>"LCT"</code> by inserting a single letter, the result is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of uppercase English letters.</li>
</ul>
|
Python
|
class Solution:
def numOfSubsequences(self, s: str) -> int:
def calc(t: str) -> int:
cnt = a = 0
for c in s:
if c == t[1]:
cnt += a
a += int(c == t[0])
return cnt
l, r = 0, s.count("T")
ans = mx = 0
for c in s:
r -= int(c == "T")
if c == "C":
ans += l * r
l += int(c == "L")
mx = max(mx, l * r)
mx = max(mx, calc("LC"), calc("CT"))
ans += mx
return ans
|
|
3,628 |
Maximum Number of Subsequences After One Inserting
|
Medium
|
<p>You are given a string <code>s</code> consisting of uppercase English letters.</p>
<p>You are allowed to insert <strong>at most one</strong> uppercase English letter at <strong>any</strong> position (including the beginning or end) of the string.</p>
<p>Return the <strong>maximum</strong> number of <code>"LCT"</code> <span data-keyword="subsequence-string-nonempty">subsequences</span> that can be formed in the resulting string after <strong>at most one insertion</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LMCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLMCT"</code>, which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "LCCT"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>We can insert a <code>"L"</code> at the beginning of the string s to make <code>"LLCCT"</code>, which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "L"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Since it is not possible to obtain the subsequence <code>"LCT"</code> by inserting a single letter, the result is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of uppercase English letters.</li>
</ul>
|
TypeScript
|
function numOfSubsequences(s: string): number {
const calc = (t: string): number => {
let [cnt, a] = [0, 0];
for (const c of s) {
if (c === t[1]) cnt += a;
if (c === t[0]) a++;
}
return cnt;
};
let [l, r] = [0, 0];
for (const c of s) {
if (c === 'T') r++;
}
let [ans, mx] = [0, 0];
for (const c of s) {
if (c === 'T') r--;
if (c === 'C') ans += l * r;
if (c === 'L') l++;
mx = Math.max(mx, l * r);
}
mx = Math.max(mx, calc('LC'));
mx = Math.max(mx, calc('CT'));
ans += mx;
return ans;
}
|
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
C++
|
class Solution {
public:
vector<vector<int>> sortThreats(vector<vector<int>>& threats) {
sort(threats.begin(), threats.end(), [](const vector<int>& a, const vector<int>& b) {
long long score1 = 2LL * a[1] + a[2];
long long score2 = 2LL * b[1] + b[2];
if (score1 == score2) {
return a[0] < b[0];
}
return score2 < score1;
});
return threats;
}
};
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
Go
|
func sortThreats(threats [][]int) [][]int {
sort.Slice(threats, func(i, j int) bool {
score1 := 2*int64(threats[i][1]) + int64(threats[i][2])
score2 := 2*int64(threats[j][1]) + int64(threats[j][2])
if score1 == score2 {
return threats[i][0] < threats[j][0]
}
return score2 < score1
})
return threats
}
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
Java
|
class Solution {
public int[][] sortThreats(int[][] threats) {
Arrays.sort(threats, (a, b) -> {
long score1 = 2L * a[1] + a[2];
long score2 = 2L * b[1] + b[2];
if (score1 == score2) {
return Integer.compare(a[0], b[0]);
}
return Long.compare(score2, score1);
});
return threats;
}
}
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
Python
|
class Solution:
def sortThreats(self, threats: List[List[int]]) -> List[List[int]]:
threats.sort(key=lambda x: (-(x[1] * 2 + x[2]), x[0]))
return threats
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
Rust
|
impl Solution {
pub fn sort_threats(mut threats: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
threats.sort_by(|a, b| {
let score1 = 2i64 * a[1] as i64 + a[2] as i64;
let score2 = 2i64 * b[1] as i64 + b[2] as i64;
if score1 == score2 {
a[0].cmp(&b[0])
} else {
score2.cmp(&score1)
}
});
threats
}
}
|
3,631 |
Sort Threats by Severity and Exploitability
|
Medium
|
<p>You are given a 2D integer array <code>threats</code>, where each <code>threats[i] = [ID<sub>i</sub>, sev<sub>i</sub>β, exp<sub>i</sub>]</code></p>
<ul>
<li><code>ID<sub>i</sub></code>: Unique identifier of the threat.</li>
<li><code>sev<sub>i</sub></code>: Indicates the severity of the threat.</li>
<li><code>exp<sub>i</sub></code>: Indicates the exploitability of the threat.</li>
</ul>
<p>The<strong> score</strong> of a threat <code>i</code> is defined as: <code>score = 2 × sev<sub>i</sub> + exp<sub>i</sub></code></p>
<p>Your task is to return <code>threats</code> sorted in <strong>descending</strong> order of <strong>score</strong>.</p>
<p>If multiple threats have the same score, sort them by <strong>ascending ID</strong>βββββββ.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,2,3],[102,3,2],[103,3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[103,3,3],[102,3,2],[101,2,3]]</span></p>
<p><strong>Explanation:</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>2</td>
<td>3</td>
<td>2 × 2 + 3 = 7</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>102</td>
<td>3</td>
<td>2</td>
<td>2 × 3 + 2 = 8</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>103</td>
<td>3</td>
<td>3</td>
<td>2 × 3 + 3 = 9</td>
</tr>
</tbody>
</table>
<p>Sorted Order: <code>[[103, 3, 3], [102, 3, 2], [101, 2, 3]]</code></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">threats = [[101,4,1],[103,1,5],[102,1,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[101,4,1],[102,1,5],[103,1,5]]</span></p>
<p><strong>Explanation:βββββββ</strong></p>
<table border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">
<thead>
<tr>
<th>Threat</th>
<th>ID</th>
<th>sev</th>
<th>exp</th>
<th>Score = 2 × sev + exp</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>threats[0]</code></td>
<td>101</td>
<td>4</td>
<td>1</td>
<td>2 × 4 + 1 = 9</td>
</tr>
<tr>
<td><code>threats[1]</code></td>
<td>103</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
<tr>
<td><code>threats[2]</code></td>
<td>102</td>
<td>1</td>
<td>5</td>
<td>2 × 1 + 5 = 7</td>
</tr>
</tbody>
</table>
<p><code>threats[1]</code> and <code>threats[2]</code> have same score, thus sort them by ascending ID.</p>
<p>Sorted Order: <code>[[101, 4, 1], [102, 1, 5], [103, 1, 5]]</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= threats.length <= 10<sup>5</sup></code></li>
<li><code>threats[i] == [ID<sub>i</sub>, sev<sub>i</sub>, exp<sub>i</sub>]</code></li>
<li><code>1 <= ID<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= sev<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= exp<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>All <code>ID<sub>i</sub></code> are <strong>unique</strong></li>
</ul>
|
Array; Sorting
|
TypeScript
|
function sortThreats(threats: number[][]): number[][] {
threats.sort((a, b) => {
const score1 = 2 * a[1] + a[2];
const score2 = 2 * b[1] + b[2];
if (score1 === score2) {
return a[0] - b[0];
}
return score2 - score1;
});
return threats;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.