id
int64 1
3.71k
| 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,078
|
Match Alphanumerical Pattern in Matrix I
|
Medium
|
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 <= board[r][c] <= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p>
<p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p>
<p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p>
<ul>
<li>The matrices have identical dimensions.</li>
<li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li>
<li>If <code>pattern[r][c]</code> is a letter <code>x</code>:
<ul>
<li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li>
<li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li>
</ul>
</li>
</ul>
<p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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;">2</td>
<td 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 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;">2</td>
<td 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;">2</td>
<td 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>
</tr>
<tr>
<td 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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;">b</td>
<td 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;">b</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 1</code> and <code>"b" -> 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p>
<p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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 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>
<td 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>
</tr>
<tr>
<td 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 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;">6</td>
<td 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;">6</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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 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>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 3</code> and <code>"b" -> 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p>
<p>Note that since the corresponding values of <code>"a"</code> and <code>"b"</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">x</td>
<td 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;">x</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = ["xx"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
<p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 50</code></li>
<li><code>1 <= board[i].length <= 50</code></li>
<li><code>0 <= board[i][j] <= 9</code></li>
<li><code>1 <= pattern.length <= 50</code></li>
<li><code>1 <= pattern[i].length <= 50</code></li>
<li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li>
</ul>
|
Array; Hash Table; String; Matrix
|
Java
|
class Solution {
public int[] findPattern(int[][] board, String[] pattern) {
int m = board.length, n = board[0].length;
int r = pattern.length, c = pattern[0].length();
for (int i = 0; i < m - r + 1; ++i) {
for (int j = 0; j < n - c + 1; ++j) {
if (check(board, pattern, i, j)) {
return new int[] {i, j};
}
}
}
return new int[] {-1, -1};
}
private boolean check(int[][] board, String[] pattern, int i, int j) {
int[] d1 = new int[26];
int[] d2 = new int[10];
Arrays.fill(d1, -1);
Arrays.fill(d2, -1);
for (int a = 0; a < pattern.length; ++a) {
for (int b = 0; b < pattern[0].length(); ++b) {
int x = i + a, y = j + b;
if (Character.isDigit(pattern[a].charAt(b))) {
int v = pattern[a].charAt(b) - '0';
if (v != board[x][y]) {
return false;
}
} else {
int v = pattern[a].charAt(b) - 'a';
if (d1[v] != -1 && d1[v] != board[x][y]) {
return false;
}
if (d2[board[x][y]] != -1 && d2[board[x][y]] != v) {
return false;
}
d1[v] = board[x][y];
d2[board[x][y]] = v;
}
}
}
return true;
}
}
|
3,078
|
Match Alphanumerical Pattern in Matrix I
|
Medium
|
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 <= board[r][c] <= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p>
<p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p>
<p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p>
<ul>
<li>The matrices have identical dimensions.</li>
<li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li>
<li>If <code>pattern[r][c]</code> is a letter <code>x</code>:
<ul>
<li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li>
<li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li>
</ul>
</li>
</ul>
<p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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;">2</td>
<td 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 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;">2</td>
<td 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;">2</td>
<td 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>
</tr>
<tr>
<td 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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;">b</td>
<td 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;">b</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 1</code> and <code>"b" -> 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p>
<p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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 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>
<td 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>
</tr>
<tr>
<td 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 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;">6</td>
<td 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;">6</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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 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>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 3</code> and <code>"b" -> 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p>
<p>Note that since the corresponding values of <code>"a"</code> and <code>"b"</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">x</td>
<td 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;">x</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = ["xx"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
<p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 50</code></li>
<li><code>1 <= board[i].length <= 50</code></li>
<li><code>0 <= board[i][j] <= 9</code></li>
<li><code>1 <= pattern.length <= 50</code></li>
<li><code>1 <= pattern[i].length <= 50</code></li>
<li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li>
</ul>
|
Array; Hash Table; String; Matrix
|
Python
|
class Solution:
def findPattern(self, board: List[List[int]], pattern: List[str]) -> List[int]:
def check(i: int, j: int) -> bool:
d1 = {}
d2 = {}
for a in range(r):
for b in range(c):
x, y = i + a, j + b
if pattern[a][b].isdigit():
if int(pattern[a][b]) != board[x][y]:
return False
else:
if pattern[a][b] in d1 and d1[pattern[a][b]] != board[x][y]:
return False
if board[x][y] in d2 and d2[board[x][y]] != pattern[a][b]:
return False
d1[pattern[a][b]] = board[x][y]
d2[board[x][y]] = pattern[a][b]
return True
m, n = len(board), len(board[0])
r, c = len(pattern), len(pattern[0])
for i in range(m - r + 1):
for j in range(n - c + 1):
if check(i, j):
return [i, j]
return [-1, -1]
|
3,078
|
Match Alphanumerical Pattern in Matrix I
|
Medium
|
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 <= board[r][c] <= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p>
<p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p>
<p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p>
<ul>
<li>The matrices have identical dimensions.</li>
<li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li>
<li>If <code>pattern[r][c]</code> is a letter <code>x</code>:
<ul>
<li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li>
<li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li>
</ul>
</li>
</ul>
<p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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;">2</td>
<td 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 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;">2</td>
<td 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;">2</td>
<td 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>
</tr>
<tr>
<td 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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;">b</td>
<td 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;">b</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = ["ab","bb"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 1</code> and <code>"b" -> 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p>
<p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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 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>
<td 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>
</tr>
<tr>
<td 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 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;">6</td>
<td 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;">6</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">a</td>
<td 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;">b</td>
</tr>
<tr>
<td 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 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>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = ["ab","66"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1]</span></p>
<p><strong>Explanation:</strong> If we consider this mapping: <code>"a" -> 3</code> and <code>"b" -> 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p>
<p>Note that since the corresponding values of <code>"a"</code> and <code>"b"</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;">
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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 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 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 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>
</tr>
</tbody>
</table>
<table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;">
<tbody>
<tr>
<td 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;">x</td>
<td 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;">x</td>
</tr>
</tbody>
</table>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = ["xx"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p>
<p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= board.length <= 50</code></li>
<li><code>1 <= board[i].length <= 50</code></li>
<li><code>0 <= board[i][j] <= 9</code></li>
<li><code>1 <= pattern.length <= 50</code></li>
<li><code>1 <= pattern[i].length <= 50</code></li>
<li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li>
</ul>
|
Array; Hash Table; String; Matrix
|
TypeScript
|
function findPattern(board: number[][], pattern: string[]): number[] {
const m: number = board.length;
const n: number = board[0].length;
const r: number = pattern.length;
const c: number = pattern[0].length;
const check = (i: number, j: number): boolean => {
const d1: number[] = Array(26).fill(-1);
const d2: number[] = Array(10).fill(-1);
for (let a = 0; a < r; ++a) {
for (let b = 0; b < c; ++b) {
const x: number = i + a;
const y: number = j + b;
if (!isNaN(Number(pattern[a][b]))) {
const v: number = Number(pattern[a][b]);
if (v !== board[x][y]) {
return false;
}
} else {
const v: number = pattern[a].charCodeAt(b) - 'a'.charCodeAt(0);
if (d1[v] !== -1 && d1[v] !== board[x][y]) {
return false;
}
if (d2[board[x][y]] !== -1 && d2[board[x][y]] !== v) {
return false;
}
d1[v] = board[x][y];
d2[board[x][y]] = v;
}
}
}
return true;
};
for (let i = 0; i < m - r + 1; ++i) {
for (let j = 0; j < n - c + 1; ++j) {
if (check(i, j)) {
return [i, j];
}
}
}
return [-1, -1];
}
|
3,079
|
Find the Sum of Encrypted Integers
|
Easy
|
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p>
<p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
int sumOfEncryptedInt(vector<int>& nums) {
auto encrypt = [&](int x) {
int mx = 0, p = 0;
for (; x; x /= 10) {
mx = max(mx, x % 10);
p = p * 10 + 1;
}
return mx * p;
};
int ans = 0;
for (int x : nums) {
ans += encrypt(x);
}
return ans;
}
};
|
3,079
|
Find the Sum of Encrypted Integers
|
Easy
|
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p>
<p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math
|
Go
|
func sumOfEncryptedInt(nums []int) (ans int) {
encrypt := func(x int) int {
mx, p := 0, 0
for ; x > 0; x /= 10 {
mx = max(mx, x%10)
p = p*10 + 1
}
return mx * p
}
for _, x := range nums {
ans += encrypt(x)
}
return
}
|
3,079
|
Find the Sum of Encrypted Integers
|
Easy
|
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p>
<p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int sumOfEncryptedInt(int[] nums) {
int ans = 0;
for (int x : nums) {
ans += encrypt(x);
}
return ans;
}
private int encrypt(int x) {
int mx = 0, p = 0;
for (; x > 0; x /= 10) {
mx = Math.max(mx, x % 10);
p = p * 10 + 1;
}
return mx * p;
}
}
|
3,079
|
Find the Sum of Encrypted Integers
|
Easy
|
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p>
<p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def sumOfEncryptedInt(self, nums: List[int]) -> int:
def encrypt(x: int) -> int:
mx = p = 0
while x:
x, v = divmod(x, 10)
mx = max(mx, v)
p = p * 10 + 1
return mx * p
return sum(encrypt(x) for x in nums)
|
3,079
|
Find the Sum of Encrypted Integers
|
Easy
|
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p>
<p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p>
<p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Math
|
TypeScript
|
function sumOfEncryptedInt(nums: number[]): number {
const encrypt = (x: number): number => {
let [mx, p] = [0, 0];
for (; x > 0; x = Math.floor(x / 10)) {
mx = Math.max(mx, x % 10);
p = p * 10 + 1;
}
return mx * p;
};
return nums.reduce((acc, x) => acc + encrypt(x), 0);
}
|
3,080
|
Mark Elements on Array by Performing Queries
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p>
<p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p>
<p>Initially all elements of the array are <strong>unmarked</strong>.</p>
<p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p>
<ul>
<li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li>
<li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li>
</ul>
<p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>We do the following queries on the array:</p>
<ul>
<li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li>
<li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li>
<li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p>
<p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>m == queries.length</code></li>
<li><code>1 <= m <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= index<sub>i</sub>, k<sub>i</sub> <= n - 1</code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<long long> unmarkedSumArray(vector<int>& nums, vector<vector<int>>& queries) {
int n = nums.size();
long long s = accumulate(nums.begin(), nums.end(), 0LL);
vector<bool> mark(n);
vector<pair<int, int>> arr;
for (int i = 0; i < n; ++i) {
arr.emplace_back(nums[i], i);
}
sort(arr.begin(), arr.end());
vector<long long> ans;
int m = queries.size();
for (int i = 0, j = 0; i < m; ++i) {
int index = queries[i][0], k = queries[i][1];
if (!mark[index]) {
mark[index] = true;
s -= nums[index];
}
for (; k && j < n; ++j) {
if (!mark[arr[j].second]) {
mark[arr[j].second] = true;
s -= arr[j].first;
--k;
}
}
ans.push_back(s);
}
return ans;
}
};
|
3,080
|
Mark Elements on Array by Performing Queries
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p>
<p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p>
<p>Initially all elements of the array are <strong>unmarked</strong>.</p>
<p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p>
<ul>
<li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li>
<li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li>
</ul>
<p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>We do the following queries on the array:</p>
<ul>
<li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li>
<li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li>
<li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p>
<p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>m == queries.length</code></li>
<li><code>1 <= m <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= index<sub>i</sub>, k<sub>i</sub> <= n - 1</code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Go
|
func unmarkedSumArray(nums []int, queries [][]int) []int64 {
n := len(nums)
var s int64
for _, x := range nums {
s += int64(x)
}
mark := make([]bool, n)
arr := make([][2]int, 0, n)
for i, x := range nums {
arr = append(arr, [2]int{x, i})
}
sort.Slice(arr, func(i, j int) bool {
if arr[i][0] == arr[j][0] {
return arr[i][1] < arr[j][1]
}
return arr[i][0] < arr[j][0]
})
ans := make([]int64, len(queries))
j := 0
for i, q := range queries {
index, k := q[0], q[1]
if !mark[index] {
mark[index] = true
s -= int64(nums[index])
}
for ; k > 0 && j < n; j++ {
if !mark[arr[j][1]] {
mark[arr[j][1]] = true
s -= int64(arr[j][0])
k--
}
}
ans[i] = s
}
return ans
}
|
3,080
|
Mark Elements on Array by Performing Queries
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p>
<p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p>
<p>Initially all elements of the array are <strong>unmarked</strong>.</p>
<p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p>
<ul>
<li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li>
<li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li>
</ul>
<p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>We do the following queries on the array:</p>
<ul>
<li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li>
<li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li>
<li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p>
<p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>m == queries.length</code></li>
<li><code>1 <= m <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= index<sub>i</sub>, k<sub>i</sub> <= n - 1</code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public long[] unmarkedSumArray(int[] nums, int[][] queries) {
int n = nums.length;
long s = Arrays.stream(nums).asLongStream().sum();
boolean[] mark = new boolean[n];
int[][] arr = new int[n][0];
for (int i = 0; i < n; ++i) {
arr[i] = new int[] {nums[i], i};
}
Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
int m = queries.length;
long[] ans = new long[m];
for (int i = 0, j = 0; i < m; ++i) {
int index = queries[i][0], k = queries[i][1];
if (!mark[index]) {
mark[index] = true;
s -= nums[index];
}
for (; k > 0 && j < n; ++j) {
if (!mark[arr[j][1]]) {
mark[arr[j][1]] = true;
s -= arr[j][0];
--k;
}
}
ans[i] = s;
}
return ans;
}
}
|
3,080
|
Mark Elements on Array by Performing Queries
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p>
<p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p>
<p>Initially all elements of the array are <strong>unmarked</strong>.</p>
<p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p>
<ul>
<li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li>
<li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li>
</ul>
<p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>We do the following queries on the array:</p>
<ul>
<li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li>
<li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li>
<li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p>
<p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>m == queries.length</code></li>
<li><code>1 <= m <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= index<sub>i</sub>, k<sub>i</sub> <= n - 1</code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def unmarkedSumArray(self, nums: List[int], queries: List[List[int]]) -> List[int]:
n = len(nums)
s = sum(nums)
mark = [False] * n
arr = sorted((x, i) for i, x in enumerate(nums))
j = 0
ans = []
for index, k in queries:
if not mark[index]:
mark[index] = True
s -= nums[index]
while k and j < n:
if not mark[arr[j][1]]:
mark[arr[j][1]] = True
s -= arr[j][0]
k -= 1
j += 1
ans.append(s)
return ans
|
3,080
|
Mark Elements on Array by Performing Queries
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p>
<p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p>
<p>Initially all elements of the array are <strong>unmarked</strong>.</p>
<p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p>
<ul>
<li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li>
<li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li>
</ul>
<p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>We do the following queries on the array:</p>
<ul>
<li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li>
<li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li>
<li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p>
<p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>m == queries.length</code></li>
<li><code>1 <= m <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>0 <= index<sub>i</sub>, k<sub>i</sub> <= n - 1</code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
TypeScript
|
function unmarkedSumArray(nums: number[], queries: number[][]): number[] {
const n = nums.length;
let s = nums.reduce((acc, x) => acc + x, 0);
const mark: boolean[] = Array(n).fill(false);
const arr = nums.map((x, i) => [x, i]);
arr.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]));
let j = 0;
const ans: number[] = [];
for (let [index, k] of queries) {
if (!mark[index]) {
mark[index] = true;
s -= nums[index];
}
for (; k && j < n; ++j) {
if (!mark[arr[j][1]]) {
mark[arr[j][1]] = true;
s -= arr[j][0];
--k;
}
}
ans.push(s);
}
return ans;
}
|
3,081
|
Replace Question Marks in String to Minimize Its Value
|
Medium
|
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>'?'</code>.</p>
<p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code> as the number of characters <strong>equal</strong> to <code>t[i]</code> that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p>
<p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p>
<p>For example, for the string <code>t = "aab"</code>:</p>
<ul>
<li><code>cost(0) = 0</code></li>
<li><code>cost(1) = 1</code></li>
<li><code>cost(2) = 0</code></li>
<li>Hence, the value of <code>"aab"</code> is <code>0 + 1 + 0 = 1</code>.</li>
</ul>
<p>Your task is to <strong>replace all</strong> occurrences of <code>'?'</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p>
<p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>'?'</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "???" </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "abc" </span></p>
<p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>'?'</code> to make <code>s</code> equal to <code>"abc"</code>.</p>
<p>For <code>"abc"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p>
<p>The value of <code>"abc"</code> is <code>0</code>.</p>
<p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>"cba"</code>, <code>"abz"</code>, and, <code>"hey"</code>.</p>
<p>Among all of them, we choose the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "a?a?"</span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">"abac"</span></p>
<p><strong>Explanation: </strong> In this example, the occurrences of <code>'?'</code> can be replaced to make <code>s</code> equal to <code>"abac"</code>.</p>
<p>For <code>"abac"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p>
<p>The value of <code>"abac"</code> is <code>1</code>.</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 a lowercase English letter or <code>'?'</code>.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
string minimizeStringValue(string s) {
int cnt[26]{};
int k = 0;
for (char& c : s) {
if (c == '?') {
++k;
} else {
++cnt[c - 'a'];
}
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
for (int i = 0; i < 26; ++i) {
pq.push({cnt[i], i});
}
vector<int> t(k);
for (int i = 0; i < k; ++i) {
auto [v, c] = pq.top();
pq.pop();
t[i] = c;
pq.push({v + 1, c});
}
sort(t.begin(), t.end());
int j = 0;
for (char& c : s) {
if (c == '?') {
c = t[j++] + 'a';
}
}
return s;
}
};
|
3,081
|
Replace Question Marks in String to Minimize Its Value
|
Medium
|
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>'?'</code>.</p>
<p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code> as the number of characters <strong>equal</strong> to <code>t[i]</code> that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p>
<p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p>
<p>For example, for the string <code>t = "aab"</code>:</p>
<ul>
<li><code>cost(0) = 0</code></li>
<li><code>cost(1) = 1</code></li>
<li><code>cost(2) = 0</code></li>
<li>Hence, the value of <code>"aab"</code> is <code>0 + 1 + 0 = 1</code>.</li>
</ul>
<p>Your task is to <strong>replace all</strong> occurrences of <code>'?'</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p>
<p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>'?'</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "???" </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "abc" </span></p>
<p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>'?'</code> to make <code>s</code> equal to <code>"abc"</code>.</p>
<p>For <code>"abc"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p>
<p>The value of <code>"abc"</code> is <code>0</code>.</p>
<p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>"cba"</code>, <code>"abz"</code>, and, <code>"hey"</code>.</p>
<p>Among all of them, we choose the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "a?a?"</span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">"abac"</span></p>
<p><strong>Explanation: </strong> In this example, the occurrences of <code>'?'</code> can be replaced to make <code>s</code> equal to <code>"abac"</code>.</p>
<p>For <code>"abac"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p>
<p>The value of <code>"abac"</code> is <code>1</code>.</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 a lowercase English letter or <code>'?'</code>.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
|
Go
|
func minimizeStringValue(s string) string {
cnt := [26]int{}
k := 0
for _, c := range s {
if c == '?' {
k++
} else {
cnt[c-'a']++
}
}
pq := hp{}
for i, c := range cnt {
heap.Push(&pq, pair{c, i})
}
t := make([]int, k)
for i := 0; i < k; i++ {
p := heap.Pop(&pq).(pair)
t[i] = p.c
p.v++
heap.Push(&pq, p)
}
sort.Ints(t)
cs := []byte(s)
j := 0
for i, c := range cs {
if c == '?' {
cs[i] = byte(t[j] + 'a')
j++
}
}
return string(cs)
}
type pair struct{ v, c int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].v < h[j].v || h[i].v == h[j].v && h[i].c < h[j].c }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
3,081
|
Replace Question Marks in String to Minimize Its Value
|
Medium
|
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>'?'</code>.</p>
<p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code> as the number of characters <strong>equal</strong> to <code>t[i]</code> that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p>
<p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p>
<p>For example, for the string <code>t = "aab"</code>:</p>
<ul>
<li><code>cost(0) = 0</code></li>
<li><code>cost(1) = 1</code></li>
<li><code>cost(2) = 0</code></li>
<li>Hence, the value of <code>"aab"</code> is <code>0 + 1 + 0 = 1</code>.</li>
</ul>
<p>Your task is to <strong>replace all</strong> occurrences of <code>'?'</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p>
<p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>'?'</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "???" </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "abc" </span></p>
<p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>'?'</code> to make <code>s</code> equal to <code>"abc"</code>.</p>
<p>For <code>"abc"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p>
<p>The value of <code>"abc"</code> is <code>0</code>.</p>
<p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>"cba"</code>, <code>"abz"</code>, and, <code>"hey"</code>.</p>
<p>Among all of them, we choose the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "a?a?"</span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">"abac"</span></p>
<p><strong>Explanation: </strong> In this example, the occurrences of <code>'?'</code> can be replaced to make <code>s</code> equal to <code>"abac"</code>.</p>
<p>For <code>"abac"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p>
<p>The value of <code>"abac"</code> is <code>1</code>.</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 a lowercase English letter or <code>'?'</code>.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public String minimizeStringValue(String s) {
int[] cnt = new int[26];
int n = s.length();
int k = 0;
char[] cs = s.toCharArray();
for (char c : cs) {
if (c == '?') {
++k;
} else {
++cnt[c - 'a'];
}
}
PriorityQueue<int[]> pq
= new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
for (int i = 0; i < 26; ++i) {
pq.offer(new int[] {cnt[i], i});
}
int[] t = new int[k];
for (int j = 0; j < k; ++j) {
int[] p = pq.poll();
t[j] = p[1];
pq.offer(new int[] {p[0] + 1, p[1]});
}
Arrays.sort(t);
for (int i = 0, j = 0; i < n; ++i) {
if (cs[i] == '?') {
cs[i] = (char) (t[j++] + 'a');
}
}
return new String(cs);
}
}
|
3,081
|
Replace Question Marks in String to Minimize Its Value
|
Medium
|
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>'?'</code>.</p>
<p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code> as the number of characters <strong>equal</strong> to <code>t[i]</code> that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p>
<p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p>
<p>For example, for the string <code>t = "aab"</code>:</p>
<ul>
<li><code>cost(0) = 0</code></li>
<li><code>cost(1) = 1</code></li>
<li><code>cost(2) = 0</code></li>
<li>Hence, the value of <code>"aab"</code> is <code>0 + 1 + 0 = 1</code>.</li>
</ul>
<p>Your task is to <strong>replace all</strong> occurrences of <code>'?'</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p>
<p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>'?'</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "???" </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "abc" </span></p>
<p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>'?'</code> to make <code>s</code> equal to <code>"abc"</code>.</p>
<p>For <code>"abc"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p>
<p>The value of <code>"abc"</code> is <code>0</code>.</p>
<p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>"cba"</code>, <code>"abz"</code>, and, <code>"hey"</code>.</p>
<p>Among all of them, we choose the lexicographically smallest.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "a?a?"</span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">"abac"</span></p>
<p><strong>Explanation: </strong> In this example, the occurrences of <code>'?'</code> can be replaced to make <code>s</code> equal to <code>"abac"</code>.</p>
<p>For <code>"abac"</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p>
<p>The value of <code>"abac"</code> is <code>1</code>.</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 a lowercase English letter or <code>'?'</code>.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def minimizeStringValue(self, s: str) -> str:
cnt = Counter(s)
pq = [(cnt[c], c) for c in ascii_lowercase]
heapify(pq)
t = []
for _ in range(s.count("?")):
v, c = pq[0]
t.append(c)
heapreplace(pq, (v + 1, c))
t.sort()
cs = list(s)
j = 0
for i, c in enumerate(s):
if c == "?":
cs[i] = t[j]
j += 1
return "".join(cs)
|
3,082
|
Find the Sum of the Power of All Subsequences
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p>
<p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></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" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>5</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>3</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int sumOfPower(vector<int>& nums, int k) {
const int mod = 1e9 + 7;
int n = nums.size();
int f[n + 1][k + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= k; ++j) {
f[i][j] = (f[i - 1][j] * 2) % mod;
if (j >= nums[i - 1]) {
f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod;
}
}
}
return f[n][k];
}
};
|
3,082
|
Find the Sum of the Power of All Subsequences
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p>
<p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></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" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>5</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>3</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func sumOfPower(nums []int, k int) int {
const mod int = 1e9 + 7
n := len(nums)
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, k+1)
}
f[0][0] = 1
for i := 1; i <= n; i++ {
for j := 0; j <= k; j++ {
f[i][j] = (f[i-1][j] * 2) % mod
if j >= nums[i-1] {
f[i][j] = (f[i][j] + f[i-1][j-nums[i-1]]) % mod
}
}
}
return f[n][k]
}
|
3,082
|
Find the Sum of the Power of All Subsequences
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p>
<p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></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" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>5</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>3</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int sumOfPower(int[] nums, int k) {
final int mod = (int) 1e9 + 7;
int n = nums.length;
int[][] f = new int[n + 1][k + 1];
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= k; ++j) {
f[i][j] = (f[i - 1][j] * 2) % mod;
if (j >= nums[i - 1]) {
f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod;
}
}
}
return f[n][k];
}
}
|
3,082
|
Find the Sum of the Power of All Subsequences
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p>
<p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></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" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>5</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>3</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def sumOfPower(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
n = len(nums)
f = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = 1
for i, x in enumerate(nums, 1):
for j in range(k + 1):
f[i][j] = f[i - 1][j] * 2 % mod
if j >= x:
f[i][j] = (f[i][j] + f[i - 1][j - x]) % mod
return f[n][k]
|
3,082
|
Find the Sum of the Power of All Subsequences
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p>
<p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></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" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>5</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li>
<li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>There are <code>3</code> subsequences of nums with non-zero power:</p>
<ul>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li>
<li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li>
</ul>
<p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function sumOfPower(nums: number[], k: number): number {
const mod = 10 ** 9 + 7;
const n = nums.length;
const f: number[][] = Array.from({ length: n + 1 }, () => Array(k + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= n; ++i) {
for (let j = 0; j <= k; ++j) {
f[i][j] = (f[i - 1][j] * 2) % mod;
if (j >= nums[i - 1]) {
f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod;
}
}
}
return f[n][k];
}
|
3,083
|
Existence of a Substring in a String and Its Reverse
|
Easy
|
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p>
<p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "leetcode"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> Substring <code>"ee"</code> is of length <code>2</code> which is also present in <code>reverse(s) == "edocteel"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcba"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>"ab"</code>, <code>"bc"</code>, <code>"cb"</code>, <code>"ba"</code> are also present in <code>reverse(s) == "abcba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcd"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p>
<p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
C++
|
class Solution {
public:
bool isSubstringPresent(string s) {
bool st[26][26]{};
int n = s.size();
for (int i = 0; i < n - 1; ++i) {
st[s[i + 1] - 'a'][s[i] - 'a'] = true;
}
for (int i = 0; i < n - 1; ++i) {
if (st[s[i] - 'a'][s[i + 1] - 'a']) {
return true;
}
}
return false;
}
};
|
3,083
|
Existence of a Substring in a String and Its Reverse
|
Easy
|
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p>
<p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "leetcode"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> Substring <code>"ee"</code> is of length <code>2</code> which is also present in <code>reverse(s) == "edocteel"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcba"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>"ab"</code>, <code>"bc"</code>, <code>"cb"</code>, <code>"ba"</code> are also present in <code>reverse(s) == "abcba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcd"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p>
<p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Go
|
func isSubstringPresent(s string) bool {
st := [26][26]bool{}
for i := 0; i < len(s)-1; i++ {
st[s[i+1]-'a'][s[i]-'a'] = true
}
for i := 0; i < len(s)-1; i++ {
if st[s[i]-'a'][s[i+1]-'a'] {
return true
}
}
return false
}
|
3,083
|
Existence of a Substring in a String and Its Reverse
|
Easy
|
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p>
<p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "leetcode"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> Substring <code>"ee"</code> is of length <code>2</code> which is also present in <code>reverse(s) == "edocteel"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcba"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>"ab"</code>, <code>"bc"</code>, <code>"cb"</code>, <code>"ba"</code> are also present in <code>reverse(s) == "abcba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcd"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p>
<p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Java
|
class Solution {
public boolean isSubstringPresent(String s) {
boolean[][] st = new boolean[26][26];
int n = s.length();
for (int i = 0; i < n - 1; ++i) {
st[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a'] = true;
}
for (int i = 0; i < n - 1; ++i) {
if (st[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']) {
return true;
}
}
return false;
}
}
|
3,083
|
Existence of a Substring in a String and Its Reverse
|
Easy
|
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p>
<p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "leetcode"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> Substring <code>"ee"</code> is of length <code>2</code> which is also present in <code>reverse(s) == "edocteel"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcba"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>"ab"</code>, <code>"bc"</code>, <code>"cb"</code>, <code>"ba"</code> are also present in <code>reverse(s) == "abcba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcd"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p>
<p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
Python
|
class Solution:
def isSubstringPresent(self, s: str) -> bool:
st = {(a, b) for a, b in pairwise(s[::-1])}
return any((a, b) in st for a, b in pairwise(s))
|
3,083
|
Existence of a Substring in a String and Its Reverse
|
Easy
|
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p>
<p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "leetcode"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> Substring <code>"ee"</code> is of length <code>2</code> which is also present in <code>reverse(s) == "edocteel"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcba"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p>
<p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>"ab"</code>, <code>"bc"</code>, <code>"cb"</code>, <code>"ba"</code> are also present in <code>reverse(s) == "abcba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abcd"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p>
<p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String
|
TypeScript
|
function isSubstringPresent(s: string): boolean {
const st: boolean[][] = Array.from({ length: 26 }, () => Array(26).fill(false));
for (let i = 0; i < s.length - 1; ++i) {
st[s.charCodeAt(i + 1) - 97][s.charCodeAt(i) - 97] = true;
}
for (let i = 0; i < s.length - 1; ++i) {
if (st[s.charCodeAt(i) - 97][s.charCodeAt(i + 1) - 97]) {
return true;
}
}
return false;
}
|
3,084
|
Count Substrings Starting and Ending with Given Character
|
Medium
|
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abada", c = "a"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> Substrings starting and ending with <code>"a"</code> are: <code>"<strong><u>a</u></strong>bada"</code>, <code>"<u><strong>aba</strong></u>da"</code>, <code>"<u><strong>abada</strong></u>"</code>, <code>"ab<u><strong>a</strong></u>da"</code>, <code>"ab<u><strong>ada</strong></u>"</code>, <code>"abad<u><strong>a</strong></u>"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "zzz", c = "z"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>"z"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Math; String; Counting
|
C++
|
class Solution {
public:
long long countSubstrings(string s, char c) {
long long cnt = ranges::count(s, c);
return cnt + cnt * (cnt - 1) / 2;
}
};
|
3,084
|
Count Substrings Starting and Ending with Given Character
|
Medium
|
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abada", c = "a"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> Substrings starting and ending with <code>"a"</code> are: <code>"<strong><u>a</u></strong>bada"</code>, <code>"<u><strong>aba</strong></u>da"</code>, <code>"<u><strong>abada</strong></u>"</code>, <code>"ab<u><strong>a</strong></u>da"</code>, <code>"ab<u><strong>ada</strong></u>"</code>, <code>"abad<u><strong>a</strong></u>"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "zzz", c = "z"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>"z"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Math; String; Counting
|
Go
|
func countSubstrings(s string, c byte) int64 {
cnt := int64(strings.Count(s, string(c)))
return cnt + cnt*(cnt-1)/2
}
|
3,084
|
Count Substrings Starting and Ending with Given Character
|
Medium
|
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abada", c = "a"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> Substrings starting and ending with <code>"a"</code> are: <code>"<strong><u>a</u></strong>bada"</code>, <code>"<u><strong>aba</strong></u>da"</code>, <code>"<u><strong>abada</strong></u>"</code>, <code>"ab<u><strong>a</strong></u>da"</code>, <code>"ab<u><strong>ada</strong></u>"</code>, <code>"abad<u><strong>a</strong></u>"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "zzz", c = "z"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>"z"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Math; String; Counting
|
Java
|
class Solution {
public long countSubstrings(String s, char c) {
long cnt = s.chars().filter(ch -> ch == c).count();
return cnt + cnt * (cnt - 1) / 2;
}
}
|
3,084
|
Count Substrings Starting and Ending with Given Character
|
Medium
|
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abada", c = "a"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> Substrings starting and ending with <code>"a"</code> are: <code>"<strong><u>a</u></strong>bada"</code>, <code>"<u><strong>aba</strong></u>da"</code>, <code>"<u><strong>abada</strong></u>"</code>, <code>"ab<u><strong>a</strong></u>da"</code>, <code>"ab<u><strong>ada</strong></u>"</code>, <code>"abad<u><strong>a</strong></u>"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "zzz", c = "z"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>"z"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Math; String; Counting
|
Python
|
class Solution:
def countSubstrings(self, s: str, c: str) -> int:
cnt = s.count(c)
return cnt + cnt * (cnt - 1) // 2
|
3,084
|
Count Substrings Starting and Ending with Given Character
|
Medium
|
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "abada", c = "a"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> Substrings starting and ending with <code>"a"</code> are: <code>"<strong><u>a</u></strong>bada"</code>, <code>"<u><strong>aba</strong></u>da"</code>, <code>"<u><strong>abada</strong></u>"</code>, <code>"ab<u><strong>a</strong></u>da"</code>, <code>"ab<u><strong>ada</strong></u>"</code>, <code>"abad<u><strong>a</strong></u>"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = "zzz", c = "z"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p>
<p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>"z"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>c</code> consist only of lowercase English letters.</li>
</ul>
|
Math; String; Counting
|
TypeScript
|
function countSubstrings(s: string, c: string): number {
const cnt = s.split('').filter(ch => ch === c).length;
return cnt + Math.floor((cnt * (cnt - 1)) / 2);
}
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
C++
|
class Solution {
public:
int minimumDeletions(string word, int k) {
int freq[26]{};
for (char& c : word) {
++freq[c - 'a'];
}
vector<int> nums;
for (int v : freq) {
if (v) {
nums.push_back(v);
}
}
int n = word.size();
int ans = n;
auto f = [&](int v) {
int ans = 0;
for (int x : nums) {
if (x < v) {
ans += x;
} else if (x > v + k) {
ans += x - v - k;
}
}
return ans;
};
for (int i = 0; i <= n; ++i) {
ans = min(ans, f(i));
}
return ans;
}
};
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
Go
|
func minimumDeletions(word string, k int) int {
freq := [26]int{}
for _, c := range word {
freq[c-'a']++
}
nums := []int{}
for _, v := range freq {
if v > 0 {
nums = append(nums, v)
}
}
f := func(v int) int {
ans := 0
for _, x := range nums {
if x < v {
ans += x
} else if x > v+k {
ans += x - v - k
}
}
return ans
}
ans := len(word)
for i := 0; i <= len(word); i++ {
ans = min(ans, f(i))
}
return ans
}
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
Java
|
class Solution {
private List<Integer> nums = new ArrayList<>();
public int minimumDeletions(String word, int k) {
int[] freq = new int[26];
int n = word.length();
for (int i = 0; i < n; ++i) {
++freq[word.charAt(i) - 'a'];
}
for (int v : freq) {
if (v > 0) {
nums.add(v);
}
}
int ans = n;
for (int i = 0; i <= n; ++i) {
ans = Math.min(ans, f(i, k));
}
return ans;
}
private int f(int v, int k) {
int ans = 0;
for (int x : nums) {
if (x < v) {
ans += x;
} else if (x > v + k) {
ans += x - v - k;
}
}
return ans;
}
}
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
Python
|
class Solution:
def minimumDeletions(self, word: str, k: int) -> int:
def f(v: int) -> int:
ans = 0
for x in nums:
if x < v:
ans += x
elif x > v + k:
ans += x - v - k
return ans
nums = Counter(word).values()
return min(f(v) for v in range(len(word) + 1))
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
Rust
|
impl Solution {
pub fn minimum_deletions(word: String, k: i32) -> i32 {
let mut freq = [0; 26];
for c in word.chars() {
freq[(c as u8 - b'a') as usize] += 1;
}
let mut nums = vec![];
for &v in freq.iter() {
if v > 0 {
nums.push(v);
}
}
let n = word.len() as i32;
let mut ans = n;
for i in 0..=n {
let mut cur = 0;
for &x in nums.iter() {
if x < i {
cur += x;
} else if x > i + k {
cur += x - i - k;
}
}
ans = ans.min(cur);
}
ans
}
}
|
3,085
|
Minimum Deletions to Make String K-Special
|
Medium
|
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p>
<p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| <= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p>
<p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aabcaba", k = 0</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>"a"</code> and <code>1</code> occurrence of <code>"c"</code>. Therefore, <code>word</code> becomes equal to <code>"baba"</code> where <code>freq('a') == freq('b') == 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "dabdcbdcdcd", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"a"</code> and <code>1</code> occurrence of <code>"d"</code>. Therefore, <code>word</code> becomes equal to "bdcbdcdcd" where <code>freq('b') == 2</code>, <code>freq('c') == 3</code>, and <code>freq('d') == 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = "aaabaaa", k = 2</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p>
<p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>"b"</code>. Therefore, <code>word</code> becomes equal to <code>"aaaaaa"</code> where each letter's frequency is now uniformly <code>6</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Hash Table; String; Counting; Sorting
|
TypeScript
|
function minimumDeletions(word: string, k: number): number {
const freq: number[] = Array(26).fill(0);
for (const ch of word) {
++freq[ch.charCodeAt(0) - 97];
}
const nums = freq.filter(x => x > 0);
const f = (v: number): number => {
let ans = 0;
for (const x of nums) {
if (x < v) {
ans += x;
} else if (x > v + k) {
ans += x - v - k;
}
}
return ans;
};
return Math.min(...Array.from({ length: word.length + 1 }, (_, i) => f(i)));
}
|
3,086
|
Minimum Moves to Pick K Ones
|
Hard
|
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p>
<p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p>
<ul>
<li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li>
<li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p>
<ul>
<li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li>
<li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
</ul>
<p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p>
<ul>
<li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
<li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= maxChanges <= 10<sup>5</sup></code></li>
<li><code>maxChanges + sum(nums) >= k</code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sliding Window
|
C++
|
class Solution {
public:
long long minimumMoves(vector<int>& nums, int k, int maxChanges) {
int n = nums.size();
vector<int> cnt(n + 1, 0);
vector<long long> s(n + 1, 0);
for (int i = 1; i <= n; ++i) {
cnt[i] = cnt[i - 1] + nums[i - 1];
s[i] = s[i - 1] + 1LL * i * nums[i - 1];
}
long long ans = LLONG_MAX;
for (int i = 1; i <= n; ++i) {
long long t = 0;
int need = k - nums[i - 1];
for (int j = i - 1; j <= i + 1; j += 2) {
if (need > 0 && 1 <= j && j <= n && nums[j - 1] == 1) {
--need;
++t;
}
}
int c = min(need, maxChanges);
need -= c;
t += c * 2;
if (need <= 0) {
ans = min(ans, t);
continue;
}
int l = 2, r = max(i - 1, n - i);
while (l <= r) {
int mid = (l + r) / 2;
int l1 = max(1, i - mid), r1 = max(0, i - 2);
int l2 = min(n + 1, i + 2), r2 = min(n, i + mid);
int c1 = cnt[r1] - cnt[l1 - 1];
int c2 = cnt[r2] - cnt[l2 - 1];
if (c1 + c2 >= need) {
long long t1 = 1LL * c1 * i - (s[r1] - s[l1 - 1]);
long long t2 = s[r2] - s[l2 - 1] - 1LL * c2 * i;
ans = min(ans, t + t1 + t2);
r = mid - 1;
} else {
l = mid + 1;
}
}
}
return ans;
}
};
|
3,086
|
Minimum Moves to Pick K Ones
|
Hard
|
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p>
<p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p>
<ul>
<li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li>
<li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p>
<ul>
<li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li>
<li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
</ul>
<p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p>
<ul>
<li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
<li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= maxChanges <= 10<sup>5</sup></code></li>
<li><code>maxChanges + sum(nums) >= k</code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sliding Window
|
Go
|
func minimumMoves(nums []int, k int, maxChanges int) int64 {
n := len(nums)
cnt := make([]int, n+1)
s := make([]int, n+1)
for i := 1; i <= n; i++ {
cnt[i] = cnt[i-1] + nums[i-1]
s[i] = s[i-1] + i*nums[i-1]
}
ans := math.MaxInt64
for i := 1; i <= n; i++ {
t := 0
need := k - nums[i-1]
for _, j := range []int{i - 1, i + 1} {
if need > 0 && 1 <= j && j <= n && nums[j-1] == 1 {
need--
t++
}
}
c := min(need, maxChanges)
need -= c
t += c * 2
if need <= 0 {
ans = min(ans, t)
continue
}
l, r := 2, max(i-1, n-i)
for l <= r {
mid := (l + r) >> 1
l1, r1 := max(1, i-mid), max(0, i-2)
l2, r2 := min(n+1, i+2), min(n, i+mid)
c1 := cnt[r1] - cnt[l1-1]
c2 := cnt[r2] - cnt[l2-1]
if c1+c2 >= need {
t1 := c1*i - (s[r1] - s[l1-1])
t2 := s[r2] - s[l2-1] - c2*i
ans = min(ans, t+t1+t2)
r = mid - 1
} else {
l = mid + 1
}
}
}
return int64(ans)
}
|
3,086
|
Minimum Moves to Pick K Ones
|
Hard
|
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p>
<p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p>
<ul>
<li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li>
<li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p>
<ul>
<li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li>
<li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
</ul>
<p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p>
<ul>
<li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
<li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= maxChanges <= 10<sup>5</sup></code></li>
<li><code>maxChanges + sum(nums) >= k</code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sliding Window
|
Java
|
class Solution {
public long minimumMoves(int[] nums, int k, int maxChanges) {
int n = nums.length;
int[] cnt = new int[n + 1];
long[] s = new long[n + 1];
for (int i = 1; i <= n; ++i) {
cnt[i] = cnt[i - 1] + nums[i - 1];
s[i] = s[i - 1] + i * nums[i - 1];
}
long ans = Long.MAX_VALUE;
for (int i = 1; i <= n; ++i) {
long t = 0;
int need = k - nums[i - 1];
for (int j = i - 1; j <= i + 1; j += 2) {
if (need > 0 && 1 <= j && j <= n && nums[j - 1] == 1) {
--need;
++t;
}
}
int c = Math.min(need, maxChanges);
need -= c;
t += c * 2;
if (need <= 0) {
ans = Math.min(ans, t);
continue;
}
int l = 2, r = Math.max(i - 1, n - i);
while (l <= r) {
int mid = (l + r) >> 1;
int l1 = Math.max(1, i - mid), r1 = Math.max(0, i - 2);
int l2 = Math.min(n + 1, i + 2), r2 = Math.min(n, i + mid);
int c1 = cnt[r1] - cnt[l1 - 1];
int c2 = cnt[r2] - cnt[l2 - 1];
if (c1 + c2 >= need) {
long t1 = 1L * c1 * i - (s[r1] - s[l1 - 1]);
long t2 = s[r2] - s[l2 - 1] - 1L * c2 * i;
ans = Math.min(ans, t + t1 + t2);
r = mid - 1;
} else {
l = mid + 1;
}
}
}
return ans;
}
}
|
3,086
|
Minimum Moves to Pick K Ones
|
Hard
|
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p>
<p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p>
<ul>
<li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li>
<li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p>
<ul>
<li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li>
<li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
</ul>
<p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p>
<ul>
<li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
<li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= maxChanges <= 10<sup>5</sup></code></li>
<li><code>maxChanges + sum(nums) >= k</code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sliding Window
|
Python
|
class Solution:
def minimumMoves(self, nums: List[int], k: int, maxChanges: int) -> int:
n = len(nums)
cnt = [0] * (n + 1)
s = [0] * (n + 1)
for i, x in enumerate(nums, 1):
cnt[i] = cnt[i - 1] + x
s[i] = s[i - 1] + i * x
ans = inf
max = lambda x, y: x if x > y else y
min = lambda x, y: x if x < y else y
for i, x in enumerate(nums, 1):
t = 0
need = k - x
for j in (i - 1, i + 1):
if need > 0 and 1 <= j <= n and nums[j - 1] == 1:
need -= 1
t += 1
c = min(need, maxChanges)
need -= c
t += c * 2
if need <= 0:
ans = min(ans, t)
continue
l, r = 2, max(i - 1, n - i)
while l <= r:
mid = (l + r) >> 1
l1, r1 = max(1, i - mid), max(0, i - 2)
l2, r2 = min(n + 1, i + 2), min(n, i + mid)
c1 = cnt[r1] - cnt[l1 - 1]
c2 = cnt[r2] - cnt[l2 - 1]
if c1 + c2 >= need:
t1 = c1 * i - (s[r1] - s[l1 - 1])
t2 = s[r2] - s[l2 - 1] - c2 * i
ans = min(ans, t + t1 + t2)
r = mid - 1
else:
l = mid + 1
return ans
|
3,086
|
Minimum Moves to Pick K Ones
|
Hard
|
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p>
<p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p>
<ul>
<li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li>
<li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p>
<ul>
<li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li>
<li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
<li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li>
</ul>
<p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p>
<p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p>
<ul>
<li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
<li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li>
<li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 1</code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= maxChanges <= 10<sup>5</sup></code></li>
<li><code>maxChanges + sum(nums) >= k</code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sliding Window
|
TypeScript
|
function minimumMoves(nums: number[], k: number, maxChanges: number): number {
const n = nums.length;
const cnt = Array(n + 1).fill(0);
const s = Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
cnt[i] = cnt[i - 1] + nums[i - 1];
s[i] = s[i - 1] + i * nums[i - 1];
}
let ans = Infinity;
for (let i = 1; i <= n; i++) {
let t = 0;
let need = k - nums[i - 1];
for (let j of [i - 1, i + 1]) {
if (need > 0 && 1 <= j && j <= n && nums[j - 1] === 1) {
need--;
t++;
}
}
const c = Math.min(need, maxChanges);
need -= c;
t += c * 2;
if (need <= 0) {
ans = Math.min(ans, t);
continue;
}
let l = 2,
r = Math.max(i - 1, n - i);
while (l <= r) {
const mid = (l + r) >> 1;
const [l1, r1] = [Math.max(1, i - mid), Math.max(0, i - 2)];
const [l2, r2] = [Math.min(n + 1, i + 2), Math.min(n, i + mid)];
const c1 = cnt[r1] - cnt[l1 - 1];
const c2 = cnt[r2] - cnt[l2 - 1];
if (c1 + c2 >= need) {
const t1 = c1 * i - (s[r1] - s[l1 - 1]);
const t2 = s[r2] - s[l2 - 1] - c2 * i;
ans = Math.min(ans, t + t1 + t2);
r = mid - 1;
} else {
l = mid + 1;
}
}
}
return ans;
}
|
3,087
|
Find Trending Hashtags
|
Medium
|
<p>Table: <code>Tweets</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| tweet_id | int |
| tweet_date | date |
| tweet | varchar |
+-------------+---------+
tweet_id is the primary key (column with unique values) for this table.
Each row of this table contains user_id, tweet_id, tweet_date and tweet.
</pre>
<p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong> in <strong>February</strong> <code>2024</code>. Each tweet only contains one hashtag.</p>
<p>Return <em>the result table orderd by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tweets table:</p>
<pre class="example-io">
+---------+----------+----------------------------------------------+------------+
| user_id | tweet_id | tweet | tweet_date |
+---------+----------+----------------------------------------------+------------+
| 135 | 13 | Enjoying a great start to the day! #HappyDay | 2024-02-01 |
| 136 | 14 | Another #HappyDay with good vibes! | 2024-02-03 |
| 137 | 15 | Productivity peaks! #WorkLife | 2024-02-04 |
| 138 | 16 | Exploring new tech frontiers. #TechLife | 2024-02-04 |
| 139 | 17 | Gratitude for today's moments. #HappyDay | 2024-02-05 |
| 140 | 18 | Innovation drives us. #TechLife | 2024-02-07 |
| 141 | 19 | Connecting with nature's serenity. #Nature | 2024-02-09 |
+---------+----------+----------------------------------------------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+--------------+
| hashtag | hashtag_count|
+-----------+--------------+
| #HappyDay | 3 |
| #TechLife | 2 |
| #WorkLife | 1 |
+-----------+--------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li>
<li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li>
<li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li>
</ul>
<p><b>Note:</b> Output table is sorted in descending order by hashtag_count and hashtag respectively.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_trending_hashtags(tweets: pd.DataFrame) -> pd.DataFrame:
tweets = tweets[tweets["tweet_date"].dt.strftime("%Y%m") == "202402"]
tweets["hashtag"] = "#" + tweets["tweet"].str.extract(r"#(\w+)")
hashtag_counts = tweets["hashtag"].value_counts().reset_index()
hashtag_counts.columns = ["hashtag", "hashtag_count"]
hashtag_counts = hashtag_counts.sort_values(
by=["hashtag_count", "hashtag"], ascending=[False, False]
)
top_3_hashtags = hashtag_counts.head(3)
return top_3_hashtags
|
3,087
|
Find Trending Hashtags
|
Medium
|
<p>Table: <code>Tweets</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| tweet_id | int |
| tweet_date | date |
| tweet | varchar |
+-------------+---------+
tweet_id is the primary key (column with unique values) for this table.
Each row of this table contains user_id, tweet_id, tweet_date and tweet.
</pre>
<p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong> in <strong>February</strong> <code>2024</code>. Each tweet only contains one hashtag.</p>
<p>Return <em>the result table orderd by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tweets table:</p>
<pre class="example-io">
+---------+----------+----------------------------------------------+------------+
| user_id | tweet_id | tweet | tweet_date |
+---------+----------+----------------------------------------------+------------+
| 135 | 13 | Enjoying a great start to the day! #HappyDay | 2024-02-01 |
| 136 | 14 | Another #HappyDay with good vibes! | 2024-02-03 |
| 137 | 15 | Productivity peaks! #WorkLife | 2024-02-04 |
| 138 | 16 | Exploring new tech frontiers. #TechLife | 2024-02-04 |
| 139 | 17 | Gratitude for today's moments. #HappyDay | 2024-02-05 |
| 140 | 18 | Innovation drives us. #TechLife | 2024-02-07 |
| 141 | 19 | Connecting with nature's serenity. #Nature | 2024-02-09 |
+---------+----------+----------------------------------------------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+--------------+
| hashtag | hashtag_count|
+-----------+--------------+
| #HappyDay | 3 |
| #TechLife | 2 |
| #WorkLife | 1 |
+-----------+--------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li>
<li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li>
<li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li>
</ul>
<p><b>Note:</b> Output table is sorted in descending order by hashtag_count and hashtag respectively.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
CONCAT('#', SUBSTRING_INDEX(SUBSTRING_INDEX(tweet, '#', -1), ' ', 1)) AS hashtag,
COUNT(1) AS hashtag_count
FROM Tweets
WHERE DATE_FORMAT(tweet_date, '%Y%m') = '202402'
GROUP BY 1
ORDER BY 2 DESC, 1 DESC
LIMIT 3;
|
3,088
|
Make String Anti-palindrome
|
Hard
|
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 <= i < n</code>, <code>s[i] != s[n - i - 1]</code>.</p>
<p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p>
<p>In one operation, you can select two characters from <code>s</code> and swap them.</p>
<p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can't be made into an anti-palindrome, return </em><code>"-1"</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abca"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabc"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabc"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abca"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabb"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabb"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">"-1"</span></p>
<p><strong>Explanation:</strong></p>
<p>You can see that no matter how you rearrange the characters of <code>"cccd"</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s.length % 2 == 0</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String; Counting Sort; Sorting
|
C++
|
class Solution {
public:
string makeAntiPalindrome(string s) {
sort(s.begin(), s.end());
int n = s.length();
int m = n / 2;
if (s[m] == s[m - 1]) {
int i = m;
while (i < n && s[i] == s[i - 1]) {
++i;
}
for (int j = m; j < n && s[j] == s[n - j - 1]; ++i, ++j) {
if (i >= n) {
return "-1";
}
swap(s[i], s[j]);
}
}
return s;
}
};
|
3,088
|
Make String Anti-palindrome
|
Hard
|
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 <= i < n</code>, <code>s[i] != s[n - i - 1]</code>.</p>
<p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p>
<p>In one operation, you can select two characters from <code>s</code> and swap them.</p>
<p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can't be made into an anti-palindrome, return </em><code>"-1"</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abca"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabc"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabc"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abca"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabb"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabb"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">"-1"</span></p>
<p><strong>Explanation:</strong></p>
<p>You can see that no matter how you rearrange the characters of <code>"cccd"</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s.length % 2 == 0</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String; Counting Sort; Sorting
|
Go
|
func makeAntiPalindrome(s string) string {
cs := []byte(s)
sort.Slice(cs, func(i, j int) bool { return cs[i] < cs[j] })
n := len(cs)
m := n / 2
if cs[m] == cs[m-1] {
i := m
for i < n && cs[i] == cs[i-1] {
i++
}
for j := m; j < n && cs[j] == cs[n-j-1]; i, j = i+1, j+1 {
if i >= n {
return "-1"
}
cs[i], cs[j] = cs[j], cs[i]
}
}
return string(cs)
}
|
3,088
|
Make String Anti-palindrome
|
Hard
|
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 <= i < n</code>, <code>s[i] != s[n - i - 1]</code>.</p>
<p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p>
<p>In one operation, you can select two characters from <code>s</code> and swap them.</p>
<p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can't be made into an anti-palindrome, return </em><code>"-1"</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abca"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabc"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabc"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abca"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabb"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabb"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">"-1"</span></p>
<p><strong>Explanation:</strong></p>
<p>You can see that no matter how you rearrange the characters of <code>"cccd"</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s.length % 2 == 0</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String; Counting Sort; Sorting
|
Java
|
class Solution {
public String makeAntiPalindrome(String s) {
char[] cs = s.toCharArray();
Arrays.sort(cs);
int n = cs.length;
int m = n / 2;
if (cs[m] == cs[m - 1]) {
int i = m;
while (i < n && cs[i] == cs[i - 1]) {
++i;
}
for (int j = m; j < n && cs[j] == cs[n - j - 1]; ++i, ++j) {
if (i >= n) {
return "-1";
}
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
}
}
return new String(cs);
}
}
|
3,088
|
Make String Anti-palindrome
|
Hard
|
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 <= i < n</code>, <code>s[i] != s[n - i - 1]</code>.</p>
<p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p>
<p>In one operation, you can select two characters from <code>s</code> and swap them.</p>
<p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can't be made into an anti-palindrome, return </em><code>"-1"</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abca"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabc"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabc"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abca"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabb"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabb"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">"-1"</span></p>
<p><strong>Explanation:</strong></p>
<p>You can see that no matter how you rearrange the characters of <code>"cccd"</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s.length % 2 == 0</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String; Counting Sort; Sorting
|
Python
|
class Solution:
def makeAntiPalindrome(self, s: str) -> str:
cs = sorted(s)
n = len(cs)
m = n // 2
if cs[m] == cs[m - 1]:
i = m
while i < n and cs[i] == cs[i - 1]:
i += 1
j = m
while j < n and cs[j] == cs[n - j - 1]:
if i >= n:
return "-1"
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j + 1
return "".join(cs)
|
3,088
|
Make String Anti-palindrome
|
Hard
|
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 <= i < n</code>, <code>s[i] != s[n - i - 1]</code>.</p>
<p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p>
<p>In one operation, you can select two characters from <code>s</code> and swap them.</p>
<p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can't be made into an anti-palindrome, return </em><code>"-1"</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abca"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabc"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabc"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abca"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">"aabb"</span></p>
<p><strong>Explanation:</strong></p>
<p><code>"aabb"</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>"abba"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "cccd"</span></p>
<p><strong>Output:</strong> <span class="example-io">"-1"</span></p>
<p><strong>Explanation:</strong></p>
<p>You can see that no matter how you rearrange the characters of <code>"cccd"</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s.length % 2 == 0</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String; Counting Sort; Sorting
|
TypeScript
|
function makeAntiPalindrome(s: string): string {
const cs: string[] = s.split('').sort();
const n: number = cs.length;
const m = n >> 1;
if (cs[m] === cs[m - 1]) {
let i = m;
for (; i < n && cs[i] === cs[i - 1]; i++);
for (let j = m; j < n && cs[j] === cs[n - j - 1]; ++i, ++j) {
if (i >= n) {
return '-1';
}
[cs[j], cs[i]] = [cs[i], cs[j]];
}
}
return cs.join('');
}
|
3,089
|
Find Bursty Behavior
|
Medium
|
<p>Table: <code>Posts</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| post_id | int |
| user_id | int |
| post_date | date |
+-------------+---------+
post_id is the primary key (column with unique values) for this table.
Each row of this table contains post_id, user_id, and post_date.
</pre>
<p>Write a solution to find users who demonstrate <strong>bursty behavior</strong> in their posting patterns during February <code>2024</code>. <strong>Bursty behavior</strong> is defined as <strong>any</strong> period of <strong>7</strong> <strong>consecutive</strong> days where a user's posting frequency is <strong>at least twice</strong> to their <strong>average</strong> weekly posting frequency for February <code>2024</code>.</p>
<p><strong>Note:</strong> Only include the dates from February <code>1</code> to February <code>28</code> in your analysis, which means you should count February as having exactly <code>4</code> weeks.</p>
<p>Return <em>the result table orderd by </em><code>user_id</code><em> in </em><strong>ascending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Posts table:</p>
<pre class="example-io">
+---------+---------+------------+
| post_id | user_id | post_date |
+---------+---------+------------+
| 1 | 1 | 2024-02-27 |
| 2 | 5 | 2024-02-06 |
| 3 | 3 | 2024-02-25 |
| 4 | 3 | 2024-02-14 |
| 5 | 3 | 2024-02-06 |
| 6 | 2 | 2024-02-25 |
+---------+---------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------+----------------+------------------+
| user_id | max_7day_posts | avg_weekly_posts |
+---------+----------------+------------------+
| 1 | 1 | 0.2500 |
| 2 | 1 | 0.2500 |
| 5 | 1 | 0.2500 |
+---------+----------------+------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>User 1:</strong> Made only 1 post in February, resulting in an average of 0.25 posts per week and a max of 1 post in any 7-day period.</li>
<li><strong>User 2:</strong> Also made just 1 post, with the same average and max 7-day posting frequency as User 1.</li>
<li><strong>User 5:</strong> Like Users 1 and 2, User 5 made only 1 post throughout February, leading to the same average and max 7-day posting metrics.</li>
<li><strong>User 3:</strong> Although User 3 made more posts than the others (3 posts), they did not reach twice the average weekly posts in their consecutive 7-day window, so they are not listed in the output.</li>
</ul>
<p><b>Note:</b> Output table is ordered by user_id in ascending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_bursty_behavior(posts: pd.DataFrame) -> pd.DataFrame:
# Subquery P
p1 = pd.merge(posts, posts, on="user_id", suffixes=("_1", "_2"))
p1 = p1[
p1["post_date_2"].between(
p1["post_date_1"], p1["post_date_1"] + pd.Timedelta(days=6)
)
]
p1 = p1.groupby(["user_id", "post_id_1"]).size().reset_index(name="cnt")
# Subquery T
t = posts[
(posts["post_date"] >= "2024-02-01") & (posts["post_date"] <= "2024-02-28")
]
t = t.groupby("user_id").size().div(4).reset_index(name="avg_weekly_posts")
# Joining P and T
merged_df = pd.merge(p1, t, on="user_id", how="inner")
# Filtering
filtered_df = merged_df[merged_df["cnt"] >= merged_df["avg_weekly_posts"] * 2]
# Aggregating
result_df = (
filtered_df.groupby("user_id")
.agg({"cnt": "max", "avg_weekly_posts": "first"})
.reset_index()
)
result_df.columns = ["user_id", "max_7day_posts", "avg_weekly_posts"]
# Sorting
result_df.sort_values(by="user_id", inplace=True)
return result_df
|
3,089
|
Find Bursty Behavior
|
Medium
|
<p>Table: <code>Posts</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| post_id | int |
| user_id | int |
| post_date | date |
+-------------+---------+
post_id is the primary key (column with unique values) for this table.
Each row of this table contains post_id, user_id, and post_date.
</pre>
<p>Write a solution to find users who demonstrate <strong>bursty behavior</strong> in their posting patterns during February <code>2024</code>. <strong>Bursty behavior</strong> is defined as <strong>any</strong> period of <strong>7</strong> <strong>consecutive</strong> days where a user's posting frequency is <strong>at least twice</strong> to their <strong>average</strong> weekly posting frequency for February <code>2024</code>.</p>
<p><strong>Note:</strong> Only include the dates from February <code>1</code> to February <code>28</code> in your analysis, which means you should count February as having exactly <code>4</code> weeks.</p>
<p>Return <em>the result table orderd by </em><code>user_id</code><em> in </em><strong>ascending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Posts table:</p>
<pre class="example-io">
+---------+---------+------------+
| post_id | user_id | post_date |
+---------+---------+------------+
| 1 | 1 | 2024-02-27 |
| 2 | 5 | 2024-02-06 |
| 3 | 3 | 2024-02-25 |
| 4 | 3 | 2024-02-14 |
| 5 | 3 | 2024-02-06 |
| 6 | 2 | 2024-02-25 |
+---------+---------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------+----------------+------------------+
| user_id | max_7day_posts | avg_weekly_posts |
+---------+----------------+------------------+
| 1 | 1 | 0.2500 |
| 2 | 1 | 0.2500 |
| 5 | 1 | 0.2500 |
+---------+----------------+------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>User 1:</strong> Made only 1 post in February, resulting in an average of 0.25 posts per week and a max of 1 post in any 7-day period.</li>
<li><strong>User 2:</strong> Also made just 1 post, with the same average and max 7-day posting frequency as User 1.</li>
<li><strong>User 5:</strong> Like Users 1 and 2, User 5 made only 1 post throughout February, leading to the same average and max 7-day posting metrics.</li>
<li><strong>User 3:</strong> Although User 3 made more posts than the others (3 posts), they did not reach twice the average weekly posts in their consecutive 7-day window, so they are not listed in the output.</li>
</ul>
<p><b>Note:</b> Output table is ordered by user_id in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
P AS (
SELECT p1.user_id AS user_id, COUNT(1) AS cnt
FROM
Posts AS p1
JOIN Posts AS p2
ON p1.user_id = p2.user_id
AND p2.post_date BETWEEN p1.post_date AND DATE_ADD(p1.post_date, INTERVAL 6 DAY)
GROUP BY p1.user_id, p1.post_id
),
T AS (
SELECT user_id, COUNT(1) / 4 AS avg_weekly_posts
FROM Posts
WHERE post_date BETWEEN '2024-02-01' AND '2024-02-28'
GROUP BY 1
)
SELECT user_id, MAX(cnt) AS max_7day_posts, avg_weekly_posts
FROM
P
JOIN T USING (user_id)
GROUP BY 1
HAVING max_7day_posts >= avg_weekly_posts * 2
ORDER BY 1;
|
3,090
|
Maximum Length Substring With Two Occurrences
|
Easy
|
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span> such that it contains <em>at most two occurrences</em> of each character.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "bcbbbcba"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 4 and contains at most two occurrences of each character: <code>"bcbb<u>bcba</u>"</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 2 and contains at most two occurrences of each character: <code>"<u>aa</u>aa"</code>.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Sliding Window
|
C++
|
class Solution {
public:
int maximumLengthSubstring(string s) {
int cnt[26]{};
int ans = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
int idx = s[j] - 'a';
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s[i++] - 'a'];
}
ans = max(ans, j - i + 1);
}
return ans;
}
};
|
3,090
|
Maximum Length Substring With Two Occurrences
|
Easy
|
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span> such that it contains <em>at most two occurrences</em> of each character.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "bcbbbcba"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 4 and contains at most two occurrences of each character: <code>"bcbb<u>bcba</u>"</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 2 and contains at most two occurrences of each character: <code>"<u>aa</u>aa"</code>.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Sliding Window
|
Go
|
func maximumLengthSubstring(s string) (ans int) {
cnt := [26]int{}
i := 0
for j, c := range s {
idx := c - 'a'
cnt[idx]++
for cnt[idx] > 2 {
cnt[s[i]-'a']--
i++
}
ans = max(ans, j-i+1)
}
return
}
|
3,090
|
Maximum Length Substring With Two Occurrences
|
Easy
|
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span> such that it contains <em>at most two occurrences</em> of each character.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "bcbbbcba"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 4 and contains at most two occurrences of each character: <code>"bcbb<u>bcba</u>"</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 2 and contains at most two occurrences of each character: <code>"<u>aa</u>aa"</code>.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Sliding Window
|
Java
|
class Solution {
public int maximumLengthSubstring(String s) {
int[] cnt = new int[26];
int ans = 0;
for (int i = 0, j = 0; j < s.length(); ++j) {
int idx = s.charAt(j) - 'a';
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s.charAt(i++) - 'a'];
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
}
|
3,090
|
Maximum Length Substring With Two Occurrences
|
Easy
|
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span> such that it contains <em>at most two occurrences</em> of each character.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "bcbbbcba"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 4 and contains at most two occurrences of each character: <code>"bcbb<u>bcba</u>"</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 2 and contains at most two occurrences of each character: <code>"<u>aa</u>aa"</code>.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Sliding Window
|
Python
|
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
cnt = Counter()
ans = i = 0
for j, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 2:
cnt[s[i]] -= 1
i += 1
ans = max(ans, j - i + 1)
return ans
|
3,090
|
Maximum Length Substring With Two Occurrences
|
Easy
|
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span> such that it contains <em>at most two occurrences</em> of each character.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "bcbbbcba"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 4 and contains at most two occurrences of each character: <code>"bcbb<u>bcba</u>"</code>.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
The following substring has a length of 2 and contains at most two occurrences of each character: <code>"<u>aa</u>aa"</code>.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Sliding Window
|
TypeScript
|
function maximumLengthSubstring(s: string): number {
let ans = 0;
const cnt: number[] = Array(26).fill(0);
for (let i = 0, j = 0; j < s.length; ++j) {
const idx = s[j].charCodeAt(0) - 'a'.charCodeAt(0);
++cnt[idx];
while (cnt[idx] > 2) {
--cnt[s[i++].charCodeAt(0) - 'a'.charCodeAt(0)];
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
C++
|
class Solution {
public:
int minOperations(int k) {
int ans = k;
for (int a = 0; a < k; ++a) {
int x = a + 1;
int b = (k + x - 1) / x - 1;
ans = min(ans, a + b);
}
return ans;
}
};
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
Go
|
func minOperations(k int) int {
ans := k
for a := 0; a < k; a++ {
x := a + 1
b := (k+x-1)/x - 1
ans = min(ans, a+b)
}
return ans
}
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
Java
|
class Solution {
public int minOperations(int k) {
int ans = k;
for (int a = 0; a < k; ++a) {
int x = a + 1;
int b = (k + x - 1) / x - 1;
ans = Math.min(ans, a + b);
}
return ans;
}
}
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
Python
|
class Solution:
def minOperations(self, k: int) -> int:
ans = k
for a in range(k):
x = a + 1
b = (k + x - 1) // x - 1
ans = min(ans, a + b)
return ans
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
Rust
|
impl Solution {
pub fn min_operations(k: i32) -> i32 {
let mut ans = k;
for a in 0..k {
let x = a + 1;
let b = (k + x - 1) / x - 1;
ans = ans.min(a + b);
}
ans
}
}
|
3,091
|
Apply Operations to Make Sum of Array Greater Than or Equal to k
|
Medium
|
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p>
<p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p>
<ul>
<li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li>
<li>Duplicate any element in the array and add it to the end of the array.</li>
</ul>
<p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the following operations on the array <code>nums = [1]</code>:</p>
<ul>
<li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li>
<li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li>
</ul>
<p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br />
The total number of operations performed is <code>3 + 2 = 5</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Math; Enumeration
|
TypeScript
|
function minOperations(k: number): number {
let ans = k;
for (let a = 0; a < k; ++a) {
const x = a + 1;
const b = Math.ceil(k / x) - 1;
ans = Math.min(ans, a + b);
}
return ans;
}
|
3,092
|
Most Frequent IDs
|
Medium
|
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p>
<ul>
<li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li>
<li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li>
</ul>
<p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code> step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</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,1], freq = [3,2,-3,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br />
After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br />
After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br />
After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br />
After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br />
After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == freq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>-10<sup>5</sup> <= freq[i] <= 10<sup>5</sup></code></li>
<li><code>freq[i] != 0</code></li>
<li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li>
</ul>
|
Array; Hash Table; Ordered Set; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<long long> mostFrequentIDs(vector<int>& nums, vector<int>& freq) {
unordered_map<int, long long> cnt;
unordered_map<long long, int> lazy;
int n = nums.size();
vector<long long> ans(n);
priority_queue<long long> pq;
for (int i = 0; i < n; ++i) {
int x = nums[i], f = freq[i];
lazy[cnt[x]]++;
cnt[x] += f;
pq.push(cnt[x]);
while (!pq.empty() && lazy[pq.top()] > 0) {
lazy[pq.top()]--;
pq.pop();
}
ans[i] = pq.empty() ? 0 : pq.top();
}
return ans;
}
};
|
3,092
|
Most Frequent IDs
|
Medium
|
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p>
<ul>
<li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li>
<li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li>
</ul>
<p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code> step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</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,1], freq = [3,2,-3,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br />
After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br />
After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br />
After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br />
After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br />
After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == freq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>-10<sup>5</sup> <= freq[i] <= 10<sup>5</sup></code></li>
<li><code>freq[i] != 0</code></li>
<li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li>
</ul>
|
Array; Hash Table; Ordered Set; Heap (Priority Queue)
|
Go
|
func mostFrequentIDs(nums []int, freq []int) []int64 {
n := len(nums)
cnt := map[int]int{}
lazy := map[int]int{}
ans := make([]int64, n)
pq := hp{}
heap.Init(&pq)
for i, x := range nums {
f := freq[i]
lazy[cnt[x]]++
cnt[x] += f
heap.Push(&pq, cnt[x])
for pq.Len() > 0 && lazy[pq.IntSlice[0]] > 0 {
lazy[pq.IntSlice[0]]--
heap.Pop(&pq)
}
if pq.Len() > 0 {
ans[i] = int64(pq.IntSlice[0])
}
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
3,092
|
Most Frequent IDs
|
Medium
|
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p>
<ul>
<li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li>
<li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li>
</ul>
<p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code> step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</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,1], freq = [3,2,-3,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br />
After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br />
After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br />
After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br />
After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br />
After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == freq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>-10<sup>5</sup> <= freq[i] <= 10<sup>5</sup></code></li>
<li><code>freq[i] != 0</code></li>
<li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li>
</ul>
|
Array; Hash Table; Ordered Set; Heap (Priority Queue)
|
Java
|
class Solution {
public long[] mostFrequentIDs(int[] nums, int[] freq) {
Map<Integer, Long> cnt = new HashMap<>();
Map<Long, Integer> lazy = new HashMap<>();
int n = nums.length;
long[] ans = new long[n];
PriorityQueue<Long> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < n; ++i) {
int x = nums[i], f = freq[i];
lazy.merge(cnt.getOrDefault(x, 0L), 1, Integer::sum);
cnt.merge(x, (long) f, Long::sum);
pq.add(cnt.get(x));
while (!pq.isEmpty() && lazy.getOrDefault(pq.peek(), 0) > 0) {
lazy.merge(pq.poll(), -1, Integer::sum);
}
ans[i] = pq.isEmpty() ? 0 : pq.peek();
}
return ans;
}
}
|
3,092
|
Most Frequent IDs
|
Medium
|
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p>
<ul>
<li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li>
<li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li>
</ul>
<p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code> step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</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,1], freq = [3,2,-3,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br />
After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br />
After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br />
After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br />
After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br />
After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == freq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>-10<sup>5</sup> <= freq[i] <= 10<sup>5</sup></code></li>
<li><code>freq[i] != 0</code></li>
<li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li>
</ul>
|
Array; Hash Table; Ordered Set; Heap (Priority Queue)
|
Python
|
class Solution:
def mostFrequentIDs(self, nums: List[int], freq: List[int]) -> List[int]:
cnt = Counter()
lazy = Counter()
ans = []
pq = []
for x, f in zip(nums, freq):
lazy[cnt[x]] += 1
cnt[x] += f
heappush(pq, -cnt[x])
while pq and lazy[-pq[0]] > 0:
lazy[-pq[0]] -= 1
heappop(pq)
ans.append(0 if not pq else -pq[0])
return ans
|
3,093
|
Longest Common Suffix Queries
|
Hard
|
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p>
<p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p>
<p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "cd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"cd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[1] = "bcd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"bcd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[2] = "xyz"</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>""</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "gh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
<li>For <code>wordsQuery[1] = "acbfgh"</code>, only the string at index 0 shares the longest common suffix <code>"fgh"</code>. Hence it is the answer, even though the string at index 2 is shorter.</li>
<li>For <code>wordsQuery[2] = "acbfegh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= wordsContainer.length, wordsQuery.length <= 10<sup>4</sup></code></li>
<li><code>1 <= wordsContainer[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= wordsQuery[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li>
<li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li>
<li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
<li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String
|
C++
|
class Trie {
private:
const int inf = 1 << 30;
Trie* children[26];
int length = inf;
int idx = inf;
public:
Trie() {
for (int i = 0; i < 26; ++i) {
children[i] = nullptr;
}
}
void insert(string w, int i) {
Trie* node = this;
if (node->length > w.length()) {
node->length = w.length();
node->idx = i;
}
for (int k = w.length() - 1; k >= 0; --k) {
int idx = w[k] - 'a';
if (node->children[idx] == nullptr) {
node->children[idx] = new Trie();
}
node = node->children[idx];
if (node->length > w.length()) {
node->length = w.length();
node->idx = i;
}
}
}
int query(string w) {
Trie* node = this;
for (int k = w.length() - 1; k >= 0; --k) {
int idx = w[k] - 'a';
if (node->children[idx] == nullptr) {
break;
}
node = node->children[idx];
}
return node->idx;
}
};
class Solution {
public:
vector<int> stringIndices(vector<string>& wordsContainer, vector<string>& wordsQuery) {
Trie* trie = new Trie();
for (int i = 0; i < wordsContainer.size(); ++i) {
trie->insert(wordsContainer[i], i);
}
int n = wordsQuery.size();
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ans[i] = trie->query(wordsQuery[i]);
}
return ans;
}
};
|
3,093
|
Longest Common Suffix Queries
|
Hard
|
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p>
<p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p>
<p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "cd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"cd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[1] = "bcd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"bcd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[2] = "xyz"</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>""</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "gh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
<li>For <code>wordsQuery[1] = "acbfgh"</code>, only the string at index 0 shares the longest common suffix <code>"fgh"</code>. Hence it is the answer, even though the string at index 2 is shorter.</li>
<li>For <code>wordsQuery[2] = "acbfegh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= wordsContainer.length, wordsQuery.length <= 10<sup>4</sup></code></li>
<li><code>1 <= wordsContainer[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= wordsQuery[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li>
<li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li>
<li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
<li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String
|
Go
|
const inf = 1 << 30
type Trie struct {
children [26]*Trie
length int
idx int
}
func newTrie() *Trie {
return &Trie{length: inf, idx: inf}
}
func (t *Trie) insert(w string, i int) {
node := t
if node.length > len(w) {
node.length = len(w)
node.idx = i
}
for k := len(w) - 1; k >= 0; k-- {
idx := int(w[k] - 'a')
if node.children[idx] == nil {
node.children[idx] = newTrie()
}
node = node.children[idx]
if node.length > len(w) {
node.length = len(w)
node.idx = i
}
}
}
func (t *Trie) query(w string) int {
node := t
for k := len(w) - 1; k >= 0; k-- {
idx := int(w[k] - 'a')
if node.children[idx] == nil {
break
}
node = node.children[idx]
}
return node.idx
}
func stringIndices(wordsContainer []string, wordsQuery []string) (ans []int) {
trie := newTrie()
for i, w := range wordsContainer {
trie.insert(w, i)
}
for _, w := range wordsQuery {
ans = append(ans, trie.query(w))
}
return
}
|
3,093
|
Longest Common Suffix Queries
|
Hard
|
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p>
<p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p>
<p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "cd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"cd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[1] = "bcd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"bcd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[2] = "xyz"</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>""</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "gh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
<li>For <code>wordsQuery[1] = "acbfgh"</code>, only the string at index 0 shares the longest common suffix <code>"fgh"</code>. Hence it is the answer, even though the string at index 2 is shorter.</li>
<li>For <code>wordsQuery[2] = "acbfegh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= wordsContainer.length, wordsQuery.length <= 10<sup>4</sup></code></li>
<li><code>1 <= wordsContainer[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= wordsQuery[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li>
<li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li>
<li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
<li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String
|
Java
|
class Trie {
private final int inf = 1 << 30;
private Trie[] children = new Trie[26];
private int length = inf;
private int idx = inf;
public void insert(String w, int i) {
Trie node = this;
if (node.length > w.length()) {
node.length = w.length();
node.idx = i;
}
for (int k = w.length() - 1; k >= 0; --k) {
int idx = w.charAt(k) - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
if (node.length > w.length()) {
node.length = w.length();
node.idx = i;
}
}
}
public int query(String w) {
Trie node = this;
for (int k = w.length() - 1; k >= 0; --k) {
int idx = w.charAt(k) - 'a';
if (node.children[idx] == null) {
break;
}
node = node.children[idx];
}
return node.idx;
}
}
class Solution {
public int[] stringIndices(String[] wordsContainer, String[] wordsQuery) {
Trie trie = new Trie();
for (int i = 0; i < wordsContainer.length; ++i) {
trie.insert(wordsContainer[i], i);
}
int n = wordsQuery.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = trie.query(wordsQuery[i]);
}
return ans;
}
}
|
3,093
|
Longest Common Suffix Queries
|
Hard
|
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p>
<p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p>
<p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "cd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"cd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[1] = "bcd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"bcd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[2] = "xyz"</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>""</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "gh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
<li>For <code>wordsQuery[1] = "acbfgh"</code>, only the string at index 0 shares the longest common suffix <code>"fgh"</code>. Hence it is the answer, even though the string at index 2 is shorter.</li>
<li>For <code>wordsQuery[2] = "acbfegh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= wordsContainer.length, wordsQuery.length <= 10<sup>4</sup></code></li>
<li><code>1 <= wordsContainer[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= wordsQuery[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li>
<li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li>
<li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
<li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String
|
Python
|
class Trie:
__slots__ = ("children", "length", "idx")
def __init__(self):
self.children = [None] * 26
self.length = inf
self.idx = inf
def insert(self, w: str, i: int):
node = self
if node.length > len(w):
node.length = len(w)
node.idx = i
for c in w[::-1]:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
if node.length > len(w):
node.length = len(w)
node.idx = i
def query(self, w: str) -> int:
node = self
for c in w[::-1]:
idx = ord(c) - ord("a")
if node.children[idx] is None:
break
node = node.children[idx]
return node.idx
class Solution:
def stringIndices(
self, wordsContainer: List[str], wordsQuery: List[str]
) -> List[int]:
trie = Trie()
for i, w in enumerate(wordsContainer):
trie.insert(w, i)
return [trie.query(w) for w in wordsQuery]
|
3,093
|
Longest Common Suffix Queries
|
Hard
|
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p>
<p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p>
<p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "cd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"cd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[1] = "bcd"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"bcd"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
<li>For <code>wordsQuery[2] = "xyz"</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>""</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at each <code>wordsQuery[i]</code> separately:</p>
<ul>
<li>For <code>wordsQuery[0] = "gh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
<li>For <code>wordsQuery[1] = "acbfgh"</code>, only the string at index 0 shares the longest common suffix <code>"fgh"</code>. Hence it is the answer, even though the string at index 2 is shorter.</li>
<li>For <code>wordsQuery[2] = "acbfegh"</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>"gh"</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= wordsContainer.length, wordsQuery.length <= 10<sup>4</sup></code></li>
<li><code>1 <= wordsContainer[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>1 <= wordsQuery[i].length <= 5 * 10<sup>3</sup></code></li>
<li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li>
<li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li>
<li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
<li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String
|
TypeScript
|
class Trie {
private children: Trie[] = new Array<Trie>(26);
private length: number = Infinity;
private idx: number = Infinity;
public insert(w: string, i: number): void {
let node: Trie = this;
if (node.length > w.length) {
node.length = w.length;
node.idx = i;
}
for (let k: number = w.length - 1; k >= 0; --k) {
let idx: number = w.charCodeAt(k) - 'a'.charCodeAt(0);
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
if (node.length > w.length) {
node.length = w.length;
node.idx = i;
}
}
}
public query(w: string): number {
let node: Trie = this;
for (let k: number = w.length - 1; k >= 0; --k) {
let idx: number = w.charCodeAt(k) - 'a'.charCodeAt(0);
if (node.children[idx] == null) {
break;
}
node = node.children[idx];
}
return node.idx;
}
}
function stringIndices(wordsContainer: string[], wordsQuery: string[]): number[] {
const trie: Trie = new Trie();
for (let i: number = 0; i < wordsContainer.length; ++i) {
trie.insert(wordsContainer[i], i);
}
const n: number = wordsQuery.length;
const ans: number[] = new Array<number>(n);
for (let i: number = 0; i < n; ++i) {
ans[i] = trie.query(wordsQuery[i]);
}
return ans;
}
|
3,094
|
Guess the Number Using Bitwise Questions II
|
Medium
|
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p>
<p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p>
<p><code>commonBits(int num)</code> acts as follows:</p>
<ul>
<li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li>
<li><code>n = n XOR num</code></li>
<li>Return <code>count</code>.</li>
</ul>
<p>Return <em>the number</em> <code>n</code>.</p>
<p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
C++
|
/**
* Definition of commonBits API.
* int commonBits(int num);
*/
class Solution {
public:
int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
int count1 = commonBits(1 << i);
int count2 = commonBits(1 << i);
if (count1 > count2) {
n |= 1 << i;
}
}
return n;
}
};
|
3,094
|
Guess the Number Using Bitwise Questions II
|
Medium
|
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p>
<p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p>
<p><code>commonBits(int num)</code> acts as follows:</p>
<ul>
<li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li>
<li><code>n = n XOR num</code></li>
<li>Return <code>count</code>.</li>
</ul>
<p>Return <em>the number</em> <code>n</code>.</p>
<p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Go
|
/**
* Definition of commonBits API.
* func commonBits(num int) int;
*/
func findNumber() (n int) {
for i := 0; i < 32; i++ {
count1 := commonBits(1 << i)
count2 := commonBits(1 << i)
if count1 > count2 {
n |= 1 << i
}
}
return
}
|
3,094
|
Guess the Number Using Bitwise Questions II
|
Medium
|
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p>
<p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p>
<p><code>commonBits(int num)</code> acts as follows:</p>
<ul>
<li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li>
<li><code>n = n XOR num</code></li>
<li>Return <code>count</code>.</li>
</ul>
<p>Return <em>the number</em> <code>n</code>.</p>
<p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Java
|
/**
* Definition of commonBits API (defined in the parent class Problem).
* int commonBits(int num);
*/
public class Solution extends Problem {
public int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
int count1 = commonBits(1 << i);
int count2 = commonBits(1 << i);
if (count1 > count2) {
n |= 1 << i;
}
}
return n;
}
}
|
3,094
|
Guess the Number Using Bitwise Questions II
|
Medium
|
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p>
<p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p>
<p><code>commonBits(int num)</code> acts as follows:</p>
<ul>
<li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li>
<li><code>n = n XOR num</code></li>
<li>Return <code>count</code>.</li>
</ul>
<p>Return <em>the number</em> <code>n</code>.</p>
<p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Python
|
# Definition of commonBits API.
# def commonBits(num: int) -> int:
class Solution:
def findNumber(self) -> int:
n = 0
for i in range(32):
count1 = commonBits(1 << i)
count2 = commonBits(1 << i)
if count1 > count2:
n |= 1 << i
return n
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
C++
|
class Solution {
public:
int minimumSubarrayLength(vector<int>& nums, int k) {
int n = nums.size();
int cnt[32]{};
int ans = n + 1;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (int h = 0; h < 32; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = min(ans, j - i + 1);
for (int h = 0; h < 32; ++h) {
if ((nums[i] >> h & 1) == 1) {
if (--cnt[h] == 0) {
s ^= 1 << h;
}
}
}
}
}
return ans > n ? -1 : ans;
}
};
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Go
|
func minimumSubarrayLength(nums []int, k int) int {
n := len(nums)
cnt := [32]int{}
ans := n + 1
s, i := 0, 0
for j, x := range nums {
s |= x
for h := 0; h < 32; h++ {
if x>>h&1 == 1 {
cnt[h]++
}
}
for ; s >= k && i <= j; i++ {
ans = min(ans, j-i+1)
for h := 0; h < 32; h++ {
if nums[i]>>h&1 == 1 {
cnt[h]--
if cnt[h] == 0 {
s ^= 1 << h
}
}
}
}
}
if ans == n+1 {
return -1
}
return ans
}
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Java
|
class Solution {
public int minimumSubarrayLength(int[] nums, int k) {
int n = nums.length;
int[] cnt = new int[32];
int ans = n + 1;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (int h = 0; h < 32; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = Math.min(ans, j - i + 1);
for (int h = 0; h < 32; ++h) {
if ((nums[i] >> h & 1) == 1) {
if (--cnt[h] == 0) {
s ^= 1 << h;
}
}
}
}
}
return ans > n ? -1 : ans;
}
}
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Python
|
class Solution:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
cnt = [0] * 32
ans = n + 1
s = i = 0
for j, x in enumerate(nums):
s |= x
for h in range(32):
if x >> h & 1:
cnt[h] += 1
while s >= k and i <= j:
ans = min(ans, j - i + 1)
y = nums[i]
for h in range(32):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
return -1 if ans > n else ans
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Rust
|
impl Solution {
pub fn minimum_subarray_length(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut cnt = vec![0; 32];
let mut ans = n as i32 + 1;
let mut s = 0;
let mut i = 0;
for (j, &x) in nums.iter().enumerate() {
s |= x;
for h in 0..32 {
if (x >> h) & 1 == 1 {
cnt[h] += 1;
}
}
while s >= k && i <= j {
ans = ans.min((j - i + 1) as i32);
let y = nums[i];
for h in 0..32 {
if (y >> h) & 1 == 1 {
cnt[h] -= 1;
if cnt[h] == 0 {
s ^= 1 << h;
}
}
}
i += 1;
}
}
if ans > n as i32 {
-1
} else {
ans
}
}
}
|
3,095
|
Shortest Subarray With OR at Least K I
|
Easy
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
<p>Note that <code>[2]</code> is also a special subarray.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= k < 64</code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
TypeScript
|
function minimumSubarrayLength(nums: number[], k: number): number {
const n = nums.length;
let ans = n + 1;
const cnt: number[] = new Array<number>(32).fill(0);
for (let i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (let h = 0; h < 32; ++h) {
if (((nums[j] >> h) & 1) === 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = Math.min(ans, j - i + 1);
for (let h = 0; h < 32; ++h) {
if (((nums[i] >> h) & 1) === 1 && --cnt[h] === 0) {
s ^= 1 << h;
}
}
}
}
return ans === n + 1 ? -1 : ans;
}
|
3,096
|
Minimum Levels to Gain More Points
|
Medium
|
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p>
<p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p>
<p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p>
<p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p>
<p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p>
<p><strong>Note</strong> that each player must play at least <code>1</code> level.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li>
</ul>
<p>Alice must play a minimum of 1 level to gain more points.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li>
<li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li>
</ul>
<p>Alice must play a minimum of 3 levels to gain more points.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == possible.length <= 10<sup>5</sup></code></li>
<li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Prefix Sum
|
C++
|
class Solution {
public:
int minimumLevels(vector<int>& possible) {
int s = 0;
for (int x : possible) {
s += x == 0 ? -1 : 1;
}
int t = 0;
for (int i = 1; i < possible.size(); ++i) {
t += possible[i - 1] == 0 ? -1 : 1;
if (t > s - t) {
return i;
}
}
return -1;
}
};
|
3,096
|
Minimum Levels to Gain More Points
|
Medium
|
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p>
<p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p>
<p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p>
<p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p>
<p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p>
<p><strong>Note</strong> that each player must play at least <code>1</code> level.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li>
</ul>
<p>Alice must play a minimum of 1 level to gain more points.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li>
<li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li>
</ul>
<p>Alice must play a minimum of 3 levels to gain more points.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == possible.length <= 10<sup>5</sup></code></li>
<li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Prefix Sum
|
Go
|
func minimumLevels(possible []int) int {
s := 0
for _, x := range possible {
if x == 0 {
x = -1
}
s += x
}
t := 0
for i, x := range possible[:len(possible)-1] {
if x == 0 {
x = -1
}
t += x
if t > s-t {
return i + 1
}
}
return -1
}
|
3,096
|
Minimum Levels to Gain More Points
|
Medium
|
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p>
<p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p>
<p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p>
<p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p>
<p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p>
<p><strong>Note</strong> that each player must play at least <code>1</code> level.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li>
</ul>
<p>Alice must play a minimum of 1 level to gain more points.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li>
<li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li>
</ul>
<p>Alice must play a minimum of 3 levels to gain more points.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == possible.length <= 10<sup>5</sup></code></li>
<li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Prefix Sum
|
Java
|
class Solution {
public int minimumLevels(int[] possible) {
int s = 0;
for (int x : possible) {
s += x == 0 ? -1 : 1;
}
int t = 0;
for (int i = 1; i < possible.length; ++i) {
t += possible[i - 1] == 0 ? -1 : 1;
if (t > s - t) {
return i;
}
}
return -1;
}
}
|
3,096
|
Minimum Levels to Gain More Points
|
Medium
|
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p>
<p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p>
<p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p>
<p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p>
<p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p>
<p><strong>Note</strong> that each player must play at least <code>1</code> level.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li>
</ul>
<p>Alice must play a minimum of 1 level to gain more points.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li>
<li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li>
</ul>
<p>Alice must play a minimum of 3 levels to gain more points.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == possible.length <= 10<sup>5</sup></code></li>
<li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Prefix Sum
|
Python
|
class Solution:
def minimumLevels(self, possible: List[int]) -> int:
s = sum(-1 if x == 0 else 1 for x in possible)
t = 0
for i, x in enumerate(possible[:-1], 1):
t += -1 if x == 0 else 1
if t > s - t:
return i
return -1
|
3,096
|
Minimum Levels to Gain More Points
|
Medium
|
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p>
<p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p>
<p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p>
<p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p>
<p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p>
<p><strong>Note</strong> that each player must play at least <code>1</code> level.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li>
</ul>
<p>Alice must play a minimum of 1 level to gain more points.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Let's look at all the levels that Alice can play up to:</p>
<ul>
<li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li>
<li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li>
<li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li>
<li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li>
</ul>
<p>Alice must play a minimum of 3 levels to gain more points.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == possible.length <= 10<sup>5</sup></code></li>
<li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Prefix Sum
|
TypeScript
|
function minimumLevels(possible: number[]): number {
const s = possible.reduce((acc, x) => acc + (x === 0 ? -1 : 1), 0);
let t = 0;
for (let i = 1; i < possible.length; ++i) {
t += possible[i - 1] === 0 ? -1 : 1;
if (t > s - t) {
return i;
}
}
return -1;
}
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
C++
|
class Solution {
public:
int minimumSubarrayLength(vector<int>& nums, int k) {
int n = nums.size();
int cnt[32]{};
int ans = n + 1;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (int h = 0; h < 32; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = min(ans, j - i + 1);
for (int h = 0; h < 32; ++h) {
if ((nums[i] >> h & 1) == 1) {
if (--cnt[h] == 0) {
s ^= 1 << h;
}
}
}
}
}
return ans > n ? -1 : ans;
}
};
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Go
|
func minimumSubarrayLength(nums []int, k int) int {
n := len(nums)
cnt := [32]int{}
ans := n + 1
s, i := 0, 0
for j, x := range nums {
s |= x
for h := 0; h < 32; h++ {
if x>>h&1 == 1 {
cnt[h]++
}
}
for ; s >= k && i <= j; i++ {
ans = min(ans, j-i+1)
for h := 0; h < 32; h++ {
if nums[i]>>h&1 == 1 {
cnt[h]--
if cnt[h] == 0 {
s ^= 1 << h
}
}
}
}
}
if ans == n+1 {
return -1
}
return ans
}
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Java
|
class Solution {
public int minimumSubarrayLength(int[] nums, int k) {
int n = nums.length;
int[] cnt = new int[32];
int ans = n + 1;
for (int i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (int h = 0; h < 32; ++h) {
if ((nums[j] >> h & 1) == 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = Math.min(ans, j - i + 1);
for (int h = 0; h < 32; ++h) {
if ((nums[i] >> h & 1) == 1) {
if (--cnt[h] == 0) {
s ^= 1 << h;
}
}
}
}
}
return ans > n ? -1 : ans;
}
}
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Python
|
class Solution:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
cnt = [0] * 32
ans = n + 1
s = i = 0
for j, x in enumerate(nums):
s |= x
for h in range(32):
if x >> h & 1:
cnt[h] += 1
while s >= k and i <= j:
ans = min(ans, j - i + 1)
y = nums[i]
for h in range(32):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
return -1 if ans > n else ans
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
Rust
|
impl Solution {
pub fn minimum_subarray_length(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut cnt = vec![0; 32];
let mut ans = n as i32 + 1;
let mut s = 0;
let mut i = 0;
for (j, &x) in nums.iter().enumerate() {
s |= x;
for h in 0..32 {
if (x >> h) & 1 == 1 {
cnt[h] += 1;
}
}
while s >= k && i <= j {
ans = ans.min((j - i + 1) as i32);
let y = nums[i];
for h in 0..32 {
if (y >> h) & 1 == 1 {
cnt[h] -= 1;
if cnt[h] == 0 {
s ^= 1 << h;
}
}
}
i += 1;
}
}
if ans > n as i32 {
-1
} else {
ans
}
}
}
|
3,097
|
Shortest Subarray With OR at Least K II
|
Medium
|
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p>
<p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p>
<p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</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], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array; Sliding Window
|
TypeScript
|
function minimumSubarrayLength(nums: number[], k: number): number {
const n = nums.length;
let ans = n + 1;
const cnt: number[] = new Array<number>(32).fill(0);
for (let i = 0, j = 0, s = 0; j < n; ++j) {
s |= nums[j];
for (let h = 0; h < 32; ++h) {
if (((nums[j] >> h) & 1) === 1) {
++cnt[h];
}
}
for (; s >= k && i <= j; ++i) {
ans = Math.min(ans, j - i + 1);
for (let h = 0; h < 32; ++h) {
if (((nums[i] >> h) & 1) === 1 && --cnt[h] === 0) {
s ^= 1 << h;
}
}
}
}
return ans === n + 1 ? -1 : ans;
}
|
3,098
|
Find the Sum of Subsequence Powers
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p>
<p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p>
<p>Since the answer may be 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 = [1,2,3,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subsequence in <code>nums</code> which has length 2 is <code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 50</code></li>
<li><code>-10<sup>8</sup> <= nums[i] <= 10<sup>8</sup> </code></li>
<li><code>2 <= k <= n</code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
C++
|
class Solution {
public:
int sumOfPowers(vector<int>& nums, int k) {
unordered_map<long long, int> f;
const int mod = 1e9 + 7;
int n = nums.size();
sort(nums.begin(), nums.end());
auto dfs = [&](this auto&& dfs, int i, int j, int k, int mi) -> int {
if (i >= n) {
return k == 0 ? mi : 0;
}
if (n - i < k) {
return 0;
}
long long key = (1LL * mi) << 18 | (i << 12) | (j << 6) | k;
if (f.contains(key)) {
return f[key];
}
long long ans = dfs(i + 1, j, k, mi);
if (j == n) {
ans += dfs(i + 1, i, k - 1, mi);
} else {
ans += dfs(i + 1, i, k - 1, min(mi, nums[i] - nums[j]));
}
ans %= mod;
f[key] = ans;
return f[key];
};
return dfs(0, n, k, INT_MAX);
}
};
|
3,098
|
Find the Sum of Subsequence Powers
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p>
<p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p>
<p>Since the answer may be 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 = [1,2,3,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subsequence in <code>nums</code> which has length 2 is <code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 50</code></li>
<li><code>-10<sup>8</sup> <= nums[i] <= 10<sup>8</sup> </code></li>
<li><code>2 <= k <= n</code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Go
|
func sumOfPowers(nums []int, k int) int {
const mod int = 1e9 + 7
sort.Ints(nums)
n := len(nums)
f := map[int]int{}
var dfs func(i, j, k, mi int) int
dfs = func(i, j, k, mi int) int {
if i >= n {
if k == 0 {
return mi
}
return 0
}
if n-i < k {
return 0
}
key := mi<<18 | (i << 12) | (j << 6) | k
if v, ok := f[key]; ok {
return v
}
ans := dfs(i+1, j, k, mi)
if j == n {
ans += dfs(i+1, i, k-1, mi)
} else {
ans += dfs(i+1, i, k-1, min(mi, nums[i]-nums[j]))
}
ans %= mod
f[key] = ans
return ans
}
return dfs(0, n, k, math.MaxInt)
}
|
3,098
|
Find the Sum of Subsequence Powers
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p>
<p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p>
<p>Since the answer may be 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 = [1,2,3,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subsequence in <code>nums</code> which has length 2 is <code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 50</code></li>
<li><code>-10<sup>8</sup> <= nums[i] <= 10<sup>8</sup> </code></li>
<li><code>2 <= k <= n</code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Java
|
class Solution {
private Map<Long, Integer> f = new HashMap<>();
private final int mod = (int) 1e9 + 7;
private int[] nums;
public int sumOfPowers(int[] nums, int k) {
Arrays.sort(nums);
this.nums = nums;
return dfs(0, nums.length, k, Integer.MAX_VALUE);
}
private int dfs(int i, int j, int k, int mi) {
if (i >= nums.length) {
return k == 0 ? mi : 0;
}
if (nums.length - i < k) {
return 0;
}
long key = (1L * mi) << 18 | (i << 12) | (j << 6) | k;
if (f.containsKey(key)) {
return f.get(key);
}
int ans = dfs(i + 1, j, k, mi);
if (j == nums.length) {
ans += dfs(i + 1, i, k - 1, mi);
} else {
ans += dfs(i + 1, i, k - 1, Math.min(mi, nums[i] - nums[j]));
}
ans %= mod;
f.put(key, ans);
return ans;
}
}
|
3,098
|
Find the Sum of Subsequence Powers
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p>
<p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p>
<p>Since the answer may be 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 = [1,2,3,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subsequence in <code>nums</code> which has length 2 is <code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 50</code></li>
<li><code>-10<sup>8</sup> <= nums[i] <= 10<sup>8</sup> </code></li>
<li><code>2 <= k <= n</code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Python
|
class Solution:
def sumOfPowers(self, nums: List[int], k: int) -> int:
@cache
def dfs(i: int, j: int, k: int, mi: int) -> int:
if i >= n:
return mi if k == 0 else 0
if n - i < k:
return 0
ans = dfs(i + 1, j, k, mi)
if j == n:
ans += dfs(i + 1, i, k - 1, mi)
else:
ans += dfs(i + 1, i, k - 1, min(mi, nums[i] - nums[j]))
ans %= mod
return ans
mod = 10**9 + 7
n = len(nums)
nums.sort()
return dfs(0, n, k, inf)
|
3,098
|
Find the Sum of Subsequence Powers
|
Hard
|
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p>
<p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p>
<p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p>
<p>Since the answer may be 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 = [1,2,3,4], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subsequence in <code>nums</code> which has length 2 is <code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 50</code></li>
<li><code>-10<sup>8</sup> <= nums[i] <= 10<sup>8</sup> </code></li>
<li><code>2 <= k <= n</code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
TypeScript
|
function sumOfPowers(nums: number[], k: number): number {
const mod = BigInt(1e9 + 7);
nums.sort((a, b) => a - b);
const n = nums.length;
const f: Map<bigint, bigint> = new Map();
function dfs(i: number, j: number, k: number, mi: number): bigint {
if (i >= n) {
if (k === 0) {
return BigInt(mi);
}
return BigInt(0);
}
if (n - i < k) {
return BigInt(0);
}
const key =
(BigInt(mi) << BigInt(18)) |
(BigInt(i) << BigInt(12)) |
(BigInt(j) << BigInt(6)) |
BigInt(k);
if (f.has(key)) {
return f.get(key)!;
}
let ans = dfs(i + 1, j, k, mi);
if (j === n) {
ans += dfs(i + 1, i, k - 1, mi);
} else {
ans += dfs(i + 1, i, k - 1, Math.min(mi, nums[i] - nums[j]));
}
ans %= mod;
f.set(key, ans);
return ans;
}
return Number(dfs(0, n, k, Number.MAX_SAFE_INTEGER));
}
|
3,099
|
Harshad Number
|
Easy
|
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 18</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x <= 100</code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
int sumOfTheDigitsOfHarshadNumber(int x) {
int s = 0;
for (int y = x; y > 0; y /= 10) {
s += y % 10;
}
return x % s == 0 ? s : -1;
}
};
|
3,099
|
Harshad Number
|
Easy
|
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 18</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x <= 100</code></li>
</ul>
|
Math
|
Go
|
func sumOfTheDigitsOfHarshadNumber(x int) int {
s := 0
for y := x; y > 0; y /= 10 {
s += y % 10
}
if x%s == 0 {
return s
}
return -1
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.