id
int64 1
3.64k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,248 |
Snake in Matrix
|
Easy
|
<p>There is a snake in an <code>n x n</code> matrix <code>grid</code> and can move in <strong>four possible directions</strong>. Each cell in the <code>grid</code> is identified by the position: <code>grid[i][j] = (i * n) + j</code>.</p>
<p>The snake starts at cell 0 and follows a sequence of commands.</p>
<p>You are given an integer <code>n</code> representing the size of the <code>grid</code> and an array of strings <code>commands</code> where each <code>command[i]</code> is either <code>"UP"</code>, <code>"RIGHT"</code>, <code>"DOWN"</code>, and <code>"LEFT"</code>. It's guaranteed that the snake will remain within the <code>grid</code> boundaries throughout its movement.</p>
<p>Return the position of the final cell where the snake ends up after executing <code>commands</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 = 2, commands = ["RIGHT","DOWN"]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<div style="display:flex; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td>
</tr>
</tbody>
</table>
</div>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, commands = ["DOWN","RIGHT","UP"]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<div style="display:flex; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">5</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">7</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">8</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">5</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">7</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">8</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">5</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">7</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">8</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">0</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">5</td>
</tr>
<tr>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">7</td>
<td data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left="" data-darkreader-inline-border-right="" data-darkreader-inline-border-top="" style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">8</td>
</tr>
</tbody>
</table>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10</code></li>
<li><code>1 <= commands.length <= 100</code></li>
<li><code>commands</code> consists only of <code>"UP"</code>, <code>"RIGHT"</code>, <code>"DOWN"</code>, and <code>"LEFT"</code>.</li>
<li>The input is generated such the snake will not move outside of the boundaries.</li>
</ul>
|
Array; String; Simulation
|
TypeScript
|
function finalPositionOfSnake(n: number, commands: string[]): number {
let [x, y] = [0, 0];
for (const c of commands) {
c[0] === 'U' && x--;
c[0] === 'D' && x++;
c[0] === 'L' && y--;
c[0] === 'R' && y++;
}
return x * n + y;
}
|
3,249 |
Count the Number of Good Nodes
|
Medium
|
<p>There is an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>A node is <strong>good</strong> if all the <span data-keyword="subtree">subtrees</span> rooted at its children have the same size.</p>
<p>Return the number of <strong>good</strong> nodes in the given tree.</p>
<p>A <strong>subtree</strong> of <code>treeName</code> is a tree consisting of a node in <code>treeName</code> and all of its descendants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/tree1.png" style="width: 360px; height: 158px;" />
<p>All of the nodes of the given tree are good.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/screenshot-2024-06-03-193552.png" style="width: 360px; height: 303px;" />
<p>There are 6 good nodes in the given tree. They are colored in the image above.</p>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/rob.jpg" style="width: 450px; height: 277px;" />
<p>All nodes except node 9 are good.</p>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
C++
|
class Solution {
public:
int countGoodNodes(vector<vector<int>>& edges) {
int n = edges.size() + 1;
vector<int> g[n];
for (const auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
int ans = 0;
auto dfs = [&](this auto&& dfs, int a, int fa) -> int {
int pre = -1, cnt = 1, ok = 1;
for (int b : g[a]) {
if (b != fa) {
int cur = dfs(b, a);
cnt += cur;
if (pre < 0) {
pre = cur;
} else if (pre != cur) {
ok = 0;
}
}
}
ans += ok;
return cnt;
};
dfs(0, -1);
return ans;
}
};
|
3,249 |
Count the Number of Good Nodes
|
Medium
|
<p>There is an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>A node is <strong>good</strong> if all the <span data-keyword="subtree">subtrees</span> rooted at its children have the same size.</p>
<p>Return the number of <strong>good</strong> nodes in the given tree.</p>
<p>A <strong>subtree</strong> of <code>treeName</code> is a tree consisting of a node in <code>treeName</code> and all of its descendants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/tree1.png" style="width: 360px; height: 158px;" />
<p>All of the nodes of the given tree are good.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/screenshot-2024-06-03-193552.png" style="width: 360px; height: 303px;" />
<p>There are 6 good nodes in the given tree. They are colored in the image above.</p>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/rob.jpg" style="width: 450px; height: 277px;" />
<p>All nodes except node 9 are good.</p>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Go
|
func countGoodNodes(edges [][]int) (ans int) {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
var dfs func(int, int) int
dfs = func(a, fa int) int {
pre, cnt, ok := -1, 1, 1
for _, b := range g[a] {
if b != fa {
cur := dfs(b, a)
cnt += cur
if pre < 0 {
pre = cur
} else if pre != cur {
ok = 0
}
}
}
ans += ok
return cnt
}
dfs(0, -1)
return
}
|
3,249 |
Count the Number of Good Nodes
|
Medium
|
<p>There is an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>A node is <strong>good</strong> if all the <span data-keyword="subtree">subtrees</span> rooted at its children have the same size.</p>
<p>Return the number of <strong>good</strong> nodes in the given tree.</p>
<p>A <strong>subtree</strong> of <code>treeName</code> is a tree consisting of a node in <code>treeName</code> and all of its descendants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/tree1.png" style="width: 360px; height: 158px;" />
<p>All of the nodes of the given tree are good.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/screenshot-2024-06-03-193552.png" style="width: 360px; height: 303px;" />
<p>There are 6 good nodes in the given tree. They are colored in the image above.</p>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/rob.jpg" style="width: 450px; height: 277px;" />
<p>All nodes except node 9 are good.</p>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Java
|
class Solution {
private int ans;
private List<Integer>[] g;
public int countGoodNodes(int[][] edges) {
int n = edges.length + 1;
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
dfs(0, -1);
return ans;
}
private int dfs(int a, int fa) {
int pre = -1, cnt = 1, ok = 1;
for (int b : g[a]) {
if (b != fa) {
int cur = dfs(b, a);
cnt += cur;
if (pre < 0) {
pre = cur;
} else if (pre != cur) {
ok = 0;
}
}
}
ans += ok;
return cnt;
}
}
|
3,249 |
Count the Number of Good Nodes
|
Medium
|
<p>There is an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>A node is <strong>good</strong> if all the <span data-keyword="subtree">subtrees</span> rooted at its children have the same size.</p>
<p>Return the number of <strong>good</strong> nodes in the given tree.</p>
<p>A <strong>subtree</strong> of <code>treeName</code> is a tree consisting of a node in <code>treeName</code> and all of its descendants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/tree1.png" style="width: 360px; height: 158px;" />
<p>All of the nodes of the given tree are good.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/screenshot-2024-06-03-193552.png" style="width: 360px; height: 303px;" />
<p>There are 6 good nodes in the given tree. They are colored in the image above.</p>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/rob.jpg" style="width: 450px; height: 277px;" />
<p>All nodes except node 9 are good.</p>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
Python
|
class Solution:
def countGoodNodes(self, edges: List[List[int]]) -> int:
def dfs(a: int, fa: int) -> int:
pre = -1
cnt = ok = 1
for b in g[a]:
if b != fa:
cur = dfs(b, a)
cnt += cur
if pre < 0:
pre = cur
elif pre != cur:
ok = 0
nonlocal ans
ans += ok
return cnt
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
|
3,249 |
Count the Number of Good Nodes
|
Medium
|
<p>There is an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>A node is <strong>good</strong> if all the <span data-keyword="subtree">subtrees</span> rooted at its children have the same size.</p>
<p>Return the number of <strong>good</strong> nodes in the given tree.</p>
<p>A <strong>subtree</strong> of <code>treeName</code> is a tree consisting of a node in <code>treeName</code> and all of its descendants.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/tree1.png" style="width: 360px; height: 158px;" />
<p>All of the nodes of the given tree are good.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/screenshot-2024-06-03-193552.png" style="width: 360px; height: 303px;" />
<p>There are 6 good nodes in the given tree. They are colored in the image above.</p>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3249.Count%20the%20Number%20of%20Good%20Nodes/images/rob.jpg" style="width: 450px; height: 277px;" />
<p>All nodes except node 9 are good.</p>
</div>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search
|
TypeScript
|
function countGoodNodes(edges: number[][]): number {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
let ans = 0;
const dfs = (a: number, fa: number): number => {
let [pre, cnt, ok] = [-1, 1, 1];
for (const b of g[a]) {
if (b !== fa) {
const cur = dfs(b, a);
cnt += cur;
if (pre < 0) {
pre = cur;
} else if (pre !== cur) {
ok = 0;
}
}
}
ans += ok;
return cnt;
};
dfs(0, -1);
return ans;
}
|
3,250 |
Find the Count of Monotonic Pairs I
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
C++
|
class Solution {
public:
int countOfPairs(vector<int>& nums) {
const int mod = 1e9 + 7;
int n = nums.size();
int m = *max_element(nums.begin(), nums.end());
vector<vector<int>> f(n, vector<int>(m + 1));
for (int j = 0; j <= nums[0]; ++j) {
f[0][j] = 1;
}
vector<int> g(m + 1);
for (int i = 1; i < n; ++i) {
g[0] = f[i - 1][0];
for (int j = 1; j <= m; ++j) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (int j = 0; j <= nums[i]; ++j) {
int k = min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
int ans = 0;
for (int j = 0; j <= nums[n - 1]; ++j) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
};
|
3,250 |
Find the Count of Monotonic Pairs I
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Go
|
func countOfPairs(nums []int) (ans int) {
const mod int = 1e9 + 7
n := len(nums)
m := slices.Max(nums)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, m+1)
}
for j := 0; j <= nums[0]; j++ {
f[0][j] = 1
}
g := make([]int, m+1)
for i := 1; i < n; i++ {
g[0] = f[i-1][0]
for j := 1; j <= m; j++ {
g[j] = (g[j-1] + f[i-1][j]) % mod
}
for j := 0; j <= nums[i]; j++ {
k := min(j, j+nums[i-1]-nums[i])
if k >= 0 {
f[i][j] = g[k]
}
}
}
for j := 0; j <= nums[n-1]; j++ {
ans = (ans + f[n-1][j]) % mod
}
return
}
|
3,250 |
Find the Count of Monotonic Pairs I
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Java
|
class Solution {
public int countOfPairs(int[] nums) {
final int mod = (int) 1e9 + 7;
int n = nums.length;
int m = Arrays.stream(nums).max().getAsInt();
int[][] f = new int[n][m + 1];
for (int j = 0; j <= nums[0]; ++j) {
f[0][j] = 1;
}
int[] g = new int[m + 1];
for (int i = 1; i < n; ++i) {
g[0] = f[i - 1][0];
for (int j = 1; j <= m; ++j) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (int j = 0; j <= nums[i]; ++j) {
int k = Math.min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
int ans = 0;
for (int j = 0; j <= nums[n - 1]; ++j) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
}
|
3,250 |
Find the Count of Monotonic Pairs I
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Python
|
class Solution:
def countOfPairs(self, nums: List[int]) -> int:
mod = 10**9 + 7
n, m = len(nums), max(nums)
f = [[0] * (m + 1) for _ in range(n)]
for j in range(nums[0] + 1):
f[0][j] = 1
for i in range(1, n):
s = list(accumulate(f[i - 1]))
for j in range(nums[i] + 1):
k = min(j, j + nums[i - 1] - nums[i])
if k >= 0:
f[i][j] = s[k] % mod
return sum(f[-1][: nums[-1] + 1]) % mod
|
3,250 |
Find the Count of Monotonic Pairs I
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
TypeScript
|
function countOfPairs(nums: number[]): number {
const mod = 1e9 + 7;
const n = nums.length;
const m = Math.max(...nums);
const f: number[][] = Array.from({ length: n }, () => Array(m + 1).fill(0));
for (let j = 0; j <= nums[0]; j++) {
f[0][j] = 1;
}
const g: number[] = Array(m + 1).fill(0);
for (let i = 1; i < n; i++) {
g[0] = f[i - 1][0];
for (let j = 1; j <= m; j++) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (let j = 0; j <= nums[i]; j++) {
const k = Math.min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
let ans = 0;
for (let j = 0; j <= nums[n - 1]; j++) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
|
3,251 |
Find the Count of Monotonic Pairs II
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
C++
|
class Solution {
public:
int countOfPairs(vector<int>& nums) {
const int mod = 1e9 + 7;
int n = nums.size();
int m = *max_element(nums.begin(), nums.end());
vector<vector<int>> f(n, vector<int>(m + 1));
for (int j = 0; j <= nums[0]; ++j) {
f[0][j] = 1;
}
vector<int> g(m + 1);
for (int i = 1; i < n; ++i) {
g[0] = f[i - 1][0];
for (int j = 1; j <= m; ++j) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (int j = 0; j <= nums[i]; ++j) {
int k = min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
int ans = 0;
for (int j = 0; j <= nums[n - 1]; ++j) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
};
|
3,251 |
Find the Count of Monotonic Pairs II
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Go
|
func countOfPairs(nums []int) (ans int) {
const mod int = 1e9 + 7
n := len(nums)
m := slices.Max(nums)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, m+1)
}
for j := 0; j <= nums[0]; j++ {
f[0][j] = 1
}
g := make([]int, m+1)
for i := 1; i < n; i++ {
g[0] = f[i-1][0]
for j := 1; j <= m; j++ {
g[j] = (g[j-1] + f[i-1][j]) % mod
}
for j := 0; j <= nums[i]; j++ {
k := min(j, j+nums[i-1]-nums[i])
if k >= 0 {
f[i][j] = g[k]
}
}
}
for j := 0; j <= nums[n-1]; j++ {
ans = (ans + f[n-1][j]) % mod
}
return
}
|
3,251 |
Find the Count of Monotonic Pairs II
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Java
|
class Solution {
public int countOfPairs(int[] nums) {
final int mod = (int) 1e9 + 7;
int n = nums.length;
int m = Arrays.stream(nums).max().getAsInt();
int[][] f = new int[n][m + 1];
for (int j = 0; j <= nums[0]; ++j) {
f[0][j] = 1;
}
int[] g = new int[m + 1];
for (int i = 1; i < n; ++i) {
g[0] = f[i - 1][0];
for (int j = 1; j <= m; ++j) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (int j = 0; j <= nums[i]; ++j) {
int k = Math.min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
int ans = 0;
for (int j = 0; j <= nums[n - 1]; ++j) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
}
|
3,251 |
Find the Count of Monotonic Pairs II
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
Python
|
class Solution:
def countOfPairs(self, nums: List[int]) -> int:
mod = 10**9 + 7
n, m = len(nums), max(nums)
f = [[0] * (m + 1) for _ in range(n)]
for j in range(nums[0] + 1):
f[0][j] = 1
for i in range(1, n):
s = list(accumulate(f[i - 1]))
for j in range(nums[i] + 1):
k = min(j, j + nums[i - 1] - nums[i])
if k >= 0:
f[i][j] = s[k] % mod
return sum(f[-1][: nums[-1] + 1]) % mod
|
3,251 |
Find the Count of Monotonic Pairs II
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>We call a pair of <strong>non-negative</strong> integer arrays <code>(arr1, arr2)</code> <strong>monotonic</strong> if:</p>
<ul>
<li>The lengths of both arrays are <code>n</code>.</li>
<li><code>arr1</code> is monotonically <strong>non-decreasing</strong>, in other words, <code>arr1[0] <= arr1[1] <= ... <= arr1[n - 1]</code>.</li>
<li><code>arr2</code> is monotonically <strong>non-increasing</strong>, in other words, <code>arr2[0] >= arr2[1] >= ... >= arr2[n - 1]</code>.</li>
<li><code>arr1[i] + arr2[i] == nums[i]</code> for all <code>0 <= i <= n - 1</code>.</li>
</ul>
<p>Return the count of <strong>monotonic</strong> pairs.</p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The good pairs are:</p>
<ol>
<li><code>([0, 1, 1], [2, 2, 1])</code></li>
<li><code>([0, 1, 2], [2, 2, 0])</code></li>
<li><code>([0, 2, 2], [2, 1, 0])</code></li>
<li><code>([1, 2, 2], [1, 1, 0])</code></li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">126</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math; Dynamic Programming; Combinatorics; Prefix Sum
|
TypeScript
|
function countOfPairs(nums: number[]): number {
const mod = 1e9 + 7;
const n = nums.length;
const m = Math.max(...nums);
const f: number[][] = Array.from({ length: n }, () => Array(m + 1).fill(0));
for (let j = 0; j <= nums[0]; j++) {
f[0][j] = 1;
}
const g: number[] = Array(m + 1).fill(0);
for (let i = 1; i < n; i++) {
g[0] = f[i - 1][0];
for (let j = 1; j <= m; j++) {
g[j] = (g[j - 1] + f[i - 1][j]) % mod;
}
for (let j = 0; j <= nums[i]; j++) {
const k = Math.min(j, j + nums[i - 1] - nums[i]);
if (k >= 0) {
f[i][j] = g[k];
}
}
}
let ans = 0;
for (let j = 0; j <= nums[n - 1]; j++) {
ans = (ans + f[n - 1][j]) % mod;
}
return ans;
}
|
3,252 |
Premier League Table Ranking II
|
Medium
|
<p>Table: <code>TeamStats</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| team_id | int |
| team_name | varchar |
| matches_played | int |
| wins | int |
| draws | int |
| losses | int |
+------------------+---------+
team_id is the unique key for this table.
This table contains team id, team name, matches_played, wins, draws, and losses.
</pre>
<p>Write a solution to calculate the <strong>points</strong>, <strong>position</strong>, and <strong>tier</strong> for each team in the league. Points are calculated as follows:</p>
<ul>
<li><code>3</code> points for a <strong>win</strong></li>
<li><code>1</code> point for a <strong>draw</strong></li>
<li><code>0</code> points for a <strong>loss</strong></li>
</ul>
<p><strong>Note:</strong> Teams with the same points must be assigned the same position.</p>
<p><strong>Tier ranking:</strong></p>
<ul>
<li>Divide the league into <code>3</code> tiers based on points:</li>
<li>Tier 1: Top <code>33%</code> of teams</li>
<li>Tier 2: Middle <code>33%</code> of teams</li>
<li>Tier 3: Bottom<code> 34%</code> of teams</li>
<li>In case of <strong>ties</strong> at<strong> tier boundaries</strong>, place tied teams in the <strong>higher tier</strong>.</li>
</ul>
<p>Return <em>the result table </em><em>ordered by</em> <code>points</code> <em>in <strong>descending</strong>,<strong> </strong>and then by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The query result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>TeamStats</code> table:</p>
<pre class="example-io">
+---------+-------------------+----------------+------+-------+--------+
| team_id | team_name | matches_played | wins | draws | losses |
+---------+-------------------+----------------+------+-------+--------+
| 1 | Chelsea | 22 | 13 | 2 | 7 |
| 2 | Nottingham Forest | 27 | 6 | 6 | 15 |
| 3 | Liverpool | 17 | 1 | 8 | 8 |
| 4 | Aston Villa | 20 | 1 | 6 | 13 |
| 5 | Fulham | 31 | 18 | 1 | 12 |
| 6 | Burnley | 26 | 6 | 9 | 11 |
| 7 | Newcastle United | 33 | 11 | 10 | 12 |
| 8 | Sheffield United | 20 | 18 | 2 | 0 |
| 9 | Luton Town | 5 | 4 | 0 | 1 |
| 10 | Everton | 14 | 2 | 6 | 6 |
+---------+-------------------+----------------+------+-------+--------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------------+--------+----------+---------+
| team_name | points | position | tier |
+-------------------+--------+----------+---------+
| Sheffield United | 56 | 1 | Tier 1 |
| Fulham | 55 | 2 | Tier 1 |
| Newcastle United | 43 | 3 | Tier 1 |
| Chelsea | 41 | 4 | Tier 1 |
| Burnley | 27 | 5 | Tier 2 |
| Nottingham Forest | 24 | 6 | Tier 2 |
| Everton | 12 | 7 | Tier 2 |
| Luton Town | 12 | 7 | Tier 2 |
| Liverpool | 11 | 9 | Tier 3 |
| Aston Villa | 9 | 10 | Tier 3 |
+-------------------+--------+----------+---------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Sheffield United has 56 points (18 wins * 3 points + 2 draws * 1 point) and is in position 1.</li>
<li>Fulham has 55 points (18 wins * 3 points + 1 draw * 1 point) and is in position 2.</li>
<li>Newcastle United has 43 points (11 wins * 3 points + 10 draws * 1 point) and is in position 3.</li>
<li>Chelsea has 41 points (13 wins * 3 points + 2 draws * 1 point) and is in position 4.</li>
<li>Burnley has 27 points (6 wins * 3 points + 9 draws * 1 point) and is in position 5.</li>
<li>Nottingham Forest has 24 points (6 wins * 3 points + 6 draws * 1 point) and is in position 6.</li>
<li>Everton and Luton Town both have 12 points, with Everton having 2 wins * 3 points + 6 draws * 1 point, and Luton Town having 4 wins * 3 points. Both teams share position 7.</li>
<li>Liverpool has 11 points (1 win * 3 points + 8 draws * 1 point) and is in position 9.</li>
<li>Aston Villa has 9 points (1 win * 3 points + 6 draws * 1 point) and is in position 10.</li>
</ul>
<p><strong>Tier Calculation:</strong></p>
<ul>
<li><strong>Tier 1:</strong> The top 33% of teams based on points. Sheffield United, Fulham, Newcastle United, and Chelsea fall into Tier 1.</li>
<li><strong>Tier 2:</strong> The middle 33% of teams. Burnley, Nottingham Forest, Everton, and Luton Town fall into Tier 2.</li>
<li><strong>Tier 3:</strong> The bottom 34% of teams. Liverpool and Aston Villa fall into Tier 3.</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def calculate_team_tiers(team_stats: pd.DataFrame) -> pd.DataFrame:
team_stats["points"] = team_stats["wins"] * 3 + team_stats["draws"]
team_stats["position"] = (
team_stats["points"].rank(method="min", ascending=False).astype(int)
)
total_teams = len(team_stats)
team_stats["tier"] = np.where(
team_stats["position"] <= np.ceil(total_teams / 3.0),
"Tier 1",
np.where(
team_stats["position"] <= np.ceil(2 * total_teams / 3.0), "Tier 2", "Tier 3"
),
)
team_stats = team_stats.sort_values(
by=["points", "team_name"], ascending=[False, True]
)
return team_stats[["team_name", "points", "position", "tier"]]
|
3,252 |
Premier League Table Ranking II
|
Medium
|
<p>Table: <code>TeamStats</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| team_id | int |
| team_name | varchar |
| matches_played | int |
| wins | int |
| draws | int |
| losses | int |
+------------------+---------+
team_id is the unique key for this table.
This table contains team id, team name, matches_played, wins, draws, and losses.
</pre>
<p>Write a solution to calculate the <strong>points</strong>, <strong>position</strong>, and <strong>tier</strong> for each team in the league. Points are calculated as follows:</p>
<ul>
<li><code>3</code> points for a <strong>win</strong></li>
<li><code>1</code> point for a <strong>draw</strong></li>
<li><code>0</code> points for a <strong>loss</strong></li>
</ul>
<p><strong>Note:</strong> Teams with the same points must be assigned the same position.</p>
<p><strong>Tier ranking:</strong></p>
<ul>
<li>Divide the league into <code>3</code> tiers based on points:</li>
<li>Tier 1: Top <code>33%</code> of teams</li>
<li>Tier 2: Middle <code>33%</code> of teams</li>
<li>Tier 3: Bottom<code> 34%</code> of teams</li>
<li>In case of <strong>ties</strong> at<strong> tier boundaries</strong>, place tied teams in the <strong>higher tier</strong>.</li>
</ul>
<p>Return <em>the result table </em><em>ordered by</em> <code>points</code> <em>in <strong>descending</strong>,<strong> </strong>and then by</em> <code>team_name</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The query result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>TeamStats</code> table:</p>
<pre class="example-io">
+---------+-------------------+----------------+------+-------+--------+
| team_id | team_name | matches_played | wins | draws | losses |
+---------+-------------------+----------------+------+-------+--------+
| 1 | Chelsea | 22 | 13 | 2 | 7 |
| 2 | Nottingham Forest | 27 | 6 | 6 | 15 |
| 3 | Liverpool | 17 | 1 | 8 | 8 |
| 4 | Aston Villa | 20 | 1 | 6 | 13 |
| 5 | Fulham | 31 | 18 | 1 | 12 |
| 6 | Burnley | 26 | 6 | 9 | 11 |
| 7 | Newcastle United | 33 | 11 | 10 | 12 |
| 8 | Sheffield United | 20 | 18 | 2 | 0 |
| 9 | Luton Town | 5 | 4 | 0 | 1 |
| 10 | Everton | 14 | 2 | 6 | 6 |
+---------+-------------------+----------------+------+-------+--------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------------+--------+----------+---------+
| team_name | points | position | tier |
+-------------------+--------+----------+---------+
| Sheffield United | 56 | 1 | Tier 1 |
| Fulham | 55 | 2 | Tier 1 |
| Newcastle United | 43 | 3 | Tier 1 |
| Chelsea | 41 | 4 | Tier 1 |
| Burnley | 27 | 5 | Tier 2 |
| Nottingham Forest | 24 | 6 | Tier 2 |
| Everton | 12 | 7 | Tier 2 |
| Luton Town | 12 | 7 | Tier 2 |
| Liverpool | 11 | 9 | Tier 3 |
| Aston Villa | 9 | 10 | Tier 3 |
+-------------------+--------+----------+---------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Sheffield United has 56 points (18 wins * 3 points + 2 draws * 1 point) and is in position 1.</li>
<li>Fulham has 55 points (18 wins * 3 points + 1 draw * 1 point) and is in position 2.</li>
<li>Newcastle United has 43 points (11 wins * 3 points + 10 draws * 1 point) and is in position 3.</li>
<li>Chelsea has 41 points (13 wins * 3 points + 2 draws * 1 point) and is in position 4.</li>
<li>Burnley has 27 points (6 wins * 3 points + 9 draws * 1 point) and is in position 5.</li>
<li>Nottingham Forest has 24 points (6 wins * 3 points + 6 draws * 1 point) and is in position 6.</li>
<li>Everton and Luton Town both have 12 points, with Everton having 2 wins * 3 points + 6 draws * 1 point, and Luton Town having 4 wins * 3 points. Both teams share position 7.</li>
<li>Liverpool has 11 points (1 win * 3 points + 8 draws * 1 point) and is in position 9.</li>
<li>Aston Villa has 9 points (1 win * 3 points + 6 draws * 1 point) and is in position 10.</li>
</ul>
<p><strong>Tier Calculation:</strong></p>
<ul>
<li><strong>Tier 1:</strong> The top 33% of teams based on points. Sheffield United, Fulham, Newcastle United, and Chelsea fall into Tier 1.</li>
<li><strong>Tier 2:</strong> The middle 33% of teams. Burnley, Nottingham Forest, Everton, and Luton Town fall into Tier 2.</li>
<li><strong>Tier 3:</strong> The bottom 34% of teams. Liverpool and Aston Villa fall into Tier 3.</li>
</ul>
</div>
|
Database
|
SQL
|
WITH
T AS (
SELECT
team_name,
wins * 3 + draws AS points,
RANK() OVER (ORDER BY wins * 3 + draws DESC) AS position,
COUNT(1) OVER () AS total_teams
FROM TeamStats
)
SELECT
team_name,
points,
position,
CASE
WHEN position <= CEIL(total_teams / 3.0) THEN 'Tier 1'
WHEN position <= CEIL(2 * total_teams / 3.0) THEN 'Tier 2'
ELSE 'Tier 3'
END tier
FROM T
ORDER BY 2 DESC, 1;
|
3,253 |
Construct String with Minimum Cost (Easy)
|
Medium
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 2000</code></li>
<li><code>1 <= words.length == costs.length <= 50</code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>5</sup></code></li>
</ul>
|
C++
|
const int inf = 1 << 29;
class Trie {
public:
Trie* children[26]{};
int cost = inf;
void insert(string& word, int cost) {
Trie* node = this;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) {
node->children[idx] = new Trie();
}
node = node->children[idx];
}
node->cost = min(node->cost, cost);
}
};
class Solution {
public:
int minimumCost(string target, vector<string>& words, vector<int>& costs) {
Trie* trie = new Trie();
for (int i = 0; i < words.size(); ++i) {
trie->insert(words[i], costs[i]);
}
int n = target.length();
int f[n];
memset(f, 0, sizeof(f));
auto dfs = [&](this auto&& dfs, int i) -> int {
if (i >= n) {
return 0;
}
if (f[i]) {
return f[i];
}
f[i] = inf;
Trie* node = trie;
for (int j = i; j < n; ++j) {
int idx = target[j] - 'a';
if (!node->children[idx]) {
return f[i];
}
node = node->children[idx];
f[i] = min(f[i], node->cost + dfs(j + 1));
}
return f[i];
};
int ans = dfs(0);
return ans < inf ? ans : -1;
}
};
|
|
3,253 |
Construct String with Minimum Cost (Easy)
|
Medium
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 2000</code></li>
<li><code>1 <= words.length == costs.length <= 50</code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>5</sup></code></li>
</ul>
|
Go
|
const inf = 1 << 29
type Trie struct {
children [26]*Trie
cost int
}
func NewTrie() *Trie {
return &Trie{cost: inf}
}
func (t *Trie) insert(word string, cost int) {
node := t
for _, c := range word {
idx := c - 'a'
if node.children[idx] == nil {
node.children[idx] = NewTrie()
}
node = node.children[idx]
}
node.cost = min(node.cost, cost)
}
func minimumCost(target string, words []string, costs []int) int {
trie := NewTrie()
for i, word := range words {
trie.insert(word, costs[i])
}
n := len(target)
f := make([]int, n)
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] != 0 {
return f[i]
}
f[i] = inf
node := trie
for j := i; j < n; j++ {
idx := target[j] - 'a'
if node.children[idx] == nil {
return f[i]
}
node = node.children[idx]
f[i] = min(f[i], node.cost+dfs(j+1))
}
return f[i]
}
if ans := dfs(0); ans < inf {
return ans
}
return -1
}
|
|
3,253 |
Construct String with Minimum Cost (Easy)
|
Medium
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 2000</code></li>
<li><code>1 <= words.length == costs.length <= 50</code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>5</sup></code></li>
</ul>
|
Java
|
class Trie {
public final int inf = 1 << 29;
public Trie[] children = new Trie[26];
public int cost = inf;
public void insert(String word, int cost) {
Trie node = this;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.cost = Math.min(node.cost, cost);
}
}
class Solution {
private Trie trie = new Trie();
private char[] target;
private Integer[] f;
public int minimumCost(String target, String[] words, int[] costs) {
for (int i = 0; i < words.length; ++i) {
trie.insert(words[i], costs[i]);
}
this.target = target.toCharArray();
f = new Integer[target.length()];
int ans = dfs(0);
return ans < trie.inf ? ans : -1;
}
private int dfs(int i) {
if (i >= target.length) {
return 0;
}
if (f[i] != null) {
return f[i];
}
f[i] = trie.inf;
Trie node = trie;
for (int j = i; j < target.length; ++j) {
int idx = target[j] - 'a';
if (node.children[idx] == null) {
return f[i];
}
node = node.children[idx];
f[i] = Math.min(f[i], node.cost + dfs(j + 1));
}
return f[i];
}
}
|
|
3,253 |
Construct String with Minimum Cost (Easy)
|
Medium
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 2000</code></li>
<li><code>1 <= words.length == costs.length <= 50</code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>5</sup></code></li>
</ul>
|
Python
|
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
self.cost = inf
def insert(self, word: str, cost: int):
node = self
for c in word:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.cost = min(node.cost, cost)
class Solution:
def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(target):
return 0
ans = inf
node = trie
for j in range(i, len(target)):
idx = ord(target[j]) - ord("a")
if node.children[idx] is None:
return ans
node = node.children[idx]
ans = min(ans, node.cost + dfs(j + 1))
return ans
trie = Trie()
for word, cost in zip(words, costs):
trie.insert(word, cost)
ans = dfs(0)
return ans if ans < inf else -1
|
|
3,253 |
Construct String with Minimum Cost (Easy)
|
Medium
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 2000</code></li>
<li><code>1 <= words.length == costs.length <= 50</code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>5</sup></code></li>
</ul>
|
TypeScript
|
const inf = 1 << 29;
class Trie {
children: (Trie | null)[];
cost: number;
constructor() {
this.children = Array(26).fill(null);
this.cost = inf;
}
insert(word: string, cost: number): void {
let node: Trie = this;
for (const c of word) {
const idx = c.charCodeAt(0) - 97;
if (!node.children[idx]) {
node.children[idx] = new Trie();
}
node = node.children[idx]!;
}
node.cost = Math.min(node.cost, cost);
}
}
function minimumCost(target: string, words: string[], costs: number[]): number {
const trie = new Trie();
for (let i = 0; i < words.length; ++i) {
trie.insert(words[i], costs[i]);
}
const n = target.length;
const f: number[] = Array(n).fill(0);
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i]) {
return f[i];
}
f[i] = inf;
let node: Trie | null = trie;
for (let j = i; j < n; ++j) {
const idx = target.charCodeAt(j) - 97;
if (!node?.children[idx]) {
return f[i];
}
node = node.children[idx];
f[i] = Math.min(f[i], node!.cost + dfs(j + 1));
}
return f[i];
};
const ans = dfs(0);
return ans < inf ? ans : -1;
}
|
|
3,254 |
Find the Power of K-Size Subarrays I
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
C++
|
class Solution {
public:
vector<int> resultsArray(vector<int>& nums, int k) {
int n = nums.size();
int f[n];
f[0] = 1;
for (int i = 1; i < n; ++i) {
f[i] = nums[i] == nums[i - 1] + 1 ? f[i - 1] + 1 : 1;
}
vector<int> ans;
for (int i = k - 1; i < n; ++i) {
ans.push_back(f[i] >= k ? nums[i] : -1);
}
return ans;
}
};
|
3,254 |
Find the Power of K-Size Subarrays I
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Go
|
func resultsArray(nums []int, k int) (ans []int) {
n := len(nums)
f := make([]int, n)
f[0] = 1
for i := 1; i < n; i++ {
if nums[i] == nums[i-1]+1 {
f[i] = f[i-1] + 1
} else {
f[i] = 1
}
}
for i := k - 1; i < n; i++ {
if f[i] >= k {
ans = append(ans, nums[i])
} else {
ans = append(ans, -1)
}
}
return
}
|
3,254 |
Find the Power of K-Size Subarrays I
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Java
|
class Solution {
public int[] resultsArray(int[] nums, int k) {
int n = nums.length;
int[] f = new int[n];
Arrays.fill(f, 1);
for (int i = 1; i < n; ++i) {
if (nums[i] == nums[i - 1] + 1) {
f[i] = f[i - 1] + 1;
}
}
int[] ans = new int[n - k + 1];
for (int i = k - 1; i < n; ++i) {
ans[i - k + 1] = f[i] >= k ? nums[i] : -1;
}
return ans;
}
}
|
3,254 |
Find the Power of K-Size Subarrays I
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Python
|
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1] * n
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
f[i] = f[i - 1] + 1
return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]
|
3,254 |
Find the Power of K-Size Subarrays I
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 500</code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
TypeScript
|
function resultsArray(nums: number[], k: number): number[] {
const n = nums.length;
const f: number[] = Array(n).fill(1);
for (let i = 1; i < n; ++i) {
if (nums[i] === nums[i - 1] + 1) {
f[i] = f[i - 1] + 1;
}
}
const ans: number[] = [];
for (let i = k - 1; i < n; ++i) {
ans.push(f[i] >= k ? nums[i] : -1);
}
return ans;
}
|
3,255 |
Find the Power of K-Size Subarrays II
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
C++
|
class Solution {
public:
vector<int> resultsArray(vector<int>& nums, int k) {
int n = nums.size();
int f[n];
f[0] = 1;
for (int i = 1; i < n; ++i) {
f[i] = nums[i] == nums[i - 1] + 1 ? f[i - 1] + 1 : 1;
}
vector<int> ans;
for (int i = k - 1; i < n; ++i) {
ans.push_back(f[i] >= k ? nums[i] : -1);
}
return ans;
}
};
|
3,255 |
Find the Power of K-Size Subarrays II
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Go
|
func resultsArray(nums []int, k int) (ans []int) {
n := len(nums)
f := make([]int, n)
f[0] = 1
for i := 1; i < n; i++ {
if nums[i] == nums[i-1]+1 {
f[i] = f[i-1] + 1
} else {
f[i] = 1
}
}
for i := k - 1; i < n; i++ {
if f[i] >= k {
ans = append(ans, nums[i])
} else {
ans = append(ans, -1)
}
}
return
}
|
3,255 |
Find the Power of K-Size Subarrays II
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Java
|
class Solution {
public int[] resultsArray(int[] nums, int k) {
int n = nums.length;
int[] f = new int[n];
Arrays.fill(f, 1);
for (int i = 1; i < n; ++i) {
if (nums[i] == nums[i - 1] + 1) {
f[i] = f[i - 1] + 1;
}
}
int[] ans = new int[n - k + 1];
for (int i = k - 1; i < n; ++i) {
ans[i - k + 1] = f[i] >= k ? nums[i] : -1;
}
return ans;
}
}
|
3,255 |
Find the Power of K-Size Subarrays II
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
Python
|
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1] * n
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
f[i] = f[i - 1] + 1
return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]
|
3,255 |
Find the Power of K-Size Subarrays II
|
Medium
|
<p>You are given an array of integers <code>nums</code> of length <code>n</code> and a <em>positive</em> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array is defined as:</p>
<ul>
<li>Its <strong>maximum</strong> element if <em>all</em> of its elements are <strong>consecutive</strong> and <strong>sorted</strong> in <strong>ascending</strong> order.</li>
<li>-1 otherwise.</li>
</ul>
<p>You need to find the <strong>power</strong> of all <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> of size <code>k</code>.</p>
<p>Return an integer array <code>results</code> of size <code>n - k + 1</code>, where <code>results[i]</code> is the <em>power</em> of <code>nums[i..(i + k - 1)]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,2,5], k = 3</span></p>
<p><strong>Output:</strong> [3,4,-1,-1,-1]</p>
<p><strong>Explanation:</strong></p>
<p>There are 5 subarrays of <code>nums</code> of size 3:</p>
<ul>
<li><code>[1, 2, 3]</code> with the maximum element 3.</li>
<li><code>[2, 3, 4]</code> with the maximum element 4.</li>
<li><code>[3, 4, 3]</code> whose elements are <strong>not</strong> consecutive.</li>
<li><code>[4, 3, 2]</code> whose elements are <strong>not</strong> sorted.</li>
<li><code>[3, 2, 5]</code> whose elements are <strong>not</strong> consecutive.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2,2,2,2], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,3,2,3,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,3,-1,3,-1]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sliding Window
|
TypeScript
|
function resultsArray(nums: number[], k: number): number[] {
const n = nums.length;
const f: number[] = Array(n).fill(1);
for (let i = 1; i < n; ++i) {
if (nums[i] === nums[i - 1] + 1) {
f[i] = f[i - 1] + 1;
}
}
const ans: number[] = [];
for (let i = k - 1; i < n; ++i) {
ans.push(f[i] >= k ? nums[i] : -1);
}
return ans;
}
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
C++
|
class Solution {
public:
int countKConstraintSubstrings(string s, int k) {
int cnt[2]{};
int ans = 0, l = 0;
for (int r = 0; r < s.length(); ++r) {
cnt[s[r] - '0']++;
while (cnt[0] > k && cnt[1] > k) {
cnt[s[l++] - '0']--;
}
ans += r - l + 1;
}
return ans;
}
};
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
Go
|
func countKConstraintSubstrings(s string, k int) (ans int) {
cnt := [2]int{}
l := 0
for r, c := range s {
cnt[c-'0']++
for ; cnt[0] > k && cnt[1] > k; l++ {
cnt[s[l]-'0']--
}
ans += r - l + 1
}
return
}
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
Java
|
class Solution {
public int countKConstraintSubstrings(String s, int k) {
int[] cnt = new int[2];
int ans = 0, l = 0;
for (int r = 0; r < s.length(); ++r) {
++cnt[s.charAt(r) - '0'];
while (cnt[0] > k && cnt[1] > k) {
cnt[s.charAt(l++) - '0']--;
}
ans += r - l + 1;
}
return ans;
}
}
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
Python
|
class Solution:
def countKConstraintSubstrings(self, s: str, k: int) -> int:
cnt = [0, 0]
ans = l = 0
for r, x in enumerate(map(int, s)):
cnt[x] += 1
while cnt[0] > k and cnt[1] > k:
cnt[int(s[l])] -= 1
l += 1
ans += r - l + 1
return ans
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
Rust
|
impl Solution {
pub fn count_k_constraint_substrings(s: String, k: i32) -> i32 {
let mut cnt = [0; 2];
let mut l = 0;
let mut ans = 0;
let s = s.as_bytes();
for (r, &c) in s.iter().enumerate() {
cnt[(c - b'0') as usize] += 1;
while cnt[0] > k && cnt[1] > k {
cnt[(s[l] - b'0') as usize] -= 1;
l += 1;
}
ans += r - l + 1;
}
ans as i32
}
}
|
3,258 |
Count Substrings That Satisfy K-Constraint I
|
Easy
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer denoting the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s</code> that satisfy the <strong>k-constraint</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 = "10101", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings <code>"1010"</code>, <code>"10101"</code>, and <code>"0101"</code> satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1010101", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">25</span></p>
<p><strong>Explanation:</strong></p>
<p>Every substring of <code>s</code> except the substrings with a length greater than 5 satisfies the k-constraint.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "11111", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>All substrings of <code>s</code> satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50 </code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String; Sliding Window
|
TypeScript
|
function countKConstraintSubstrings(s: string, k: number): number {
const cnt: [number, number] = [0, 0];
let [ans, l] = [0, 0];
for (let r = 0; r < s.length; ++r) {
cnt[+s[r]]++;
while (cnt[0] > k && cnt[1] > k) {
cnt[+s[l++]]--;
}
ans += r - l + 1;
}
return ans;
}
|
3,259 |
Maximum Energy Boost From Two Drinks
|
Medium
|
<p>You are given two integer arrays <code>energyDrinkA</code> and <code>energyDrinkB</code> of the same length <code>n</code> by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.</p>
<p>You want to <em>maximize</em> your total energy boost by drinking one energy drink <em>per hour</em>. However, if you want to switch from consuming one energy drink to the other, you need to wait for <em>one hour</em> to cleanse your system (meaning you won't get any energy boost in that hour).</p>
<p>Return the <strong>maximum</strong> total energy boost you can gain in the next <code>n</code> hours.</p>
<p><strong>Note</strong> that you can start consuming <em>either</em> of the two energy drinks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [1,3,1], </span>energyDrinkB<span class="example-io"> = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 5, drink only the energy drink A (or only B).</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [4,1,1], </span>energyDrinkB<span class="example-io"> = [1,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 7:</p>
<ul>
<li>Drink the energy drink A for the first hour.</li>
<li>Switch to the energy drink B and we lose the energy boost of the second hour.</li>
<li>Gain the energy boost of the drink B in the third hour.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == energyDrinkA.length == energyDrinkB.length</code></li>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= energyDrinkA[i], energyDrinkB[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
long long maxEnergyBoost(vector<int>& energyDrinkA, vector<int>& energyDrinkB) {
int n = energyDrinkA.size();
vector<vector<long long>> f(n, vector<long long>(2));
f[0][0] = energyDrinkA[0];
f[0][1] = energyDrinkB[0];
for (int i = 1; i < n; ++i) {
f[i][0] = max(f[i - 1][0] + energyDrinkA[i], f[i - 1][1]);
f[i][1] = max(f[i - 1][1] + energyDrinkB[i], f[i - 1][0]);
}
return max(f[n - 1][0], f[n - 1][1]);
}
};
|
3,259 |
Maximum Energy Boost From Two Drinks
|
Medium
|
<p>You are given two integer arrays <code>energyDrinkA</code> and <code>energyDrinkB</code> of the same length <code>n</code> by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.</p>
<p>You want to <em>maximize</em> your total energy boost by drinking one energy drink <em>per hour</em>. However, if you want to switch from consuming one energy drink to the other, you need to wait for <em>one hour</em> to cleanse your system (meaning you won't get any energy boost in that hour).</p>
<p>Return the <strong>maximum</strong> total energy boost you can gain in the next <code>n</code> hours.</p>
<p><strong>Note</strong> that you can start consuming <em>either</em> of the two energy drinks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [1,3,1], </span>energyDrinkB<span class="example-io"> = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 5, drink only the energy drink A (or only B).</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [4,1,1], </span>energyDrinkB<span class="example-io"> = [1,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 7:</p>
<ul>
<li>Drink the energy drink A for the first hour.</li>
<li>Switch to the energy drink B and we lose the energy boost of the second hour.</li>
<li>Gain the energy boost of the drink B in the third hour.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == energyDrinkA.length == energyDrinkB.length</code></li>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= energyDrinkA[i], energyDrinkB[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func maxEnergyBoost(energyDrinkA []int, energyDrinkB []int) int64 {
n := len(energyDrinkA)
f := make([][2]int64, n)
f[0][0] = int64(energyDrinkA[0])
f[0][1] = int64(energyDrinkB[0])
for i := 1; i < n; i++ {
f[i][0] = max(f[i-1][0]+int64(energyDrinkA[i]), f[i-1][1])
f[i][1] = max(f[i-1][1]+int64(energyDrinkB[i]), f[i-1][0])
}
return max(f[n-1][0], f[n-1][1])
}
|
3,259 |
Maximum Energy Boost From Two Drinks
|
Medium
|
<p>You are given two integer arrays <code>energyDrinkA</code> and <code>energyDrinkB</code> of the same length <code>n</code> by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.</p>
<p>You want to <em>maximize</em> your total energy boost by drinking one energy drink <em>per hour</em>. However, if you want to switch from consuming one energy drink to the other, you need to wait for <em>one hour</em> to cleanse your system (meaning you won't get any energy boost in that hour).</p>
<p>Return the <strong>maximum</strong> total energy boost you can gain in the next <code>n</code> hours.</p>
<p><strong>Note</strong> that you can start consuming <em>either</em> of the two energy drinks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [1,3,1], </span>energyDrinkB<span class="example-io"> = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 5, drink only the energy drink A (or only B).</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [4,1,1], </span>energyDrinkB<span class="example-io"> = [1,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 7:</p>
<ul>
<li>Drink the energy drink A for the first hour.</li>
<li>Switch to the energy drink B and we lose the energy boost of the second hour.</li>
<li>Gain the energy boost of the drink B in the third hour.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == energyDrinkA.length == energyDrinkB.length</code></li>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= energyDrinkA[i], energyDrinkB[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public long maxEnergyBoost(int[] energyDrinkA, int[] energyDrinkB) {
int n = energyDrinkA.length;
long[][] f = new long[n][2];
f[0][0] = energyDrinkA[0];
f[0][1] = energyDrinkB[0];
for (int i = 1; i < n; ++i) {
f[i][0] = Math.max(f[i - 1][0] + energyDrinkA[i], f[i - 1][1]);
f[i][1] = Math.max(f[i - 1][1] + energyDrinkB[i], f[i - 1][0]);
}
return Math.max(f[n - 1][0], f[n - 1][1]);
}
}
|
3,259 |
Maximum Energy Boost From Two Drinks
|
Medium
|
<p>You are given two integer arrays <code>energyDrinkA</code> and <code>energyDrinkB</code> of the same length <code>n</code> by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.</p>
<p>You want to <em>maximize</em> your total energy boost by drinking one energy drink <em>per hour</em>. However, if you want to switch from consuming one energy drink to the other, you need to wait for <em>one hour</em> to cleanse your system (meaning you won't get any energy boost in that hour).</p>
<p>Return the <strong>maximum</strong> total energy boost you can gain in the next <code>n</code> hours.</p>
<p><strong>Note</strong> that you can start consuming <em>either</em> of the two energy drinks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [1,3,1], </span>energyDrinkB<span class="example-io"> = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 5, drink only the energy drink A (or only B).</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [4,1,1], </span>energyDrinkB<span class="example-io"> = [1,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 7:</p>
<ul>
<li>Drink the energy drink A for the first hour.</li>
<li>Switch to the energy drink B and we lose the energy boost of the second hour.</li>
<li>Gain the energy boost of the drink B in the third hour.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == energyDrinkA.length == energyDrinkB.length</code></li>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= energyDrinkA[i], energyDrinkB[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def maxEnergyBoost(self, energyDrinkA: List[int], energyDrinkB: List[int]) -> int:
n = len(energyDrinkA)
f = [[0] * 2 for _ in range(n)]
f[0][0] = energyDrinkA[0]
f[0][1] = energyDrinkB[0]
for i in range(1, n):
f[i][0] = max(f[i - 1][0] + energyDrinkA[i], f[i - 1][1])
f[i][1] = max(f[i - 1][1] + energyDrinkB[i], f[i - 1][0])
return max(f[n - 1])
|
3,259 |
Maximum Energy Boost From Two Drinks
|
Medium
|
<p>You are given two integer arrays <code>energyDrinkA</code> and <code>energyDrinkB</code> of the same length <code>n</code> by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.</p>
<p>You want to <em>maximize</em> your total energy boost by drinking one energy drink <em>per hour</em>. However, if you want to switch from consuming one energy drink to the other, you need to wait for <em>one hour</em> to cleanse your system (meaning you won't get any energy boost in that hour).</p>
<p>Return the <strong>maximum</strong> total energy boost you can gain in the next <code>n</code> hours.</p>
<p><strong>Note</strong> that you can start consuming <em>either</em> of the two energy drinks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [1,3,1], </span>energyDrinkB<span class="example-io"> = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 5, drink only the energy drink A (or only B).</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> energyDrinkA<span class="example-io"> = [4,1,1], </span>energyDrinkB<span class="example-io"> = [1,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>To gain an energy boost of 7:</p>
<ul>
<li>Drink the energy drink A for the first hour.</li>
<li>Switch to the energy drink B and we lose the energy boost of the second hour.</li>
<li>Gain the energy boost of the drink B in the third hour.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == energyDrinkA.length == energyDrinkB.length</code></li>
<li><code>3 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= energyDrinkA[i], energyDrinkB[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function maxEnergyBoost(energyDrinkA: number[], energyDrinkB: number[]): number {
const n = energyDrinkA.length;
const f: number[][] = Array.from({ length: n }, () => [0, 0]);
f[0][0] = energyDrinkA[0];
f[0][1] = energyDrinkB[0];
for (let i = 1; i < n; i++) {
f[i][0] = Math.max(f[i - 1][0] + energyDrinkA[i], f[i - 1][1]);
f[i][1] = Math.max(f[i - 1][1] + energyDrinkB[i], f[i - 1][0]);
}
return Math.max(...f[n - 1]!);
}
|
3,261 |
Count Substrings That Satisfy K-Constraint II
|
Hard
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>You are also given a 2D integer array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s[l<sub>i</sub>..r<sub>i</sub>]</code> that satisfy the <strong>k-constraint</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 = "0001111", k = 2, queries = [[0,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[26]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the query <code>[0, 6]</code>, all substrings of <code>s[0..6] = "0001111"</code> satisfy the k-constraint except for the substrings <code>s[0..5] = "000111"</code> and <code>s[0..6] = "0001111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[15,9,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings of <code>s</code> with a length greater than 3 do not satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
<li><code>1 <= k <= s.length</code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [l<sub>i</sub>, r<sub>i</sub>]</code></li>
<li><code>0 <= l<sub>i</sub> <= r<sub>i</sub> < s.length</code></li>
<li>All queries are distinct.</li>
</ul>
|
Array; String; Binary Search; Prefix Sum; Sliding Window
|
C++
|
class Solution {
public:
vector<long long> countKConstraintSubstrings(string s, int k, vector<vector<int>>& queries) {
int cnt[2]{};
int n = s.size();
vector<int> d(n, n);
long long pre[n + 1];
pre[0] = 0;
for (int i = 0, j = 0; j < n; ++j) {
cnt[s[j] - '0']++;
while (cnt[0] > k && cnt[1] > k) {
d[i] = j;
cnt[s[i++] - '0']--;
}
pre[j + 1] = pre[j] + j - i + 1;
}
vector<long long> ans;
for (const auto& q : queries) {
int l = q[0], r = q[1];
int p = min(r + 1, d[l]);
long long a = (1LL + p - l) * (p - l) / 2;
long long b = pre[r + 1] - pre[p];
ans.push_back(a + b);
}
return ans;
}
};
|
3,261 |
Count Substrings That Satisfy K-Constraint II
|
Hard
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>You are also given a 2D integer array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s[l<sub>i</sub>..r<sub>i</sub>]</code> that satisfy the <strong>k-constraint</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 = "0001111", k = 2, queries = [[0,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[26]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the query <code>[0, 6]</code>, all substrings of <code>s[0..6] = "0001111"</code> satisfy the k-constraint except for the substrings <code>s[0..5] = "000111"</code> and <code>s[0..6] = "0001111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[15,9,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings of <code>s</code> with a length greater than 3 do not satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
<li><code>1 <= k <= s.length</code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [l<sub>i</sub>, r<sub>i</sub>]</code></li>
<li><code>0 <= l<sub>i</sub> <= r<sub>i</sub> < s.length</code></li>
<li>All queries are distinct.</li>
</ul>
|
Array; String; Binary Search; Prefix Sum; Sliding Window
|
Go
|
func countKConstraintSubstrings(s string, k int, queries [][]int) (ans []int64) {
cnt := [2]int{}
n := len(s)
d := make([]int, n)
for i := range d {
d[i] = n
}
pre := make([]int, n+1)
for i, j := 0, 0; j < n; j++ {
cnt[s[j]-'0']++
for cnt[0] > k && cnt[1] > k {
d[i] = j
cnt[s[i]-'0']--
i++
}
pre[j+1] = pre[j] + j - i + 1
}
for _, q := range queries {
l, r := q[0], q[1]
p := min(r+1, d[l])
a := (1 + p - l) * (p - l) / 2
b := pre[r+1] - pre[p]
ans = append(ans, int64(a+b))
}
return
}
|
3,261 |
Count Substrings That Satisfy K-Constraint II
|
Hard
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>You are also given a 2D integer array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s[l<sub>i</sub>..r<sub>i</sub>]</code> that satisfy the <strong>k-constraint</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 = "0001111", k = 2, queries = [[0,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[26]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the query <code>[0, 6]</code>, all substrings of <code>s[0..6] = "0001111"</code> satisfy the k-constraint except for the substrings <code>s[0..5] = "000111"</code> and <code>s[0..6] = "0001111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[15,9,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings of <code>s</code> with a length greater than 3 do not satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
<li><code>1 <= k <= s.length</code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [l<sub>i</sub>, r<sub>i</sub>]</code></li>
<li><code>0 <= l<sub>i</sub> <= r<sub>i</sub> < s.length</code></li>
<li>All queries are distinct.</li>
</ul>
|
Array; String; Binary Search; Prefix Sum; Sliding Window
|
Java
|
class Solution {
public long[] countKConstraintSubstrings(String s, int k, int[][] queries) {
int[] cnt = new int[2];
int n = s.length();
int[] d = new int[n];
Arrays.fill(d, n);
long[] pre = new long[n + 1];
for (int i = 0, j = 0; j < n; ++j) {
cnt[s.charAt(j) - '0']++;
while (cnt[0] > k && cnt[1] > k) {
d[i] = j;
cnt[s.charAt(i++) - '0']--;
}
pre[j + 1] = pre[j] + j - i + 1;
}
int m = queries.length;
long[] ans = new long[m];
for (int i = 0; i < m; ++i) {
int l = queries[i][0], r = queries[i][1];
int p = Math.min(r + 1, d[l]);
long a = (1L + p - l) * (p - l) / 2;
long b = pre[r + 1] - pre[p];
ans[i] = a + b;
}
return ans;
}
}
|
3,261 |
Count Substrings That Satisfy K-Constraint II
|
Hard
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>You are also given a 2D integer array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s[l<sub>i</sub>..r<sub>i</sub>]</code> that satisfy the <strong>k-constraint</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 = "0001111", k = 2, queries = [[0,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[26]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the query <code>[0, 6]</code>, all substrings of <code>s[0..6] = "0001111"</code> satisfy the k-constraint except for the substrings <code>s[0..5] = "000111"</code> and <code>s[0..6] = "0001111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[15,9,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings of <code>s</code> with a length greater than 3 do not satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
<li><code>1 <= k <= s.length</code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [l<sub>i</sub>, r<sub>i</sub>]</code></li>
<li><code>0 <= l<sub>i</sub> <= r<sub>i</sub> < s.length</code></li>
<li>All queries are distinct.</li>
</ul>
|
Array; String; Binary Search; Prefix Sum; Sliding Window
|
Python
|
class Solution:
def countKConstraintSubstrings(
self, s: str, k: int, queries: List[List[int]]
) -> List[int]:
cnt = [0, 0]
i, n = 0, len(s)
d = [n] * n
pre = [0] * (n + 1)
for j, x in enumerate(map(int, s)):
cnt[x] += 1
while cnt[0] > k and cnt[1] > k:
d[i] = j
cnt[int(s[i])] -= 1
i += 1
pre[j + 1] = pre[j] + j - i + 1
ans = []
for l, r in queries:
p = min(r + 1, d[l])
a = (1 + p - l) * (p - l) // 2
b = pre[r + 1] - pre[p]
ans.append(a + b)
return ans
|
3,261 |
Count Substrings That Satisfy K-Constraint II
|
Hard
|
<p>You are given a <strong>binary</strong> string <code>s</code> and an integer <code>k</code>.</p>
<p>You are also given a 2D integer array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p>
<p>A <strong>binary string</strong> satisfies the <strong>k-constraint</strong> if <strong>either</strong> of the following conditions holds:</p>
<ul>
<li>The number of <code>0</code>'s in the string is at most <code>k</code>.</li>
<li>The number of <code>1</code>'s in the string is at most <code>k</code>.</li>
</ul>
<p>Return an integer array <code>answer</code>, where <code>answer[i]</code> is the number of <span data-keyword="substring-nonempty">substrings</span> of <code>s[l<sub>i</sub>..r<sub>i</sub>]</code> that satisfy the <strong>k-constraint</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 = "0001111", k = 2, queries = [[0,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[26]</span></p>
<p><strong>Explanation:</strong></p>
<p>For the query <code>[0, 6]</code>, all substrings of <code>s[0..6] = "0001111"</code> satisfy the k-constraint except for the substrings <code>s[0..5] = "000111"</code> and <code>s[0..6] = "0001111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[15,9,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings of <code>s</code> with a length greater than 3 do not satisfy the k-constraint.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
<li><code>1 <= k <= s.length</code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [l<sub>i</sub>, r<sub>i</sub>]</code></li>
<li><code>0 <= l<sub>i</sub> <= r<sub>i</sub> < s.length</code></li>
<li>All queries are distinct.</li>
</ul>
|
Array; String; Binary Search; Prefix Sum; Sliding Window
|
TypeScript
|
function countKConstraintSubstrings(s: string, k: number, queries: number[][]): number[] {
const cnt: [number, number] = [0, 0];
const n = s.length;
const d: number[] = Array(n).fill(n);
const pre: number[] = Array(n + 1).fill(0);
for (let i = 0, j = 0; j < n; ++j) {
cnt[+s[j]]++;
while (Math.min(cnt[0], cnt[1]) > k) {
d[i] = j;
cnt[+s[i++]]--;
}
pre[j + 1] = pre[j] + j - i + 1;
}
const ans: number[] = [];
for (const [l, r] of queries) {
const p = Math.min(r + 1, d[l]);
const a = ((1 + p - l) * (p - l)) / 2;
const b = pre[r + 1] - pre[p];
ans.push(a + b);
}
return ans;
}
|
3,262 |
Find Overlapping Shifts
|
Medium
|
<p>Table: <code>EmployeeShifts</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| start_time | time |
| end_time | time |
+------------------+---------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start and end times on a specific date.
</pre>
<p>Write a solution to count the number of <strong>overlapping shifts</strong> for each employee. Two shifts are considered overlapping if one shift’s <code>end_time</code> is <strong>later than</strong> another shift’s <code>start_time</code>.</p>
<p><em>Return the result table ordered by</em> <code>employee_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The query 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><code>EmployeeShifts</code> table:</p>
<pre class="example-io">
+-------------+------------+----------+
| employee_id | start_time | end_time |
+-------------+------------+----------+
| 1 | 08:00:00 | 12:00:00 |
| 1 | 11:00:00 | 15:00:00 |
| 1 | 14:00:00 | 18:00:00 |
| 2 | 09:00:00 | 17:00:00 |
| 2 | 16:00:00 | 20:00:00 |
| 3 | 10:00:00 | 12:00:00 |
| 3 | 13:00:00 | 15:00:00 |
| 3 | 16:00:00 | 18:00:00 |
| 4 | 08:00:00 | 10:00:00 |
| 4 | 09:00:00 | 11:00:00 |
+-------------+------------+----------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------+--------------------+
| employee_id | overlapping_shifts |
+-------------+--------------------+
| 1 | 2 |
| 2 | 1 |
| 4 | 1 |
+-------------+--------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Employee 1 has 3 shifts:
<ul>
<li>08:00:00 to 12:00:00</li>
<li>11:00:00 to 15:00:00</li>
<li>14:00:00 to 18:00:00</li>
</ul>
The first shift overlaps with the second, and the second overlaps with the third, resulting in 2 overlapping shifts.</li>
<li>Employee 2 has 2 shifts:
<ul>
<li>09:00:00 to 17:00:00</li>
<li>16:00:00 to 20:00:00</li>
</ul>
These shifts overlap with each other, resulting in 1 overlapping shift.</li>
<li>Employee 3 has 3 shifts:
<ul>
<li>10:00:00 to 12:00:00</li>
<li>13:00:00 to 15:00:00</li>
<li>16:00:00 to 18:00:00</li>
</ul>
None of these shifts overlap, so Employee 3 is not included in the output.</li>
<li>Employee 4 has 2 shifts:
<ul>
<li>08:00:00 to 10:00:00</li>
<li>09:00:00 to 11:00:00</li>
</ul>
These shifts overlap with each other, resulting in 1 overlapping shift.</li>
</ul>
<p>The output shows the employee_id and the count of overlapping shifts for each employee who has at least one overlapping shift, ordered by employee_id in ascending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_overlapping_shifts(employee_shifts: pd.DataFrame) -> pd.DataFrame:
merged_shifts = employee_shifts.merge(
employee_shifts, on="employee_id", suffixes=("_t1", "_t2")
)
overlapping_shifts = merged_shifts[
(merged_shifts["start_time_t1"] < merged_shifts["start_time_t2"])
& (merged_shifts["end_time_t1"] > merged_shifts["start_time_t2"])
]
result = (
overlapping_shifts.groupby("employee_id")
.size()
.reset_index(name="overlapping_shifts")
)
result = result[result["overlapping_shifts"] > 0]
result = result.sort_values("employee_id").reset_index(drop=True)
return result
|
3,262 |
Find Overlapping Shifts
|
Medium
|
<p>Table: <code>EmployeeShifts</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| start_time | time |
| end_time | time |
+------------------+---------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start and end times on a specific date.
</pre>
<p>Write a solution to count the number of <strong>overlapping shifts</strong> for each employee. Two shifts are considered overlapping if one shift’s <code>end_time</code> is <strong>later than</strong> another shift’s <code>start_time</code>.</p>
<p><em>Return the result table ordered by</em> <code>employee_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The query 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><code>EmployeeShifts</code> table:</p>
<pre class="example-io">
+-------------+------------+----------+
| employee_id | start_time | end_time |
+-------------+------------+----------+
| 1 | 08:00:00 | 12:00:00 |
| 1 | 11:00:00 | 15:00:00 |
| 1 | 14:00:00 | 18:00:00 |
| 2 | 09:00:00 | 17:00:00 |
| 2 | 16:00:00 | 20:00:00 |
| 3 | 10:00:00 | 12:00:00 |
| 3 | 13:00:00 | 15:00:00 |
| 3 | 16:00:00 | 18:00:00 |
| 4 | 08:00:00 | 10:00:00 |
| 4 | 09:00:00 | 11:00:00 |
+-------------+------------+----------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------+--------------------+
| employee_id | overlapping_shifts |
+-------------+--------------------+
| 1 | 2 |
| 2 | 1 |
| 4 | 1 |
+-------------+--------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Employee 1 has 3 shifts:
<ul>
<li>08:00:00 to 12:00:00</li>
<li>11:00:00 to 15:00:00</li>
<li>14:00:00 to 18:00:00</li>
</ul>
The first shift overlaps with the second, and the second overlaps with the third, resulting in 2 overlapping shifts.</li>
<li>Employee 2 has 2 shifts:
<ul>
<li>09:00:00 to 17:00:00</li>
<li>16:00:00 to 20:00:00</li>
</ul>
These shifts overlap with each other, resulting in 1 overlapping shift.</li>
<li>Employee 3 has 3 shifts:
<ul>
<li>10:00:00 to 12:00:00</li>
<li>13:00:00 to 15:00:00</li>
<li>16:00:00 to 18:00:00</li>
</ul>
None of these shifts overlap, so Employee 3 is not included in the output.</li>
<li>Employee 4 has 2 shifts:
<ul>
<li>08:00:00 to 10:00:00</li>
<li>09:00:00 to 11:00:00</li>
</ul>
These shifts overlap with each other, resulting in 1 overlapping shift.</li>
</ul>
<p>The output shows the employee_id and the count of overlapping shifts for each employee who has at least one overlapping shift, ordered by employee_id in ascending order.</p>
</div>
|
Database
|
SQL
|
SELECT
t1.employee_id,
COUNT(*) AS overlapping_shifts
FROM
EmployeeShifts t1
JOIN EmployeeShifts t2
ON t1.employee_id = t2.employee_id
AND t1.start_time < t2.start_time
AND t1.end_time > t2.start_time
GROUP BY 1
HAVING overlapping_shifts > 0
ORDER BY 1;
|
3,263 |
Convert Doubly Linked List to Array I
|
Easy
|
<p>You are given the <code>head</code> of a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p>
<p>Return an integer array which contains the elements of the linked list <strong>in order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4,3,2,1]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [2,2,2,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2,2,2]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [3,2,3,2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2,3,2,3,2]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the given list is in the range <code>[1, 50]</code>.</li>
<li><code>1 <= Node.val <= 50</code></li>
</ul>
|
Array; Linked List; Doubly-Linked List
|
C++
|
/**
* Definition for doubly-linked list.
* class Node {
* int val;
* Node* prev;
* Node* next;
* Node() : val(0), next(nullptr), prev(nullptr) {}
* Node(int x) : val(x), next(nullptr), prev(nullptr) {}
* Node(int x, Node *prev, Node *next) : val(x), next(next), prev(prev) {}
* };
*/
class Solution {
public:
vector<int> toArray(Node* head) {
vector<int> ans;
for (; head; head = head->next) {
ans.push_back(head->val);
}
return ans;
}
};
|
3,263 |
Convert Doubly Linked List to Array I
|
Easy
|
<p>You are given the <code>head</code> of a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p>
<p>Return an integer array which contains the elements of the linked list <strong>in order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4,3,2,1]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [2,2,2,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2,2,2]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [3,2,3,2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2,3,2,3,2]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the given list is in the range <code>[1, 50]</code>.</li>
<li><code>1 <= Node.val <= 50</code></li>
</ul>
|
Array; Linked List; Doubly-Linked List
|
Go
|
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Prev *Node
* }
*/
func toArray(head *Node) (ans []int) {
for ; head != nil; head = head.Next {
ans = append(ans, head.Val)
}
return
}
|
3,263 |
Convert Doubly Linked List to Array I
|
Easy
|
<p>You are given the <code>head</code> of a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p>
<p>Return an integer array which contains the elements of the linked list <strong>in order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4,3,2,1]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [2,2,2,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2,2,2]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [3,2,3,2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2,3,2,3,2]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the given list is in the range <code>[1, 50]</code>.</li>
<li><code>1 <= Node.val <= 50</code></li>
</ul>
|
Array; Linked List; Doubly-Linked List
|
Java
|
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
};
*/
class Solution {
public int[] toArray(Node head) {
List<Integer> ans = new ArrayList<>();
for (; head != null; head = head.next) {
ans.add(head.val);
}
return ans.stream().mapToInt(i -> i).toArray();
}
}
|
3,263 |
Convert Doubly Linked List to Array I
|
Easy
|
<p>You are given the <code>head</code> of a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p>
<p>Return an integer array which contains the elements of the linked list <strong>in order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4,3,2,1]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [2,2,2,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2,2,2]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [3,2,3,2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2,3,2,3,2]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the given list is in the range <code>[1, 50]</code>.</li>
<li><code>1 <= Node.val <= 50</code></li>
</ul>
|
Array; Linked List; Doubly-Linked List
|
Python
|
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
"""
class Solution:
def toArray(self, root: "Optional[Node]") -> List[int]:
ans = []
while root:
ans.append(root.val)
root = root.next
return ans
|
3,263 |
Convert Doubly Linked List to Array I
|
Easy
|
<p>You are given the <code>head</code> of a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p>
<p>Return an integer array which contains the elements of the linked list <strong>in order</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [1,2,3,4,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4,3,2,1]</span></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [2,2,2,2,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2,2,2]</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">head = [3,2,3,2,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,2,3,2,3,2]</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the given list is in the range <code>[1, 50]</code>.</li>
<li><code>1 <= Node.val <= 50</code></li>
</ul>
|
Array; Linked List; Doubly-Linked List
|
TypeScript
|
/**
* Definition for _Node.
* class _Node {
* val: number
* prev: _Node | null
* next: _Node | null
*
* constructor(val?: number, prev? : _Node, next? : _Node) {
* this.val = (val===undefined ? 0 : val);
* this.prev = (prev===undefined ? null : prev);
* this.next = (next===undefined ? null : next);
* }
* }
*/
function toArray(head: _Node | null): number[] {
const ans: number[] = [];
for (; head; head = head.next) {
ans.push(head.val);
}
return ans;
}
|
3,264 |
Final Array State After K Multiplication Operations I
|
Easy
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 3, multiplier = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[16,8]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[4, 2]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 8]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[16, 8]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 10</code></li>
<li><code>1 <= multiplier <= 5</code></li>
</ul>
|
Array; Math; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
auto cmp = [&nums](int i, int j) {
return nums[i] == nums[j] ? i > j : nums[i] > nums[j];
};
priority_queue<int, vector<int>, decltype(cmp)> pq(cmp);
for (int i = 0; i < nums.size(); ++i) {
pq.push(i);
}
while (k--) {
int i = pq.top();
pq.pop();
nums[i] *= multiplier;
pq.push(i);
}
return nums;
}
};
|
3,264 |
Final Array State After K Multiplication Operations I
|
Easy
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 3, multiplier = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[16,8]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[4, 2]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 8]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[16, 8]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 10</code></li>
<li><code>1 <= multiplier <= 5</code></li>
</ul>
|
Array; Math; Simulation; Heap (Priority Queue)
|
Go
|
func getFinalState(nums []int, k int, multiplier int) []int {
h := &hp{nums: nums}
for i := range nums {
heap.Push(h, i)
}
for k > 0 {
i := heap.Pop(h).(int)
nums[i] *= multiplier
heap.Push(h, i)
k--
}
return nums
}
type hp struct {
sort.IntSlice
nums []int
}
func (h *hp) Less(i, j int) bool {
if h.nums[h.IntSlice[i]] == h.nums[h.IntSlice[j]] {
return h.IntSlice[i] < h.IntSlice[j]
}
return h.nums[h.IntSlice[i]] < h.nums[h.IntSlice[j]]
}
func (h *hp) Pop() any {
old := h.IntSlice
n := len(old)
x := old[n-1]
h.IntSlice = old[:n-1]
return x
}
func (h *hp) Push(x any) {
h.IntSlice = append(h.IntSlice, x.(int))
}
|
3,264 |
Final Array State After K Multiplication Operations I
|
Easy
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 3, multiplier = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[16,8]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[4, 2]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 8]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[16, 8]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 10</code></li>
<li><code>1 <= multiplier <= 5</code></li>
</ul>
|
Array; Math; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
PriorityQueue<Integer> pq
= new PriorityQueue<>((i, j) -> nums[i] - nums[j] == 0 ? i - j : nums[i] - nums[j]);
for (int i = 0; i < nums.length; i++) {
pq.offer(i);
}
while (k-- > 0) {
int i = pq.poll();
nums[i] *= multiplier;
pq.offer(i);
}
return nums;
}
}
|
3,264 |
Final Array State After K Multiplication Operations I
|
Easy
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 3, multiplier = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[16,8]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[4, 2]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 8]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[16, 8]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 10</code></li>
<li><code>1 <= multiplier <= 5</code></li>
</ul>
|
Array; Math; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
pq = [(x, i) for i, x in enumerate(nums)]
heapify(pq)
for _ in range(k):
_, i = heappop(pq)
nums[i] *= multiplier
heappush(pq, (nums[i], i))
return nums
|
3,264 |
Final Array State After K Multiplication Operations I
|
Easy
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 3, multiplier = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">[16,8]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[4, 2]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 8]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[16, 8]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 10</code></li>
<li><code>1 <= multiplier <= 5</code></li>
</ul>
|
Array; Math; Simulation; Heap (Priority Queue)
|
TypeScript
|
function getFinalState(nums: number[], k: number, multiplier: number): number[] {
const pq = new PriorityQueue({
compare: (i, j) => (nums[i] === nums[j] ? i - j : nums[i] - nums[j]),
});
for (let i = 0; i < nums.length; ++i) {
pq.enqueue(i);
}
while (k--) {
const i = pq.dequeue()!;
nums[i] *= multiplier;
pq.enqueue(i);
}
return nums;
}
|
3,265 |
Count Almost Equal Pairs I
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> in this problem <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most once</strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,12,30,17,21]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>3 and 30. By swapping 3 and 0 in 30, you get 3.</li>
<li>12 and 21. By swapping 1 and 2 in 12, you get 21.</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,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every two elements in the array are almost equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [123,231]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot swap any two digits of 123 or 231 to reach the other.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
C++
|
class Solution {
public:
int countPairs(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
unordered_map<int, int> cnt;
for (int x : nums) {
unordered_set<int> vis = {x};
string s = to_string(x);
for (int j = 0; j < s.length(); ++j) {
for (int i = 0; i < j; ++i) {
swap(s[i], s[j]);
vis.insert(stoi(s));
swap(s[i], s[j]);
}
}
for (int y : vis) {
ans += cnt[y];
}
cnt[x]++;
}
return ans;
}
};
|
3,265 |
Count Almost Equal Pairs I
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> in this problem <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most once</strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,12,30,17,21]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>3 and 30. By swapping 3 and 0 in 30, you get 3.</li>
<li>12 and 21. By swapping 1 and 2 in 12, you get 21.</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,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every two elements in the array are almost equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [123,231]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot swap any two digits of 123 or 231 to reach the other.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Go
|
func countPairs(nums []int) (ans int) {
sort.Ints(nums)
cnt := make(map[int]int)
for _, x := range nums {
vis := make(map[int]struct{})
vis[x] = struct{}{}
s := []rune(strconv.Itoa(x))
for j := 0; j < len(s); j++ {
for i := 0; i < j; i++ {
s[i], s[j] = s[j], s[i]
y, _ := strconv.Atoi(string(s))
vis[y] = struct{}{}
s[i], s[j] = s[j], s[i]
}
}
for y := range vis {
ans += cnt[y]
}
cnt[x]++
}
return
}
|
3,265 |
Count Almost Equal Pairs I
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> in this problem <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most once</strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,12,30,17,21]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>3 and 30. By swapping 3 and 0 in 30, you get 3.</li>
<li>12 and 21. By swapping 1 and 2 in 12, you get 21.</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,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every two elements in the array are almost equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [123,231]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot swap any two digits of 123 or 231 to reach the other.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Java
|
class Solution {
public int countPairs(int[] nums) {
Arrays.sort(nums);
int ans = 0;
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
Set<Integer> vis = new HashSet<>();
vis.add(x);
char[] s = String.valueOf(x).toCharArray();
for (int j = 0; j < s.length; ++j) {
for (int i = 0; i < j; ++i) {
swap(s, i, j);
vis.add(Integer.parseInt(String.valueOf(s)));
swap(s, i, j);
}
}
for (int y : vis) {
ans += cnt.getOrDefault(y, 0);
}
cnt.merge(x, 1, Integer::sum);
}
return ans;
}
private void swap(char[] s, int i, int j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
|
3,265 |
Count Almost Equal Pairs I
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> in this problem <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most once</strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,12,30,17,21]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>3 and 30. By swapping 3 and 0 in 30, you get 3.</li>
<li>12 and 21. By swapping 1 and 2 in 12, you get 21.</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,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every two elements in the array are almost equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [123,231]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot swap any two digits of 123 or 231 to reach the other.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Python
|
class Solution:
def countPairs(self, nums: List[int]) -> int:
nums.sort()
ans = 0
cnt = defaultdict(int)
for x in nums:
vis = {x}
s = list(str(x))
for j in range(len(s)):
for i in range(j):
s[i], s[j] = s[j], s[i]
vis.add(int("".join(s)))
s[i], s[j] = s[j], s[i]
ans += sum(cnt[x] for x in vis)
cnt[x] += 1
return ans
|
3,265 |
Count Almost Equal Pairs I
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> in this problem <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most once</strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,12,30,17,21]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>3 and 30. By swapping 3 and 0 in 30, you get 3.</li>
<li>12 and 21. By swapping 1 and 2 in 12, you get 21.</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,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every two elements in the array are almost equal.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [123,231]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot swap any two digits of 123 or 231 to reach the other.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
TypeScript
|
function countPairs(nums: number[]): number {
nums.sort((a, b) => a - b);
let ans = 0;
const cnt = new Map<number, number>();
for (const x of nums) {
const vis = new Set<number>();
vis.add(x);
const s = x.toString().split('');
for (let j = 0; j < s.length; j++) {
for (let i = 0; i < j; i++) {
[s[i], s[j]] = [s[j], s[i]];
vis.add(+s.join(''));
[s[i], s[j]] = [s[j], s[i]];
}
}
for (const y of vis) {
ans += cnt.get(y) || 0;
}
cnt.set(x, (cnt.get(x) || 0) + 1);
}
return ans;
}
|
3,266 |
Final Array State After K Multiplication Operations II
|
Hard
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>After the <code>k</code> operations, apply <strong>modulo</strong> <code>10<sup>9</sup> + 7</code> to every value in <code>nums</code>.</p>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations and then applying the modulo.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [100000,2000], k = 2, multiplier = 1000000</span></p>
<p><strong>Output:</strong> <span class="example-io">[999999307,999999993]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[100000, 2000000000]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[100000000000, 2000000000]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[999999307, 999999993]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= multiplier <= 10<sup>6</sup></code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
if (multiplier == 1) {
return nums;
}
using ll = long long;
using pli = pair<ll, int>;
auto cmp = [](const pli& a, const pli& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first > b.first;
};
priority_queue<pli, vector<pli>, decltype(cmp)> pq(cmp);
int n = nums.size();
int m = *max_element(nums.begin(), nums.end());
for (int i = 0; i < n; ++i) {
pq.emplace(nums[i], i);
}
while (k > 0 && pq.top().first < m) {
auto p = pq.top();
pq.pop();
p.first *= multiplier;
pq.emplace(p);
--k;
}
auto qpow = [&](ll a, ll n, ll mod) {
ll ans = 1 % mod;
a = a % mod;
while (n > 0) {
if (n & 1) {
ans = ans * a % mod;
}
a = a * a % mod;
n >>= 1;
}
return ans;
};
const int mod = 1e9 + 7;
for (int i = 0; i < n; ++i) {
auto p = pq.top();
pq.pop();
long long x = p.first;
int j = p.second;
nums[j] = static_cast<int>((x % mod) * qpow(multiplier, k / n + (i < k % n ? 1 : 0), mod) % mod);
}
return nums;
}
};
|
3,266 |
Final Array State After K Multiplication Operations II
|
Hard
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>After the <code>k</code> operations, apply <strong>modulo</strong> <code>10<sup>9</sup> + 7</code> to every value in <code>nums</code>.</p>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations and then applying the modulo.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [100000,2000], k = 2, multiplier = 1000000</span></p>
<p><strong>Output:</strong> <span class="example-io">[999999307,999999993]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[100000, 2000000000]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[100000000000, 2000000000]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[999999307, 999999993]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= multiplier <= 10<sup>6</sup></code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Go
|
func getFinalState(nums []int, k int, multiplier int) []int {
if multiplier == 1 {
return nums
}
n := len(nums)
pq := make(hp, n)
for i, x := range nums {
pq[i] = pair{x, i}
}
heap.Init(&pq)
m := slices.Max(nums)
for ; k > 0 && pq[0].x < m; k-- {
x := pq[0]
heap.Pop(&pq)
x.x *= multiplier
heap.Push(&pq, x)
}
const mod int = 1e9 + 7
for i := range nums {
p := heap.Pop(&pq).(pair)
x, j := p.x, p.i
power := k / n
if i < k%n {
power++
}
nums[j] = (x % mod) * qpow(multiplier, power, mod) % mod
}
return nums
}
func qpow(a, n, mod int) int {
ans := 1 % mod
a = a % mod
for n > 0 {
if n&1 == 1 {
ans = (ans * a) % mod
}
a = (a * a) % mod
n >>= 1
}
return int(ans)
}
type pair struct{ x, i int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].x < h[j].x || h[i].x == h[j].x && h[i].i < h[j].i }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(x any) { *h = append(*h, x.(pair)) }
func (h *hp) Pop() (x any) { a := *h; x = a[len(a)-1]; *h = a[:len(a)-1]; return x }
|
3,266 |
Final Array State After K Multiplication Operations II
|
Hard
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>After the <code>k</code> operations, apply <strong>modulo</strong> <code>10<sup>9</sup> + 7</code> to every value in <code>nums</code>.</p>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations and then applying the modulo.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [100000,2000], k = 2, multiplier = 1000000</span></p>
<p><strong>Output:</strong> <span class="example-io">[999999307,999999993]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[100000, 2000000000]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[100000000000, 2000000000]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[999999307, 999999993]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= multiplier <= 10<sup>6</sup></code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public int[] getFinalState(int[] nums, int k, int multiplier) {
if (multiplier == 1) {
return nums;
}
PriorityQueue<long[]> pq = new PriorityQueue<>(
(a, b) -> a[0] == b[0] ? Long.compare(a[1], b[1]) : Long.compare(a[0], b[0]));
int n = nums.length;
int m = Arrays.stream(nums).max().getAsInt();
for (int i = 0; i < n; ++i) {
pq.offer(new long[] {nums[i], i});
}
for (; k > 0 && pq.peek()[0] < m; --k) {
long[] p = pq.poll();
p[0] *= multiplier;
pq.offer(p);
}
final int mod = (int) 1e9 + 7;
for (int i = 0; i < n; ++i) {
long[] p = pq.poll();
long x = p[0];
int j = (int) p[1];
nums[j] = (int) ((x % mod) * qpow(multiplier, k / n + (i < k % n ? 1 : 0), mod) % mod);
}
return nums;
}
private int qpow(long a, long n, long mod) {
long ans = 1 % mod;
for (; n > 0; n >>= 1) {
if ((n & 1) == 1) {
ans = ans * a % mod;
}
a = a * a % mod;
}
return (int) ans;
}
}
|
3,266 |
Final Array State After K Multiplication Operations II
|
Hard
|
<p>You are given an integer array <code>nums</code>, an integer <code>k</code>, and an integer <code>multiplier</code>.</p>
<p>You need to perform <code>k</code> operations on <code>nums</code>. In each operation:</p>
<ul>
<li>Find the <strong>minimum</strong> value <code>x</code> in <code>nums</code>. If there are multiple occurrences of the minimum value, select the one that appears <strong>first</strong>.</li>
<li>Replace the selected minimum value <code>x</code> with <code>x * multiplier</code>.</li>
</ul>
<p>After the <code>k</code> operations, apply <strong>modulo</strong> <code>10<sup>9</sup> + 7</code> to every value in <code>nums</code>.</p>
<p>Return an integer array denoting the <em>final state</em> of <code>nums</code> after performing all <code>k</code> operations and then applying the modulo.</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,5,6], k = 5, multiplier = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,4,6,5,6]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[2, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[4, 2, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 3</td>
<td>[4, 4, 3, 5, 6]</td>
</tr>
<tr>
<td>After operation 4</td>
<td>[4, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After operation 5</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[8, 4, 6, 5, 6]</td>
</tr>
</tbody>
</table>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [100000,2000], k = 2, multiplier = 1000000</span></p>
<p><strong>Output:</strong> <span class="example-io">[999999307,999999993]</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Operation</th>
<th>Result</th>
</tr>
<tr>
<td>After operation 1</td>
<td>[100000, 2000000000]</td>
</tr>
<tr>
<td>After operation 2</td>
<td>[100000000000, 2000000000]</td>
</tr>
<tr>
<td>After applying modulo</td>
<td>[999999307, 999999993]</td>
</tr>
</tbody>
</table>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>1 <= multiplier <= 10<sup>6</sup></code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
if multiplier == 1:
return nums
pq = [(x, i) for i, x in enumerate(nums)]
heapify(pq)
m = max(nums)
while k and pq[0][0] < m:
x, i = heappop(pq)
heappush(pq, (x * multiplier, i))
k -= 1
n = len(nums)
mod = 10**9 + 7
pq.sort()
for i, (x, j) in enumerate(pq):
nums[j] = x * pow(multiplier, k // n + int(i < k % n), mod) % mod
return nums
|
3,267 |
Count Almost Equal Pairs II
|
Hard
|
<p><strong>Attention</strong>: In this version, the number of operations that can be performed, has been increased to <strong>twice</strong>.<!-- notionvc: 278e7cb2-3b05-42fa-8ae9-65f5fd6f7585 --></p>
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most <u>twice</u></strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1023,2310,2130,213]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.</li>
<li>1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.</li>
<li>2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.</li>
<li>2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.</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,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.</li>
<li>1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.</li>
<li>10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 5000</code></li>
<li><code>1 <= nums[i] < 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
C++
|
class Solution {
public:
int countPairs(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
unordered_map<int, int> cnt;
for (int x : nums) {
unordered_set<int> vis = {x};
string s = to_string(x);
for (int j = 0; j < s.length(); ++j) {
for (int i = 0; i < j; ++i) {
swap(s[i], s[j]);
vis.insert(stoi(s));
for (int q = i + 1; q < s.length(); ++q) {
for (int p = i + 1; p < q; ++p) {
swap(s[p], s[q]);
vis.insert(stoi(s));
swap(s[p], s[q]);
}
}
swap(s[i], s[j]);
}
}
for (int y : vis) {
ans += cnt[y];
}
cnt[x]++;
}
return ans;
}
};
|
3,267 |
Count Almost Equal Pairs II
|
Hard
|
<p><strong>Attention</strong>: In this version, the number of operations that can be performed, has been increased to <strong>twice</strong>.<!-- notionvc: 278e7cb2-3b05-42fa-8ae9-65f5fd6f7585 --></p>
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most <u>twice</u></strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1023,2310,2130,213]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.</li>
<li>1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.</li>
<li>2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.</li>
<li>2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.</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,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.</li>
<li>1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.</li>
<li>10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 5000</code></li>
<li><code>1 <= nums[i] < 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Go
|
func countPairs(nums []int) (ans int) {
sort.Ints(nums)
cnt := make(map[int]int)
for _, x := range nums {
vis := make(map[int]struct{})
vis[x] = struct{}{}
s := []rune(strconv.Itoa(x))
for j := 0; j < len(s); j++ {
for i := 0; i < j; i++ {
s[i], s[j] = s[j], s[i]
y, _ := strconv.Atoi(string(s))
vis[y] = struct{}{}
for q := i + 1; q < len(s); q++ {
for p := i + 1; p < q; p++ {
s[p], s[q] = s[q], s[p]
z, _ := strconv.Atoi(string(s))
vis[z] = struct{}{}
s[p], s[q] = s[q], s[p]
}
}
s[i], s[j] = s[j], s[i]
}
}
for y := range vis {
ans += cnt[y]
}
cnt[x]++
}
return
}
|
3,267 |
Count Almost Equal Pairs II
|
Hard
|
<p><strong>Attention</strong>: In this version, the number of operations that can be performed, has been increased to <strong>twice</strong>.<!-- notionvc: 278e7cb2-3b05-42fa-8ae9-65f5fd6f7585 --></p>
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most <u>twice</u></strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1023,2310,2130,213]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.</li>
<li>1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.</li>
<li>2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.</li>
<li>2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.</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,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.</li>
<li>1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.</li>
<li>10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 5000</code></li>
<li><code>1 <= nums[i] < 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Java
|
class Solution {
public int countPairs(int[] nums) {
Arrays.sort(nums);
int ans = 0;
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
Set<Integer> vis = new HashSet<>();
vis.add(x);
char[] s = String.valueOf(x).toCharArray();
for (int j = 0; j < s.length; ++j) {
for (int i = 0; i < j; ++i) {
swap(s, i, j);
vis.add(Integer.parseInt(String.valueOf(s)));
for (int q = i; q < s.length; ++q) {
for (int p = i; p < q; ++p) {
swap(s, p, q);
vis.add(Integer.parseInt(String.valueOf(s)));
swap(s, p, q);
}
}
swap(s, i, j);
}
}
for (int y : vis) {
ans += cnt.getOrDefault(y, 0);
}
cnt.merge(x, 1, Integer::sum);
}
return ans;
}
private void swap(char[] s, int i, int j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
|
3,267 |
Count Almost Equal Pairs II
|
Hard
|
<p><strong>Attention</strong>: In this version, the number of operations that can be performed, has been increased to <strong>twice</strong>.<!-- notionvc: 278e7cb2-3b05-42fa-8ae9-65f5fd6f7585 --></p>
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most <u>twice</u></strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1023,2310,2130,213]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.</li>
<li>1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.</li>
<li>2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.</li>
<li>2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.</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,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.</li>
<li>1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.</li>
<li>10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 5000</code></li>
<li><code>1 <= nums[i] < 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
Python
|
class Solution:
def countPairs(self, nums: List[int]) -> int:
nums.sort()
ans = 0
cnt = defaultdict(int)
for x in nums:
vis = {x}
s = list(str(x))
m = len(s)
for j in range(m):
for i in range(j):
s[i], s[j] = s[j], s[i]
vis.add(int("".join(s)))
for q in range(i + 1, m):
for p in range(i + 1, q):
s[p], s[q] = s[q], s[p]
vis.add(int("".join(s)))
s[p], s[q] = s[q], s[p]
s[i], s[j] = s[j], s[i]
ans += sum(cnt[x] for x in vis)
cnt[x] += 1
return ans
|
3,267 |
Count Almost Equal Pairs II
|
Hard
|
<p><strong>Attention</strong>: In this version, the number of operations that can be performed, has been increased to <strong>twice</strong>.<!-- notionvc: 278e7cb2-3b05-42fa-8ae9-65f5fd6f7585 --></p>
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>We call two integers <code>x</code> and <code>y</code> <strong>almost equal</strong> if both integers can become equal after performing the following operation <strong>at most <u>twice</u></strong>:</p>
<ul>
<li>Choose <strong>either</strong> <code>x</code> or <code>y</code> and swap any two digits within the chosen number.</li>
</ul>
<p>Return the number of indices <code>i</code> and <code>j</code> in <code>nums</code> where <code>i < j</code> such that <code>nums[i]</code> and <code>nums[j]</code> are <strong>almost equal</strong>.</p>
<p><strong>Note</strong> that it is allowed for an integer to have leading zeros after performing an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1023,2310,2130,213]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1023 and 2310. By swapping the digits 1 and 2, and then the digits 0 and 3 in 1023, you get 2310.</li>
<li>1023 and 213. By swapping the digits 1 and 0, and then the digits 1 and 2 in 1023, you get 0213, which is 213.</li>
<li>2310 and 213. By swapping the digits 2 and 0, and then the digits 3 and 2 in 2310, you get 0213, which is 213.</li>
<li>2310 and 2130. By swapping the digits 3 and 1 in 2310, you get 2130.</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,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The almost equal pairs of elements are:</p>
<ul>
<li>1 and 10. By swapping the digits 1 and 0 in 10, you get 01 which is 1.</li>
<li>1 and 100. By swapping the second 0 with the digit 1 in 100, you get 001, which is 1.</li>
<li>10 and 100. By swapping the first 0 with the digit 1 in 100, you get 010, which is 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 5000</code></li>
<li><code>1 <= nums[i] < 10<sup>7</sup></code></li>
</ul>
|
Array; Hash Table; Counting; Enumeration; Sorting
|
TypeScript
|
function countPairs(nums: number[]): number {
nums.sort((a, b) => a - b);
let ans = 0;
const cnt = new Map<number, number>();
for (const x of nums) {
const vis = new Set<number>();
vis.add(x);
const s = x.toString().split('');
for (let j = 0; j < s.length; j++) {
for (let i = 0; i < j; i++) {
[s[i], s[j]] = [s[j], s[i]];
vis.add(+s.join(''));
for (let q = i + 1; q < s.length; ++q) {
for (let p = i + 1; p < q; ++p) {
[s[p], s[q]] = [s[q], s[p]];
vis.add(+s.join(''));
[s[p], s[q]] = [s[q], s[p]];
}
}
[s[i], s[j]] = [s[j], s[i]];
}
}
for (const y of vis) {
ans += cnt.get(y) || 0;
}
cnt.set(x, (cnt.get(x) || 0) + 1);
}
return ans;
}
|
3,268 |
Find Overlapping Shifts II
|
Hard
|
<p>Table: <code>EmployeeShifts</code></p>
<pre>
+------------------+----------+
| Column Name | Type |
+------------------+----------+
| employee_id | int |
| start_time | datetime |
| end_time | datetime |
+------------------+----------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start time, and end time.
</pre>
<p>Write a solution to analyze overlapping shifts for each employee. Two shifts are considered overlapping if they occur on the <strong>same date</strong> and one shift's <code>end_time</code> is <strong>later than</strong> another shift's <code>start_time</code>.</p>
<p>For <strong>each employee</strong>, calculate the following:</p>
<ol>
<li>The <strong>maximum</strong> number of shifts that <strong>overlap</strong> at any <strong>given time</strong>.</li>
<li>The <strong>total duration</strong> of all overlaps in minutes.</li>
</ol>
<p><em>Return the result table ordered by</em> <code>employee_id</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The query 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><code>EmployeeShifts</code> table:</p>
<pre class="example-io">
+-------------+---------------------+---------------------+
| employee_id | start_time | end_time |
+-------------+---------------------+---------------------+
| 1 | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
| 1 | 2023-10-01 15:00:00 | 2023-10-01 23:00:00 |
| 1 | 2023-10-01 16:00:00 | 2023-10-02 00:00:00 |
| 2 | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
| 2 | 2023-10-01 11:00:00 | 2023-10-01 19:00:00 |
| 3 | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
+-------------+---------------------+---------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-------------+---------------------------+------------------------+
| employee_id | max_overlapping_shifts | total_overlap_duration |
+-------------+---------------------------+------------------------+
| 1 | 3 | 600 |
| 2 | 2 | 360 |
| 3 | 1 | 0 |
+-------------+---------------------------+------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Employee 1 has 3 shifts:
<ul>
<li>2023-10-01 09:00:00 to 2023-10-01 17:00:00</li>
<li>2023-10-01 15:00:00 to 2023-10-01 23:00:00</li>
<li>2023-10-01 16:00:00 to 2023-10-02 00:00:00</li>
</ul>
The maximum number of overlapping shifts is 3 (from 16:00 to 17:00). The total overlap duration is: - 2 hours (15:00-17:00) between 1st and 2nd shifts - 1 hour (16:00-17:00) between 1st and 3rd shifts - 7 hours (16:00-23:00) between 2nd and 3rd shifts Total: 10 hours = 600 minutes</li>
<li>Employee 2 has 2 shifts:
<ul>
<li>2023-10-01 09:00:00 to 2023-10-01 17:00:00</li>
<li>2023-10-01 11:00:00 to 2023-10-01 19:00:00</li>
</ul>
The maximum number of overlapping shifts is 2. The total overlap duration is 6 hours (11:00-17:00) = 360 minutes.</li>
<li>Employee 3 has only 1 shift, so there are no overlaps.</li>
</ul>
<p>The output table contains the employee_id, the maximum number of simultaneous overlaps, and the total overlap duration in minutes for each employee, ordered by employee_id in ascending order.</p>
</div>
|
Database
|
SQL
|
WITH
T AS (
SELECT DISTINCT employee_id, start_time AS st
FROM EmployeeShifts
UNION DISTINCT
SELECT DISTINCT employee_id, end_time AS st
FROM EmployeeShifts
),
P AS (
SELECT
*,
LEAD(st) OVER (
PARTITION BY employee_id
ORDER BY st
) AS ed
FROM T
),
S AS (
SELECT
P.*,
COUNT(1) AS concurrent_count
FROM
P
INNER JOIN EmployeeShifts USING (employee_id)
WHERE P.st >= EmployeeShifts.start_time AND P.ed <= EmployeeShifts.end_time
GROUP BY 1, 2, 3
),
U AS (
SELECT
t1.employee_id,
SUM(
TIMESTAMPDIFF(MINUTE, t2.start_time, LEAST(t1.end_time, t2.end_time))
) total_overlap_duration
FROM
EmployeeShifts t1
JOIN EmployeeShifts t2
ON t1.employee_id = t2.employee_id
AND t1.start_time < t2.start_time
AND t1.end_time > t2.start_time
GROUP BY 1
)
SELECT
employee_id,
MAX(concurrent_count) max_overlapping_shifts,
IFNULL(AVG(total_overlap_duration), 0) total_overlap_duration
FROM
S
LEFT JOIN U USING (employee_id)
GROUP BY 1
ORDER BY 1;
|
3,269 |
Constructing Two Increasing Arrays
|
Hard
|
<p>Given 2 integer arrays <code>nums1</code> and <code>nums2</code> consisting only of 0 and 1, your task is to calculate the <strong>minimum</strong> possible <strong>largest</strong> number in arrays <code>nums1</code> and <code>nums2</code>, after doing the following.</p>
<p>Replace every 0 with an <em>even positive integer</em> and every 1 with an <em>odd positive integer</em>. After replacement, both arrays should be <strong>increasing</strong> and each integer should be used <strong>at most</strong> once.</p>
<p>Return the <em>minimum possible largest number</em> after applying the changes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [], nums2 = [1,0,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>After replacing, <code>nums1 = []</code>, and <code>nums2 = [1, 2, 3, 5]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,1], nums2 = [1,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 9 as the largest element is <code>nums1 = [2, 3, 8, 9]</code>, and <code>nums2 = [1, 4, 6, 7]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 13 as the largest element is <code>nums1 = [2, 3, 4, 6, 7]</code>, and <code>nums2 = [8, 10, 12, 13]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums1.length <= 1000</code></li>
<li><code>1 <= nums2.length <= 1000</code></li>
<li><code>nums1</code> and <code>nums2</code> consist only of 0 and 1.</li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int minLargest(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
int f[m + 1][n + 1];
memset(f, 0, sizeof(f));
auto nxt = [](int x, int y) -> int {
return (x & 1 ^ y) == 1 ? x + 1 : x + 2;
};
for (int i = 1; i <= m; ++i) {
f[i][0] = nxt(f[i - 1][0], nums1[i - 1]);
}
for (int j = 1; j <= n; ++j) {
f[0][j] = nxt(f[0][j - 1], nums2[j - 1]);
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
int x = nxt(f[i - 1][j], nums1[i - 1]);
int y = nxt(f[i][j - 1], nums2[j - 1]);
f[i][j] = min(x, y);
}
}
return f[m][n];
}
};
|
3,269 |
Constructing Two Increasing Arrays
|
Hard
|
<p>Given 2 integer arrays <code>nums1</code> and <code>nums2</code> consisting only of 0 and 1, your task is to calculate the <strong>minimum</strong> possible <strong>largest</strong> number in arrays <code>nums1</code> and <code>nums2</code>, after doing the following.</p>
<p>Replace every 0 with an <em>even positive integer</em> and every 1 with an <em>odd positive integer</em>. After replacement, both arrays should be <strong>increasing</strong> and each integer should be used <strong>at most</strong> once.</p>
<p>Return the <em>minimum possible largest number</em> after applying the changes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [], nums2 = [1,0,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>After replacing, <code>nums1 = []</code>, and <code>nums2 = [1, 2, 3, 5]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,1], nums2 = [1,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 9 as the largest element is <code>nums1 = [2, 3, 8, 9]</code>, and <code>nums2 = [1, 4, 6, 7]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 13 as the largest element is <code>nums1 = [2, 3, 4, 6, 7]</code>, and <code>nums2 = [8, 10, 12, 13]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums1.length <= 1000</code></li>
<li><code>1 <= nums2.length <= 1000</code></li>
<li><code>nums1</code> and <code>nums2</code> consist only of 0 and 1.</li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func minLargest(nums1 []int, nums2 []int) int {
m, n := len(nums1), len(nums2)
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
nxt := func(x, y int) int {
if (x&1 ^ y) == 1 {
return x + 1
}
return x + 2
}
for i := 1; i <= m; i++ {
f[i][0] = nxt(f[i-1][0], nums1[i-1])
}
for j := 1; j <= n; j++ {
f[0][j] = nxt(f[0][j-1], nums2[j-1])
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
x := nxt(f[i-1][j], nums1[i-1])
y := nxt(f[i][j-1], nums2[j-1])
f[i][j] = min(x, y)
}
}
return f[m][n]
}
|
3,269 |
Constructing Two Increasing Arrays
|
Hard
|
<p>Given 2 integer arrays <code>nums1</code> and <code>nums2</code> consisting only of 0 and 1, your task is to calculate the <strong>minimum</strong> possible <strong>largest</strong> number in arrays <code>nums1</code> and <code>nums2</code>, after doing the following.</p>
<p>Replace every 0 with an <em>even positive integer</em> and every 1 with an <em>odd positive integer</em>. After replacement, both arrays should be <strong>increasing</strong> and each integer should be used <strong>at most</strong> once.</p>
<p>Return the <em>minimum possible largest number</em> after applying the changes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [], nums2 = [1,0,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>After replacing, <code>nums1 = []</code>, and <code>nums2 = [1, 2, 3, 5]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,1], nums2 = [1,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 9 as the largest element is <code>nums1 = [2, 3, 8, 9]</code>, and <code>nums2 = [1, 4, 6, 7]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 13 as the largest element is <code>nums1 = [2, 3, 4, 6, 7]</code>, and <code>nums2 = [8, 10, 12, 13]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums1.length <= 1000</code></li>
<li><code>1 <= nums2.length <= 1000</code></li>
<li><code>nums1</code> and <code>nums2</code> consist only of 0 and 1.</li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int minLargest(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
f[i][0] = nxt(f[i - 1][0], nums1[i - 1]);
}
for (int j = 1; j <= n; ++j) {
f[0][j] = nxt(f[0][j - 1], nums2[j - 1]);
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
int x = nxt(f[i - 1][j], nums1[i - 1]);
int y = nxt(f[i][j - 1], nums2[j - 1]);
f[i][j] = Math.min(x, y);
}
}
return f[m][n];
}
private int nxt(int x, int y) {
return (x & 1 ^ y) == 1 ? x + 1 : x + 2;
}
}
|
3,269 |
Constructing Two Increasing Arrays
|
Hard
|
<p>Given 2 integer arrays <code>nums1</code> and <code>nums2</code> consisting only of 0 and 1, your task is to calculate the <strong>minimum</strong> possible <strong>largest</strong> number in arrays <code>nums1</code> and <code>nums2</code>, after doing the following.</p>
<p>Replace every 0 with an <em>even positive integer</em> and every 1 with an <em>odd positive integer</em>. After replacement, both arrays should be <strong>increasing</strong> and each integer should be used <strong>at most</strong> once.</p>
<p>Return the <em>minimum possible largest number</em> after applying the changes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [], nums2 = [1,0,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>After replacing, <code>nums1 = []</code>, and <code>nums2 = [1, 2, 3, 5]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,1], nums2 = [1,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 9 as the largest element is <code>nums1 = [2, 3, 8, 9]</code>, and <code>nums2 = [1, 4, 6, 7]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 13 as the largest element is <code>nums1 = [2, 3, 4, 6, 7]</code>, and <code>nums2 = [8, 10, 12, 13]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums1.length <= 1000</code></li>
<li><code>1 <= nums2.length <= 1000</code></li>
<li><code>nums1</code> and <code>nums2</code> consist only of 0 and 1.</li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def minLargest(self, nums1: List[int], nums2: List[int]) -> int:
def nxt(x: int, y: int) -> int:
return x + 1 if (x & 1 ^ y) == 1 else x + 2
m, n = len(nums1), len(nums2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i, x in enumerate(nums1, 1):
f[i][0] = nxt(f[i - 1][0], x)
for j, y in enumerate(nums2, 1):
f[0][j] = nxt(f[0][j - 1], y)
for i, x in enumerate(nums1, 1):
for j, y in enumerate(nums2, 1):
f[i][j] = min(nxt(f[i - 1][j], x), nxt(f[i][j - 1], y))
return f[m][n]
|
3,269 |
Constructing Two Increasing Arrays
|
Hard
|
<p>Given 2 integer arrays <code>nums1</code> and <code>nums2</code> consisting only of 0 and 1, your task is to calculate the <strong>minimum</strong> possible <strong>largest</strong> number in arrays <code>nums1</code> and <code>nums2</code>, after doing the following.</p>
<p>Replace every 0 with an <em>even positive integer</em> and every 1 with an <em>odd positive integer</em>. After replacement, both arrays should be <strong>increasing</strong> and each integer should be used <strong>at most</strong> once.</p>
<p>Return the <em>minimum possible largest number</em> after applying the changes.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [], nums2 = [1,0,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>After replacing, <code>nums1 = []</code>, and <code>nums2 = [1, 2, 3, 5]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,1], nums2 = [1,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 9 as the largest element is <code>nums1 = [2, 3, 8, 9]</code>, and <code>nums2 = [1, 4, 6, 7]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [0,1,0,0,1], nums2 = [0,0,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to replace, having 13 as the largest element is <code>nums1 = [2, 3, 4, 6, 7]</code>, and <code>nums2 = [8, 10, 12, 13]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums1.length <= 1000</code></li>
<li><code>1 <= nums2.length <= 1000</code></li>
<li><code>nums1</code> and <code>nums2</code> consist only of 0 and 1.</li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function minLargest(nums1: number[], nums2: number[]): number {
const m = nums1.length;
const n = nums2.length;
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
const nxt = (x: number, y: number): number => {
return (x & 1) ^ y ? x + 1 : x + 2;
};
for (let i = 1; i <= m; ++i) {
f[i][0] = nxt(f[i - 1][0], nums1[i - 1]);
}
for (let j = 1; j <= n; ++j) {
f[0][j] = nxt(f[0][j - 1], nums2[j - 1]);
}
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
f[i][j] = Math.min(nxt(f[i - 1][j], nums1[i - 1]), nxt(f[i][j - 1], nums2[j - 1]));
}
}
return f[m][n];
}
|
3,270 |
Find the Key of the Numbers
|
Easy
|
<p>You are given three <strong>positive</strong> integers <code>num1</code>, <code>num2</code>, and <code>num3</code>.</p>
<p>The <code>key</code> of <code>num1</code>, <code>num2</code>, and <code>num3</code> is defined as a four-digit number such that:</p>
<ul>
<li>Initially, if any number has <strong>less than</strong> four digits, it is padded with <strong>leading zeros</strong>.</li>
<li>The <code>i<sup>th</sup></code> digit (<code>1 <= i <= 4</code>) of the <code>key</code> is generated by taking the <strong>smallest</strong> digit among the <code>i<sup>th</sup></code> digits of <code>num1</code>, <code>num2</code>, and <code>num3</code>.</li>
</ul>
<p>Return the <code>key</code> of the three numbers <strong>without</strong> leading zeros (<em>if any</em>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 10, num3 = 1000</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>On padding, <code>num1</code> becomes <code>"0001"</code>, <code>num2</code> becomes <code>"0010"</code>, and <code>num3</code> remains <code>"1000"</code>.</p>
<ul>
<li>The <code>1<sup>st</sup></code> digit of the <code>key</code> is <code>min(0, 0, 1)</code>.</li>
<li>The <code>2<sup>nd</sup></code> digit of the <code>key</code> is <code>min(0, 0, 0)</code>.</li>
<li>The <code>3<sup>rd</sup></code> digit of the <code>key</code> is <code>min(0, 1, 0)</code>.</li>
<li>The <code>4<sup>th</sup></code> digit of the <code>key</code> is <code>min(1, 0, 0)</code>.</li>
</ul>
<p>Hence, the <code>key</code> is <code>"0000"</code>, i.e. 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 987, num2 = 879, num3 = 798</span></p>
<p><strong>Output:</strong> <span class="example-io">777</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 2, num3 = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1, num2, num3 <= 9999</code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
int generateKey(int num1, int num2, int num3) {
int ans = 0, k = 1;
for (int i = 0; i < 4; ++i) {
int x = min({num1 / k % 10, num2 / k % 10, num3 / k % 10});
ans += x * k;
k *= 10;
}
return ans;
}
};
|
3,270 |
Find the Key of the Numbers
|
Easy
|
<p>You are given three <strong>positive</strong> integers <code>num1</code>, <code>num2</code>, and <code>num3</code>.</p>
<p>The <code>key</code> of <code>num1</code>, <code>num2</code>, and <code>num3</code> is defined as a four-digit number such that:</p>
<ul>
<li>Initially, if any number has <strong>less than</strong> four digits, it is padded with <strong>leading zeros</strong>.</li>
<li>The <code>i<sup>th</sup></code> digit (<code>1 <= i <= 4</code>) of the <code>key</code> is generated by taking the <strong>smallest</strong> digit among the <code>i<sup>th</sup></code> digits of <code>num1</code>, <code>num2</code>, and <code>num3</code>.</li>
</ul>
<p>Return the <code>key</code> of the three numbers <strong>without</strong> leading zeros (<em>if any</em>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 10, num3 = 1000</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>On padding, <code>num1</code> becomes <code>"0001"</code>, <code>num2</code> becomes <code>"0010"</code>, and <code>num3</code> remains <code>"1000"</code>.</p>
<ul>
<li>The <code>1<sup>st</sup></code> digit of the <code>key</code> is <code>min(0, 0, 1)</code>.</li>
<li>The <code>2<sup>nd</sup></code> digit of the <code>key</code> is <code>min(0, 0, 0)</code>.</li>
<li>The <code>3<sup>rd</sup></code> digit of the <code>key</code> is <code>min(0, 1, 0)</code>.</li>
<li>The <code>4<sup>th</sup></code> digit of the <code>key</code> is <code>min(1, 0, 0)</code>.</li>
</ul>
<p>Hence, the <code>key</code> is <code>"0000"</code>, i.e. 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 987, num2 = 879, num3 = 798</span></p>
<p><strong>Output:</strong> <span class="example-io">777</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 2, num3 = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1, num2, num3 <= 9999</code></li>
</ul>
|
Math
|
Go
|
func generateKey(num1 int, num2 int, num3 int) (ans int) {
k := 1
for i := 0; i < 4; i++ {
x := min(min(num1/k%10, num2/k%10), num3/k%10)
ans += x * k
k *= 10
}
return
}
|
3,270 |
Find the Key of the Numbers
|
Easy
|
<p>You are given three <strong>positive</strong> integers <code>num1</code>, <code>num2</code>, and <code>num3</code>.</p>
<p>The <code>key</code> of <code>num1</code>, <code>num2</code>, and <code>num3</code> is defined as a four-digit number such that:</p>
<ul>
<li>Initially, if any number has <strong>less than</strong> four digits, it is padded with <strong>leading zeros</strong>.</li>
<li>The <code>i<sup>th</sup></code> digit (<code>1 <= i <= 4</code>) of the <code>key</code> is generated by taking the <strong>smallest</strong> digit among the <code>i<sup>th</sup></code> digits of <code>num1</code>, <code>num2</code>, and <code>num3</code>.</li>
</ul>
<p>Return the <code>key</code> of the three numbers <strong>without</strong> leading zeros (<em>if any</em>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 10, num3 = 1000</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>On padding, <code>num1</code> becomes <code>"0001"</code>, <code>num2</code> becomes <code>"0010"</code>, and <code>num3</code> remains <code>"1000"</code>.</p>
<ul>
<li>The <code>1<sup>st</sup></code> digit of the <code>key</code> is <code>min(0, 0, 1)</code>.</li>
<li>The <code>2<sup>nd</sup></code> digit of the <code>key</code> is <code>min(0, 0, 0)</code>.</li>
<li>The <code>3<sup>rd</sup></code> digit of the <code>key</code> is <code>min(0, 1, 0)</code>.</li>
<li>The <code>4<sup>th</sup></code> digit of the <code>key</code> is <code>min(1, 0, 0)</code>.</li>
</ul>
<p>Hence, the <code>key</code> is <code>"0000"</code>, i.e. 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 987, num2 = 879, num3 = 798</span></p>
<p><strong>Output:</strong> <span class="example-io">777</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 2, num3 = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1, num2, num3 <= 9999</code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int generateKey(int num1, int num2, int num3) {
int ans = 0, k = 1;
for (int i = 0; i < 4; ++i) {
int x = Math.min(Math.min(num1 / k % 10, num2 / k % 10), num3 / k % 10);
ans += x * k;
k *= 10;
}
return ans;
}
}
|
3,270 |
Find the Key of the Numbers
|
Easy
|
<p>You are given three <strong>positive</strong> integers <code>num1</code>, <code>num2</code>, and <code>num3</code>.</p>
<p>The <code>key</code> of <code>num1</code>, <code>num2</code>, and <code>num3</code> is defined as a four-digit number such that:</p>
<ul>
<li>Initially, if any number has <strong>less than</strong> four digits, it is padded with <strong>leading zeros</strong>.</li>
<li>The <code>i<sup>th</sup></code> digit (<code>1 <= i <= 4</code>) of the <code>key</code> is generated by taking the <strong>smallest</strong> digit among the <code>i<sup>th</sup></code> digits of <code>num1</code>, <code>num2</code>, and <code>num3</code>.</li>
</ul>
<p>Return the <code>key</code> of the three numbers <strong>without</strong> leading zeros (<em>if any</em>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 10, num3 = 1000</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>On padding, <code>num1</code> becomes <code>"0001"</code>, <code>num2</code> becomes <code>"0010"</code>, and <code>num3</code> remains <code>"1000"</code>.</p>
<ul>
<li>The <code>1<sup>st</sup></code> digit of the <code>key</code> is <code>min(0, 0, 1)</code>.</li>
<li>The <code>2<sup>nd</sup></code> digit of the <code>key</code> is <code>min(0, 0, 0)</code>.</li>
<li>The <code>3<sup>rd</sup></code> digit of the <code>key</code> is <code>min(0, 1, 0)</code>.</li>
<li>The <code>4<sup>th</sup></code> digit of the <code>key</code> is <code>min(1, 0, 0)</code>.</li>
</ul>
<p>Hence, the <code>key</code> is <code>"0000"</code>, i.e. 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 987, num2 = 879, num3 = 798</span></p>
<p><strong>Output:</strong> <span class="example-io">777</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 2, num3 = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1, num2, num3 <= 9999</code></li>
</ul>
|
Math
|
Python
|
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
ans, k = 0, 1
for _ in range(4):
x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10)
ans += x * k
k *= 10
return ans
|
3,270 |
Find the Key of the Numbers
|
Easy
|
<p>You are given three <strong>positive</strong> integers <code>num1</code>, <code>num2</code>, and <code>num3</code>.</p>
<p>The <code>key</code> of <code>num1</code>, <code>num2</code>, and <code>num3</code> is defined as a four-digit number such that:</p>
<ul>
<li>Initially, if any number has <strong>less than</strong> four digits, it is padded with <strong>leading zeros</strong>.</li>
<li>The <code>i<sup>th</sup></code> digit (<code>1 <= i <= 4</code>) of the <code>key</code> is generated by taking the <strong>smallest</strong> digit among the <code>i<sup>th</sup></code> digits of <code>num1</code>, <code>num2</code>, and <code>num3</code>.</li>
</ul>
<p>Return the <code>key</code> of the three numbers <strong>without</strong> leading zeros (<em>if any</em>).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 10, num3 = 1000</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>On padding, <code>num1</code> becomes <code>"0001"</code>, <code>num2</code> becomes <code>"0010"</code>, and <code>num3</code> remains <code>"1000"</code>.</p>
<ul>
<li>The <code>1<sup>st</sup></code> digit of the <code>key</code> is <code>min(0, 0, 1)</code>.</li>
<li>The <code>2<sup>nd</sup></code> digit of the <code>key</code> is <code>min(0, 0, 0)</code>.</li>
<li>The <code>3<sup>rd</sup></code> digit of the <code>key</code> is <code>min(0, 1, 0)</code>.</li>
<li>The <code>4<sup>th</sup></code> digit of the <code>key</code> is <code>min(1, 0, 0)</code>.</li>
</ul>
<p>Hence, the <code>key</code> is <code>"0000"</code>, i.e. 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 987, num2 = 879, num3 = 798</span></p>
<p><strong>Output:</strong> <span class="example-io">777</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">num1 = 1, num2 = 2, num3 = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num1, num2, num3 <= 9999</code></li>
</ul>
|
Math
|
TypeScript
|
function generateKey(num1: number, num2: number, num3: number): number {
let [ans, k] = [0, 1];
for (let i = 0; i < 4; ++i) {
const x = Math.min(((num1 / k) | 0) % 10, ((num2 / k) | 0) % 10, ((num3 / k) | 0) % 10);
ans += x * k;
k *= 10;
}
return ans;
}
|
3,271 |
Hash Divided String
|
Medium
|
<p>You are given a string <code>s</code> of length <code>n</code> and an integer <code>k</code>, where <code>n</code> is a <strong>multiple</strong> of <code>k</code>. Your task is to hash the string <code>s</code> into a new string called <code>result</code>, which has a length of <code>n / k</code>.</p>
<p>First, divide <code>s</code> into <code>n / k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong>, each with a length of <code>k</code>. Then, initialize <code>result</code> as an <strong>empty</strong> string.</p>
<p>For each <strong>substring</strong> in order from the beginning:</p>
<ul>
<li>The <strong>hash value</strong> of a character is the index of that characte<!-- notionvc: 4b67483a-fa95-40b6-870d-2eacd9bc18d8 -->r in the <strong>English alphabet</strong> (e.g., <code>'a' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 0</code>, <code>'b' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 1</code>, ..., <code>'z' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 25</code>).</li>
<li>Calculate the <em>sum</em> of all the <strong>hash values</strong> of the characters in the substring.</li>
<li>Find the remainder of this sum when divided by 26, which is called <code>hashedChar</code>.</li>
<li>Identify the character in the English lowercase alphabet that corresponds to <code>hashedChar</code>.</li>
<li>Append that character to the end of <code>result</code>.</li>
</ul>
<p>Return <code>result</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 = "abcd", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"bf"</span></p>
<p><strong>Explanation:</strong></p>
<p>First substring: <code>"ab"</code>, <code>0 + 1 = 1</code>, <code>1 % 26 = 1</code>, <code>result[0] = 'b'</code>.</p>
<p>Second substring: <code>"cd"</code>, <code>2 + 3 = 5</code>, <code>5 % 26 = 5</code>, <code>result[1] = 'f'</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "mxz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"i"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring: <code>"mxz"</code>, <code>12 + 23 + 25 = 60</code>, <code>60 % 26 = 8</code>, <code>result[0] = 'i'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 100</code></li>
<li><code>k <= s.length <= 1000</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String; Simulation
|
C++
|
class Solution {
public:
string stringHash(string s, int k) {
string ans;
int n = s.length();
for (int i = 0; i < n; i += k) {
int t = 0;
for (int j = i; j < i + k; ++j) {
t += s[j] - 'a';
}
int hashedChar = t % 26;
ans += ('a' + hashedChar);
}
return ans;
}
};
|
3,271 |
Hash Divided String
|
Medium
|
<p>You are given a string <code>s</code> of length <code>n</code> and an integer <code>k</code>, where <code>n</code> is a <strong>multiple</strong> of <code>k</code>. Your task is to hash the string <code>s</code> into a new string called <code>result</code>, which has a length of <code>n / k</code>.</p>
<p>First, divide <code>s</code> into <code>n / k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong>, each with a length of <code>k</code>. Then, initialize <code>result</code> as an <strong>empty</strong> string.</p>
<p>For each <strong>substring</strong> in order from the beginning:</p>
<ul>
<li>The <strong>hash value</strong> of a character is the index of that characte<!-- notionvc: 4b67483a-fa95-40b6-870d-2eacd9bc18d8 -->r in the <strong>English alphabet</strong> (e.g., <code>'a' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 0</code>, <code>'b' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 1</code>, ..., <code>'z' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 25</code>).</li>
<li>Calculate the <em>sum</em> of all the <strong>hash values</strong> of the characters in the substring.</li>
<li>Find the remainder of this sum when divided by 26, which is called <code>hashedChar</code>.</li>
<li>Identify the character in the English lowercase alphabet that corresponds to <code>hashedChar</code>.</li>
<li>Append that character to the end of <code>result</code>.</li>
</ul>
<p>Return <code>result</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 = "abcd", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"bf"</span></p>
<p><strong>Explanation:</strong></p>
<p>First substring: <code>"ab"</code>, <code>0 + 1 = 1</code>, <code>1 % 26 = 1</code>, <code>result[0] = 'b'</code>.</p>
<p>Second substring: <code>"cd"</code>, <code>2 + 3 = 5</code>, <code>5 % 26 = 5</code>, <code>result[1] = 'f'</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "mxz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"i"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring: <code>"mxz"</code>, <code>12 + 23 + 25 = 60</code>, <code>60 % 26 = 8</code>, <code>result[0] = 'i'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 100</code></li>
<li><code>k <= s.length <= 1000</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String; Simulation
|
Go
|
func stringHash(s string, k int) string {
n := len(s)
ans := make([]byte, 0, n/k)
for i := 0; i < n; i += k {
t := 0
for j := i; j < i+k; j++ {
t += int(s[j] - 'a')
}
hashedChar := t % 26
ans = append(ans, 'a'+byte(hashedChar))
}
return string(ans)
}
|
3,271 |
Hash Divided String
|
Medium
|
<p>You are given a string <code>s</code> of length <code>n</code> and an integer <code>k</code>, where <code>n</code> is a <strong>multiple</strong> of <code>k</code>. Your task is to hash the string <code>s</code> into a new string called <code>result</code>, which has a length of <code>n / k</code>.</p>
<p>First, divide <code>s</code> into <code>n / k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong>, each with a length of <code>k</code>. Then, initialize <code>result</code> as an <strong>empty</strong> string.</p>
<p>For each <strong>substring</strong> in order from the beginning:</p>
<ul>
<li>The <strong>hash value</strong> of a character is the index of that characte<!-- notionvc: 4b67483a-fa95-40b6-870d-2eacd9bc18d8 -->r in the <strong>English alphabet</strong> (e.g., <code>'a' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 0</code>, <code>'b' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 1</code>, ..., <code>'z' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 25</code>).</li>
<li>Calculate the <em>sum</em> of all the <strong>hash values</strong> of the characters in the substring.</li>
<li>Find the remainder of this sum when divided by 26, which is called <code>hashedChar</code>.</li>
<li>Identify the character in the English lowercase alphabet that corresponds to <code>hashedChar</code>.</li>
<li>Append that character to the end of <code>result</code>.</li>
</ul>
<p>Return <code>result</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 = "abcd", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"bf"</span></p>
<p><strong>Explanation:</strong></p>
<p>First substring: <code>"ab"</code>, <code>0 + 1 = 1</code>, <code>1 % 26 = 1</code>, <code>result[0] = 'b'</code>.</p>
<p>Second substring: <code>"cd"</code>, <code>2 + 3 = 5</code>, <code>5 % 26 = 5</code>, <code>result[1] = 'f'</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "mxz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"i"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring: <code>"mxz"</code>, <code>12 + 23 + 25 = 60</code>, <code>60 % 26 = 8</code>, <code>result[0] = 'i'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 100</code></li>
<li><code>k <= s.length <= 1000</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String; Simulation
|
Java
|
class Solution {
public String stringHash(String s, int k) {
StringBuilder ans = new StringBuilder();
int n = s.length();
for (int i = 0; i < n; i += k) {
int t = 0;
for (int j = i; j < i + k; ++j) {
t += s.charAt(j) - 'a';
}
int hashedChar = t % 26;
ans.append((char) ('a' + hashedChar));
}
return ans.toString();
}
}
|
3,271 |
Hash Divided String
|
Medium
|
<p>You are given a string <code>s</code> of length <code>n</code> and an integer <code>k</code>, where <code>n</code> is a <strong>multiple</strong> of <code>k</code>. Your task is to hash the string <code>s</code> into a new string called <code>result</code>, which has a length of <code>n / k</code>.</p>
<p>First, divide <code>s</code> into <code>n / k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong>, each with a length of <code>k</code>. Then, initialize <code>result</code> as an <strong>empty</strong> string.</p>
<p>For each <strong>substring</strong> in order from the beginning:</p>
<ul>
<li>The <strong>hash value</strong> of a character is the index of that characte<!-- notionvc: 4b67483a-fa95-40b6-870d-2eacd9bc18d8 -->r in the <strong>English alphabet</strong> (e.g., <code>'a' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 0</code>, <code>'b' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 1</code>, ..., <code>'z' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 25</code>).</li>
<li>Calculate the <em>sum</em> of all the <strong>hash values</strong> of the characters in the substring.</li>
<li>Find the remainder of this sum when divided by 26, which is called <code>hashedChar</code>.</li>
<li>Identify the character in the English lowercase alphabet that corresponds to <code>hashedChar</code>.</li>
<li>Append that character to the end of <code>result</code>.</li>
</ul>
<p>Return <code>result</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 = "abcd", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"bf"</span></p>
<p><strong>Explanation:</strong></p>
<p>First substring: <code>"ab"</code>, <code>0 + 1 = 1</code>, <code>1 % 26 = 1</code>, <code>result[0] = 'b'</code>.</p>
<p>Second substring: <code>"cd"</code>, <code>2 + 3 = 5</code>, <code>5 % 26 = 5</code>, <code>result[1] = 'f'</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "mxz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"i"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring: <code>"mxz"</code>, <code>12 + 23 + 25 = 60</code>, <code>60 % 26 = 8</code>, <code>result[0] = 'i'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 100</code></li>
<li><code>k <= s.length <= 1000</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def stringHash(self, s: str, k: int) -> str:
ans = []
for i in range(0, len(s), k):
t = 0
for j in range(i, i + k):
t += ord(s[j]) - ord("a")
hashedChar = t % 26
ans.append(chr(ord("a") + hashedChar))
return "".join(ans)
|
3,271 |
Hash Divided String
|
Medium
|
<p>You are given a string <code>s</code> of length <code>n</code> and an integer <code>k</code>, where <code>n</code> is a <strong>multiple</strong> of <code>k</code>. Your task is to hash the string <code>s</code> into a new string called <code>result</code>, which has a length of <code>n / k</code>.</p>
<p>First, divide <code>s</code> into <code>n / k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong>, each with a length of <code>k</code>. Then, initialize <code>result</code> as an <strong>empty</strong> string.</p>
<p>For each <strong>substring</strong> in order from the beginning:</p>
<ul>
<li>The <strong>hash value</strong> of a character is the index of that characte<!-- notionvc: 4b67483a-fa95-40b6-870d-2eacd9bc18d8 -->r in the <strong>English alphabet</strong> (e.g., <code>'a' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 0</code>, <code>'b' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 1</code>, ..., <code>'z' →<!-- notionvc: d3f8e4c2-23cd-41ad-a14b-101dfe4c5aba --> 25</code>).</li>
<li>Calculate the <em>sum</em> of all the <strong>hash values</strong> of the characters in the substring.</li>
<li>Find the remainder of this sum when divided by 26, which is called <code>hashedChar</code>.</li>
<li>Identify the character in the English lowercase alphabet that corresponds to <code>hashedChar</code>.</li>
<li>Append that character to the end of <code>result</code>.</li>
</ul>
<p>Return <code>result</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 = "abcd", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"bf"</span></p>
<p><strong>Explanation:</strong></p>
<p>First substring: <code>"ab"</code>, <code>0 + 1 = 1</code>, <code>1 % 26 = 1</code>, <code>result[0] = 'b'</code>.</p>
<p>Second substring: <code>"cd"</code>, <code>2 + 3 = 5</code>, <code>5 % 26 = 5</code>, <code>result[1] = 'f'</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "mxz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"i"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only substring: <code>"mxz"</code>, <code>12 + 23 + 25 = 60</code>, <code>60 % 26 = 8</code>, <code>result[0] = 'i'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 100</code></li>
<li><code>k <= s.length <= 1000</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String; Simulation
|
TypeScript
|
function stringHash(s: string, k: number): string {
const ans: string[] = [];
const n: number = s.length;
for (let i = 0; i < n; i += k) {
let t: number = 0;
for (let j = i; j < i + k; j++) {
t += s.charCodeAt(j) - 97;
}
const hashedChar: number = t % 26;
ans.push(String.fromCharCode(97 + hashedChar));
}
return ans.join('');
}
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
C++
|
class Solution {
public:
long long countGoodIntegers(int n, int k) {
vector<long long> fac(n + 1, 1);
for (int i = 1; i <= n; ++i) {
fac[i] = fac[i - 1] * i;
}
long long ans = 0;
unordered_set<string> vis;
int base = pow(10, (n - 1) / 2);
for (int i = base; i < base * 10; ++i) {
string s = to_string(i);
string rev = s;
reverse(rev.begin(), rev.end());
s += rev.substr(n % 2);
if (stoll(s) % k) {
continue;
}
string t = s;
sort(t.begin(), t.end());
if (vis.count(t)) {
continue;
}
vis.insert(t);
vector<int> cnt(10);
for (char c : t) {
cnt[c - '0']++;
}
long long res = (n - cnt[0]) * fac[n - 1];
for (int x : cnt) {
res /= fac[x];
}
ans += res;
}
return ans;
}
};
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
Go
|
func factorial(n int) []int64 {
fac := make([]int64, n+1)
fac[0] = 1
for i := 1; i <= n; i++ {
fac[i] = fac[i-1] * int64(i)
}
return fac
}
func countGoodIntegers(n int, k int) (ans int64) {
fac := factorial(n)
vis := make(map[string]bool)
base := int(math.Pow(10, float64((n-1)/2)))
for i := base; i < base*10; i++ {
s := strconv.Itoa(i)
rev := reverseString(s)
s += rev[n%2:]
num, _ := strconv.ParseInt(s, 10, 64)
if num%int64(k) != 0 {
continue
}
bs := []byte(s)
slices.Sort(bs)
t := string(bs)
if vis[t] {
continue
}
vis[t] = true
cnt := make([]int, 10)
for _, c := range t {
cnt[c-'0']++
}
res := (int64(n) - int64(cnt[0])) * fac[n-1]
for _, x := range cnt {
res /= fac[x]
}
ans += res
}
return
}
func reverseString(s string) string {
t := []byte(s)
for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 {
t[i], t[j] = t[j], t[i]
}
return string(t)
}
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
Java
|
class Solution {
public long countGoodIntegers(int n, int k) {
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++) {
fac[i] = fac[i - 1] * i;
}
long ans = 0;
Set<String> vis = new HashSet<>();
int base = (int) Math.pow(10, (n - 1) / 2);
for (int i = base; i < base * 10; i++) {
String s = String.valueOf(i);
StringBuilder sb = new StringBuilder(s).reverse();
s += sb.substring(n % 2);
if (Long.parseLong(s) % k != 0) {
continue;
}
char[] arr = s.toCharArray();
Arrays.sort(arr);
String t = new String(arr);
if (vis.contains(t)) {
continue;
}
vis.add(t);
int[] cnt = new int[10];
for (char c : arr) {
cnt[c - '0']++;
}
long res = (n - cnt[0]) * fac[n - 1];
for (int x : cnt) {
res /= fac[x];
}
ans += res;
}
return ans;
}
}
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
JavaScript
|
/**
* @param {number} n
* @param {number} k
* @return {number}
*/
var countGoodIntegers = function (n, k) {
const fac = factorial(n);
let ans = 0;
const vis = new Set();
const base = Math.pow(10, Math.floor((n - 1) / 2));
for (let i = base; i < base * 10; i++) {
let s = String(i);
const rev = reverseString(s);
if (n % 2 === 1) {
s += rev.substring(1);
} else {
s += rev;
}
if (parseInt(s, 10) % k !== 0) {
continue;
}
const bs = Array.from(s).sort();
const t = bs.join('');
if (vis.has(t)) {
continue;
}
vis.add(t);
const cnt = Array(10).fill(0);
for (const c of t) {
cnt[parseInt(c, 10)]++;
}
let res = (n - cnt[0]) * fac[n - 1];
for (const x of cnt) {
res /= fac[x];
}
ans += res;
}
return ans;
};
function factorial(n) {
const fac = Array(n + 1).fill(1);
for (let i = 1; i <= n; i++) {
fac[i] = fac[i - 1] * i;
}
return fac;
}
function reverseString(s) {
return s.split('').reverse().join('');
}
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
Python
|
class Solution:
def countGoodIntegers(self, n: int, k: int) -> int:
fac = [factorial(i) for i in range(n + 1)]
ans = 0
vis = set()
base = 10 ** ((n - 1) // 2)
for i in range(base, base * 10):
s = str(i)
s += s[::-1][n % 2 :]
if int(s) % k:
continue
t = "".join(sorted(s))
if t in vis:
continue
vis.add(t)
cnt = Counter(t)
res = (n - cnt["0"]) * fac[n - 1]
for x in cnt.values():
res //= fac[x]
ans += res
return ans
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
Rust
|
impl Solution {
pub fn count_good_integers(n: i32, k: i32) -> i64 {
use std::collections::HashSet;
let n = n as usize;
let k = k as i64;
let mut fac = vec![1_i64; n + 1];
for i in 1..=n {
fac[i] = fac[i - 1] * i as i64;
}
let mut ans = 0;
let mut vis = HashSet::new();
let base = 10_i64.pow(((n - 1) / 2) as u32);
for i in base..base * 10 {
let s = i.to_string();
let rev: String = s.chars().rev().collect();
let full_s = if n % 2 == 0 {
format!("{}{}", s, rev)
} else {
format!("{}{}", s, &rev[1..])
};
let num: i64 = full_s.parse().unwrap();
if num % k != 0 {
continue;
}
let mut arr: Vec<char> = full_s.chars().collect();
arr.sort_unstable();
let t: String = arr.iter().collect();
if vis.contains(&t) {
continue;
}
vis.insert(t);
let mut cnt = vec![0; 10];
for c in arr {
cnt[c as usize - '0' as usize] += 1;
}
let mut res = (n - cnt[0]) as i64 * fac[n - 1];
for &x in &cnt {
if x > 0 {
res /= fac[x];
}
}
ans += res;
}
ans
}
}
|
3,272 |
Find the Count of Good Integers
|
Hard
|
<p>You are given two <strong>positive</strong> integers <code>n</code> and <code>k</code>.</p>
<p>An integer <code>x</code> is called <strong>k-palindromic</strong> if:</p>
<ul>
<li><code>x</code> is a <span data-keyword="palindrome-integer">palindrome</span>.</li>
<li><code>x</code> is divisible by <code>k</code>.</li>
</ul>
<p>An integer is called <strong>good</strong> if its digits can be <em>rearranged</em> to form a <strong>k-palindromic</strong> integer. For example, for <code>k = 2</code>, 2020 can be rearranged to form the <em>k-palindromic</em> integer 2002, whereas 1010 cannot be rearranged to form a <em>k-palindromic</em> integer.</p>
<p>Return the count of <strong>good</strong> integers containing <code>n</code> digits.</p>
<p><strong>Note</strong> that <em>any</em> integer must <strong>not</strong> have leading zeros, <strong>neither</strong> before <strong>nor</strong> after rearrangement. For example, 1010 <em>cannot</em> be rearranged to form 101.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">27</span></p>
<p><strong>Explanation:</strong></p>
<p><em>Some</em> of the good integers are:</p>
<ul>
<li>551 because it can be rearranged to form 515.</li>
<li>525 because it is already k-palindromic.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The two good integers are 4 and 8.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2468</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10</code></li>
<li><code>1 <= k <= 9</code></li>
</ul>
|
Hash Table; Math; Combinatorics; Enumeration
|
TypeScript
|
function countGoodIntegers(n: number, k: number): number {
const fac = factorial(n);
let ans = 0;
const vis = new Set<string>();
const base = Math.pow(10, Math.floor((n - 1) / 2));
for (let i = base; i < base * 10; i++) {
let s = `${i}`;
const rev = reverseString(s);
if (n % 2 === 1) {
s += rev.substring(1);
} else {
s += rev;
}
if (+s % k !== 0) {
continue;
}
const bs = Array.from(s).sort();
const t = bs.join('');
if (vis.has(t)) {
continue;
}
vis.add(t);
const cnt = Array(10).fill(0);
for (const c of t) {
cnt[+c]++;
}
let res = (n - cnt[0]) * fac[n - 1];
for (const x of cnt) {
res /= fac[x];
}
ans += res;
}
return ans;
}
function factorial(n: number): number[] {
const fac = Array(n + 1).fill(1);
for (let i = 1; i <= n; i++) {
fac[i] = fac[i - 1] * i;
}
return fac;
}
function reverseString(s: string): string {
return s.split('').reverse().join('');
}
|
3,274 |
Check if Two Chessboard Squares Have the Same Color
|
Easy
|
<p>You are given two strings, <code>coordinate1</code> and <code>coordinate2</code>, representing the coordinates of a square on an <code>8 x 8</code> chessboard.</p>
<p>Below is the chessboard for reference.</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3274.Check%20if%20Two%20Chessboard%20Squares%20Have%20the%20Same%20Color/images/screenshot-2021-02-20-at-22159-pm.png" style="width: 400px; height: 396px;" /></p>
<p>Return <code>true</code> if these two squares have the same color and <code>false</code> otherwise.</p>
<p>The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first (indicating its column), and the number second (indicating its row).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">coordinate1 = "a1", coordinate2 = "c3"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Both squares are black.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">coordinate1 = "a1", coordinate2 = "h3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Square <code>"a1"</code> is black and <code>"h3"</code> is white.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>coordinate1.length == coordinate2.length == 2</code></li>
<li><code>'a' <= coordinate1[0], coordinate2[0] <= 'h'</code></li>
<li><code>'1' <= coordinate1[1], coordinate2[1] <= '8'</code></li>
</ul>
|
Math; String
|
C++
|
class Solution {
public:
bool checkTwoChessboards(string coordinate1, string coordinate2) {
int x = coordinate1[0] - coordinate2[0];
int y = coordinate1[1] - coordinate2[1];
return (x + y) % 2 == 0;
}
};
|
3,274 |
Check if Two Chessboard Squares Have the Same Color
|
Easy
|
<p>You are given two strings, <code>coordinate1</code> and <code>coordinate2</code>, representing the coordinates of a square on an <code>8 x 8</code> chessboard.</p>
<p>Below is the chessboard for reference.</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3274.Check%20if%20Two%20Chessboard%20Squares%20Have%20the%20Same%20Color/images/screenshot-2021-02-20-at-22159-pm.png" style="width: 400px; height: 396px;" /></p>
<p>Return <code>true</code> if these two squares have the same color and <code>false</code> otherwise.</p>
<p>The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first (indicating its column), and the number second (indicating its row).</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">coordinate1 = "a1", coordinate2 = "c3"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>Both squares are black.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">coordinate1 = "a1", coordinate2 = "h3"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>Square <code>"a1"</code> is black and <code>"h3"</code> is white.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>coordinate1.length == coordinate2.length == 2</code></li>
<li><code>'a' <= coordinate1[0], coordinate2[0] <= 'h'</code></li>
<li><code>'1' <= coordinate1[1], coordinate2[1] <= '8'</code></li>
</ul>
|
Math; String
|
Go
|
func checkTwoChessboards(coordinate1 string, coordinate2 string) bool {
x := coordinate1[0] - coordinate2[0]
y := coordinate1[1] - coordinate2[1]
return (x+y)%2 == 0
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.