id
int64
1
3.63k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Go
func longestCommonPrefix(s string, t string) int { n, m := len(s), len(t) i, j := 0, 0 rem := false for i < n && j < m { if s[i] != t[j] { if rem { break } rem = true } else { j++ } i++ } return j }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Java
class Solution { public int longestCommonPrefix(String s, String t) { int n = s.length(), m = t.length(); int i = 0, j = 0; boolean rem = false; while (i < n && j < m) { if (s.charAt(i) != t.charAt(j)) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; } }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
JavaScript
/** * @param {string} s * @param {string} t * @return {number} */ var longestCommonPrefix = function (s, t) { const [n, m] = [s.length, t.length]; let [i, j] = [0, 0]; let rem = false; while (i < n && j < m) { if (s[i] !== t[j]) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; };
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Python
class Solution: def longestCommonPrefix(self, s: str, t: str) -> int: n, m = len(s), len(t) i = j = 0 rem = False while i < n and j < m: if s[i] != t[j]: if rem: break rem = True else: j += 1 i += 1 return j
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn longest_common_prefix(s: String, t: String) -> i32 { let (n, m) = (s.len(), t.len()); let (mut i, mut j) = (0, 0); let mut rem = false; while i < n && j < m { if s.as_bytes()[i] != t.as_bytes()[j] { if rem { break; } rem = true; } else { j += 1; } i += 1; } j as i32 } }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
TypeScript
function longestCommonPrefix(s: string, t: string): number { const [n, m] = [s.length, t.length]; let [i, j] = [0, 0]; let rem: boolean = false; while (i < n && j < m) { if (s[i] !== t[j]) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
C++
class Solution { public: bool hasSameDigits(string s) { int n = s.size(); string t = s; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (t[i] - '0' + t[i + 1] - '0') % 10 + '0'; } } return t[0] == t[1]; } };
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Go
func hasSameDigits(s string) bool { t := []byte(s) n := len(t) for k := n - 1; k > 1; k-- { for i := 0; i < k; i++ { t[i] = (t[i]-'0'+t[i+1]-'0')%10 + '0' } } return t[0] == t[1] }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Java
class Solution { public boolean hasSameDigits(String s) { char[] t = s.toCharArray(); int n = t.length; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (char) ((t[i] - '0' + t[i + 1] - '0') % 10 + '0'); } } return t[0] == t[1]; } }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Python
class Solution: def hasSameDigits(self, s: str) -> bool: t = list(map(int, s)) n = len(t) for k in range(n - 1, 1, -1): for i in range(k): t[i] = (t[i] + t[i + 1]) % 10 return t[0] == t[1]
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
TypeScript
function hasSameDigits(s: string): boolean { const t = s.split('').map(Number); const n = t.length; for (let k = n - 1; k > 1; --k) { for (let i = 0; i < k; ++i) { t[i] = (t[i] + t[i + 1]) % 10; } } return t[0] === t[1]; }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
C++
class Solution { public: long long maxSum(vector<vector<int>>& grid, vector<int>& limits, int k) { priority_queue<int, vector<int>, greater<int>> pq; int n = grid.size(); for (int i = 0; i < n; ++i) { vector<int> nums = grid[i]; int limit = limits[i]; ranges::sort(nums); for (int j = 0; j < limit; ++j) { pq.push(nums[nums.size() - j - 1]); if (pq.size() > k) { pq.pop(); } } } long long ans = 0; while (!pq.empty()) { ans += pq.top(); pq.pop(); } return ans; } };
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Go
type MinHeap []int func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] } func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(int)) } func (h *MinHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func maxSum(grid [][]int, limits []int, k int) int64 { pq := &MinHeap{} heap.Init(pq) n := len(grid) for i := 0; i < n; i++ { nums := make([]int, len(grid[i])) copy(nums, grid[i]) limit := limits[i] sort.Ints(nums) for j := 0; j < limit; j++ { heap.Push(pq, nums[len(nums)-j-1]) if pq.Len() > k { heap.Pop(pq) } } } var ans int64 = 0 for pq.Len() > 0 { ans += int64(heap.Pop(pq).(int)) } return ans }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Java
class Solution { public long maxSum(int[][] grid, int[] limits, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); int n = grid.length; for (int i = 0; i < n; ++i) { int[] nums = grid[i]; int limit = limits[i]; Arrays.sort(nums); for (int j = 0; j < limit; ++j) { pq.offer(nums[nums.length - j - 1]); if (pq.size() > k) { pq.poll(); } } } long ans = 0; for (int x : pq) { ans += x; } return ans; } }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Python
class Solution: def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int: pq = [] for nums, limit in zip(grid, limits): nums.sort() for _ in range(limit): heappush(pq, nums.pop()) if len(pq) > k: heappop(pq) return sum(pq)
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
TypeScript
function maxSum(grid: number[][], limits: number[], k: number): number { const pq = new MinPriorityQueue(); const n = grid.length; for (let i = 0; i < n; i++) { const nums = grid[i]; const limit = limits[i]; nums.sort((a, b) => a - b); for (let j = 0; j < limit; j++) { pq.enqueue(nums[nums.length - j - 1]); if (pq.size() > k) { pq.dequeue(); } } } let ans = 0; while (!pq.isEmpty()) { ans += pq.dequeue() as number; } return ans; }
3,465
Find Products with Valid Serial Numbers
Easy
<p>Table: <code>products</code></p> <pre> +--------------+------------+ | Column Name | Type | +--------------+------------+ | product_id | int | | product_name | varchar | | description | varchar | +--------------+------------+ (product_id) is the unique key for this table. Each row in the table represents a product with its unique ID, name, and description. </pre> <p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p> <ul> <li>It starts with the letters <strong>SN</strong>&nbsp;(case-sensitive).</li> <li>Followed by exactly <code>4</code> digits.</li> <li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li> <li>The serial number must be within the description (it may not necessarily start at the beginning).</li> </ul> <p>Return <em>the result table&nbsp;ordered by</em> <code>product_id</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>products table:</p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 3 | Widget C | Product SN1234-56789 is available now | | 4 | Widget D | No serial number here | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Product 1:</strong> Valid serial number SN1234-5678</li> <li><strong>Product 2:</strong> Valid serial number SN9876-1234</li> <li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li> <li><strong>Product 4:</strong> No serial number in the description</li> <li><strong>Product 5:</strong> Valid serial number SN4321-8765</li> </ul> <p>The result table is ordered by product_id in ascending order.</p> </div>
Database
Python
import pandas as pd def find_valid_serial_products(products: pd.DataFrame) -> pd.DataFrame: valid_pattern = r"\bSN[0-9]{4}-[0-9]{4}\b" valid_products = products[ products["description"].str.contains(valid_pattern, regex=True) ] valid_products = valid_products.sort_values(by="product_id") return valid_products
3,465
Find Products with Valid Serial Numbers
Easy
<p>Table: <code>products</code></p> <pre> +--------------+------------+ | Column Name | Type | +--------------+------------+ | product_id | int | | product_name | varchar | | description | varchar | +--------------+------------+ (product_id) is the unique key for this table. Each row in the table represents a product with its unique ID, name, and description. </pre> <p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p> <ul> <li>It starts with the letters <strong>SN</strong>&nbsp;(case-sensitive).</li> <li>Followed by exactly <code>4</code> digits.</li> <li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li> <li>The serial number must be within the description (it may not necessarily start at the beginning).</li> </ul> <p>Return <em>the result table&nbsp;ordered by</em> <code>product_id</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>products table:</p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 3 | Widget C | Product SN1234-56789 is available now | | 4 | Widget D | No serial number here | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Product 1:</strong> Valid serial number SN1234-5678</li> <li><strong>Product 2:</strong> Valid serial number SN9876-1234</li> <li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li> <li><strong>Product 4:</strong> No serial number in the description</li> <li><strong>Product 5:</strong> Valid serial number SN4321-8765</li> </ul> <p>The result table is ordered by product_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT product_id, product_name, description FROM products WHERE description REGEXP '\\bSN[0-9]{4}-[0-9]{4}\\b' ORDER BY 1;
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: long long maxCoins(vector<int>& lane1, vector<int>& lane2) { int n = lane1.size(); long long ans = -1e18; vector<vector<vector<long long>>> f(n, vector<vector<long long>>(2, vector<long long>(3, -1e18))); auto dfs = [&](this auto&& dfs, int i, int j, int k) -> long long { if (i >= n) { return 0LL; } if (f[i][j][k] != -1e18) { return f[i][j][k]; } int x = j == 0 ? lane1[i] : lane2[i]; long long ans = max((long long) x, dfs(i + 1, j, k) + x); if (k > 0) { ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x); ans = max(ans, dfs(i, j ^ 1, k - 1)); } return f[i][j][k] = ans; }; for (int i = 0; i < n; ++i) { ans = max(ans, dfs(i, 0, 2)); } return ans; } };
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxCoins(lane1 []int, lane2 []int) int64 { n := len(lane1) f := make([][2][3]int64, n) for i := range f { for j := range f[i] { for k := range f[i][j] { f[i][j][k] = -1 } } } var dfs func(int, int, int) int64 dfs = func(i, j, k int) int64 { if i >= n { return 0 } if f[i][j][k] != -1 { return f[i][j][k] } x := int64(lane1[i]) if j == 1 { x = int64(lane2[i]) } ans := max(x, dfs(i+1, j, k)+x) if k > 0 { ans = max(ans, dfs(i+1, j^1, k-1)+x) ans = max(ans, dfs(i, j^1, k-1)) } f[i][j][k] = ans return ans } ans := int64(-1e18) for i := range lane1 { ans = max(ans, dfs(i, 0, 2)) } return ans }
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private int n; private int[] lane1; private int[] lane2; private Long[][][] f; public long maxCoins(int[] lane1, int[] lane2) { n = lane1.length; this.lane1 = lane1; this.lane2 = lane2; f = new Long[n][2][3]; long ans = Long.MIN_VALUE; for (int i = 0; i < n; ++i) { ans = Math.max(ans, dfs(i, 0, 2)); } return ans; } private long dfs(int i, int j, int k) { if (i >= n) { return 0; } if (f[i][j][k] != null) { return f[i][j][k]; } int x = j == 0 ? lane1[i] : lane2[i]; long ans = Math.max(x, dfs(i + 1, j, k) + x); if (k > 0) { ans = Math.max(ans, dfs(i + 1, j ^ 1, k - 1) + x); ans = Math.max(ans, dfs(i, j ^ 1, k - 1)); } return f[i][j][k] = ans; } }
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxCoins(self, lane1: List[int], lane2: List[int]) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i >= n: return 0 x = lane1[i] if j == 0 else lane2[i] ans = max(x, dfs(i + 1, j, k) + x) if k > 0: ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x) ans = max(ans, dfs(i, j ^ 1, k - 1)) return ans n = len(lane1) ans = -inf for i in range(n): ans = max(ans, dfs(i, 0, 2)) return ans
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxCoins(lane1: number[], lane2: number[]): number { const n = lane1.length; const NEG_INF = -1e18; const f: number[][][] = Array.from({ length: n }, () => Array.from({ length: 2 }, () => Array(3).fill(NEG_INF)), ); const dfs = (dfs: Function, i: number, j: number, k: number): number => { if (i >= n) { return 0; } if (f[i][j][k] !== NEG_INF) { return f[i][j][k]; } const x = j === 0 ? lane1[i] : lane2[i]; let ans = Math.max(x, dfs(dfs, i + 1, j, k) + x); if (k > 0) { ans = Math.max(ans, dfs(dfs, i + 1, j ^ 1, k - 1) + x); ans = Math.max(ans, dfs(dfs, i, j ^ 1, k - 1)); } f[i][j][k] = ans; return ans; }; let ans = NEG_INF; for (let i = 0; i < n; ++i) { ans = Math.max(ans, dfs(dfs, i, 0, 2)); } return ans; }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
C++
class Solution { public: vector<int> transformArray(vector<int>& nums) { int even = 0; for (int x : nums) { even += (x & 1 ^ 1); } for (int i = 0; i < even; ++i) { nums[i] = 0; } for (int i = even; i < nums.size(); ++i) { nums[i] = 1; } return nums; } };
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Go
func transformArray(nums []int) []int { even := 0 for _, x := range nums { even += x&1 ^ 1 } for i := 0; i < even; i++ { nums[i] = 0 } for i := even; i < len(nums); i++ { nums[i] = 1 } return nums }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Java
class Solution { public int[] transformArray(int[] nums) { int even = 0; for (int x : nums) { even += (x & 1 ^ 1); } for (int i = 0; i < even; ++i) { nums[i] = 0; } for (int i = even; i < nums.length; ++i) { nums[i] = 1; } return nums; } }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Python
class Solution: def transformArray(self, nums: List[int]) -> List[int]: even = sum(x % 2 == 0 for x in nums) for i in range(even): nums[i] = 0 for i in range(even, len(nums)): nums[i] = 1 return nums
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
TypeScript
function transformArray(nums: number[]): number[] { const even = nums.filter(x => x % 2 === 0).length; for (let i = 0; i < even; ++i) { nums[i] = 0; } for (let i = even; i < nums.length; ++i) { nums[i] = 1; } return nums; }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int largestInteger(vector<int>& nums, int k) { if (k == 1) { unordered_map<int, int> cnt; for (int x : nums) { ++cnt[x]; } int ans = -1; for (auto& [x, v] : cnt) { if (v == 1) { ans = max(ans, x); } } return ans; } int n = nums.size(); if (k == n) { return ranges::max(nums); } auto f = [&](int k) -> int { for (int i = 0; i < n; ++i) { if (i != k && nums[i] == nums[k]) { return -1; } } return nums[k]; }; return max(f(0), f(n - 1)); } };
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Go
func largestInteger(nums []int, k int) int { if k == 1 { cnt := make(map[int]int) for _, x := range nums { cnt[x]++ } ans := -1 for x, v := range cnt { if v == 1 { ans = max(ans, x) } } return ans } n := len(nums) if k == n { return slices.Max(nums) } f := func(k int) int { for i, x := range nums { if i != k && x == nums[k] { return -1 } } return nums[k] } return max(f(0), f(n-1)) }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Java
class Solution { private int[] nums; public int largestInteger(int[] nums, int k) { this.nums = nums; if (k == 1) { Map<Integer, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); } int ans = -1; for (var e : cnt.entrySet()) { if (e.getValue() == 1) { ans = Math.max(ans, e.getKey()); } } return ans; } if (k == nums.length) { return Arrays.stream(nums).max().getAsInt(); } return Math.max(f(0), f(nums.length - 1)); } private int f(int k) { for (int i = 0; i < nums.length; ++i) { if (i != k && nums[i] == nums[k]) { return -1; } } return nums[k]; } }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Python
class Solution: def largestInteger(self, nums: List[int], k: int) -> int: def f(k: int) -> int: for i, x in enumerate(nums): if i != k and x == nums[k]: return -1 return nums[k] if k == 1: cnt = Counter(nums) return max((x for x, v in cnt.items() if v == 1), default=-1) if k == len(nums): return max(nums) return max(f(0), f(len(nums) - 1))
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
TypeScript
function largestInteger(nums: number[], k: number): number { if (k === 1) { const cnt = new Map<number, number>(); for (const x of nums) { cnt.set(x, (cnt.get(x) || 0) + 1); } let ans = -1; for (const [x, v] of cnt.entries()) { if (v === 1 && x > ans) { ans = x; } } return ans; } const n = nums.length; if (k === n) { return Math.max(...nums); } const f = (k: number): number => { for (let i = 0; i < n; i++) { if (i !== k && nums[i] === nums[k]) { return -1; } } return nums[k]; }; return Math.max(f(0), f(n - 1)); }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int longestPalindromicSubsequence(string s, int k) { int n = s.size(); vector f(n, vector(n, vector<int>(k + 1, -1))); auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (i > j) { return 0; } if (i == j) { return 1; } if (f[i][j][k] != -1) { return f[i][j][k]; } int res = max(dfs(i + 1, j, k), dfs(i, j - 1, k)); int d = abs(s[i] - s[j]); int t = min(d, 26 - d); if (t <= k) { res = max(res, 2 + dfs(i + 1, j - 1, k - t)); } return f[i][j][k] = res; }; return dfs(0, n - 1, k); } };
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Go
func longestPalindromicSubsequence(s string, k int) int { n := len(s) f := make([][][]int, n) for i := range f { f[i] = make([][]int, n) for j := range f[i] { f[i][j] = make([]int, k+1) for l := range f[i][j] { f[i][j][l] = -1 } } } var dfs func(int, int, int) int dfs = func(i, j, k int) int { if i > j { return 0 } if i == j { return 1 } if f[i][j][k] != -1 { return f[i][j][k] } res := max(dfs(i+1, j, k), dfs(i, j-1, k)) d := abs(int(s[i]) - int(s[j])) t := min(d, 26-d) if t <= k { res = max(res, 2+dfs(i+1, j-1, k-t)) } f[i][j][k] = res return res } return dfs(0, n-1, k) } func abs(x int) int { if x < 0 { return -x } return x }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { private char[] s; private Integer[][][] f; public int longestPalindromicSubsequence(String s, int k) { this.s = s.toCharArray(); int n = s.length(); f = new Integer[n][n][k + 1]; return dfs(0, n - 1, k); } private int dfs(int i, int j, int k) { if (i > j) { return 0; } if (i == j) { return 1; } if (f[i][j][k] != null) { return f[i][j][k]; } int res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k)); int d = Math.abs(s[i] - s[j]); int t = Math.min(d, 26 - d); if (t <= k) { res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t)); } f[i][j][k] = res; return res; } }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def longestPalindromicSubsequence(self, s: str, k: int) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i > j: return 0 if i == j: return 1 res = max(dfs(i + 1, j, k), dfs(i, j - 1, k)) d = abs(s[i] - s[j]) t = min(d, 26 - d) if t <= k: res = max(res, dfs(i + 1, j - 1, k - t) + 2) return res s = list(map(ord, s)) n = len(s) ans = dfs(0, n - 1, k) dfs.cache_clear() return ans
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function longestPalindromicSubsequence(s: string, k: number): number { const n = s.length; const sCodes = s.split('').map(c => c.charCodeAt(0)); const f: number[][][] = Array.from({ length: n }, () => Array.from({ length: n }, () => Array(k + 1).fill(-1)), ); function dfs(i: number, j: number, k: number): number { if (i > j) { return 0; } if (i === j) { return 1; } if (f[i][j][k] !== -1) { return f[i][j][k]; } let res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k)); const d = Math.abs(sCodes[i] - sCodes[j]); const t = Math.min(d, 26 - d); if (t <= k) { res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t)); } return (f[i][j][k] = res); } return dfs(0, n - 1, k); }
3,475
DNA Pattern Recognition
Medium
<p>Table: <code>Samples</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | sample_id | int | | dna_sequence | varchar | | species | varchar | +----------------+---------+ sample_id is the unique key for this table. Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from. </pre> <p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p> <ul> <li>Sequences that <strong>start</strong> with <strong>ATG</strong>&nbsp;(a common <strong>start codon</strong>)</li> <li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong>&nbsp;(<strong>stop codons</strong>)</li> <li>Sequences containing the motif <strong>ATAT</strong>&nbsp;(a simple repeated pattern)</li> <li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong>&nbsp;(like <strong>GGG</strong>&nbsp;or <strong>GGGG</strong>)</li> </ul> <p>Return <em>the result table ordered by&nbsp;</em><em>sample_id in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Samples table:</p> <pre class="example-io"> +-----------+------------------+-----------+ | sample_id | dna_sequence | species | +-----------+------------------+-----------+ | 1 | ATGCTAGCTAGCTAA | Human | | 2 | GGGTCAATCATC | Human | | 3 | ATATATCGTAGCTA | Human | | 4 | ATGGGGTCATCATAA | Mouse | | 5 | TCAGTCAGTCAG | Mouse | | 6 | ATATCGCGCTAG | Zebrafish | | 7 | CGTATGCGTCGTA | Zebrafish | +-----------+------------------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+------------------+-------------+-------------+------------+------------+------------+ | sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg | +-----------+------------------+-------------+-------------+------------+------------+------------+ | 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 | | 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 | | 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 | | 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 | | 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 | | 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 | | 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 | +-----------+------------------+-------------+-------------+------------+------------+------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Sample 1 (ATGCTAGCTAGCTAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 2 (GGGTCAATCATC): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 3 (ATATATCGTAGCTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Contains ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 4 (ATGGGGTCATCATAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 5 (TCAGTCAGTCAG): <ul> <li>Does not match any patterns (all fields = 0)</li> </ul> </li> <li>Sample 6 (ATATCGCGCTAG): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Ends with TAG&nbsp;(has_stop = 1)</li> <li>Starts with ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 7 (CGTATGCGTCGTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, &quot;TAG&quot;, or &quot;TGA&quot; (has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered by sample_id in ascending order</li> <li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li> </ul> </div>
Database
Python
import pandas as pd def analyze_dna_patterns(samples: pd.DataFrame) -> pd.DataFrame: samples["has_start"] = samples["dna_sequence"].str.startswith("ATG").astype(int) samples["has_stop"] = ( samples["dna_sequence"].str.endswith(("TAA", "TAG", "TGA")).astype(int) ) samples["has_atat"] = samples["dna_sequence"].str.contains("ATAT").astype(int) samples["has_ggg"] = samples["dna_sequence"].str.contains("GGG+").astype(int) return samples.sort_values(by="sample_id").reset_index(drop=True)
3,475
DNA Pattern Recognition
Medium
<p>Table: <code>Samples</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | sample_id | int | | dna_sequence | varchar | | species | varchar | +----------------+---------+ sample_id is the unique key for this table. Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from. </pre> <p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p> <ul> <li>Sequences that <strong>start</strong> with <strong>ATG</strong>&nbsp;(a common <strong>start codon</strong>)</li> <li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong>&nbsp;(<strong>stop codons</strong>)</li> <li>Sequences containing the motif <strong>ATAT</strong>&nbsp;(a simple repeated pattern)</li> <li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong>&nbsp;(like <strong>GGG</strong>&nbsp;or <strong>GGGG</strong>)</li> </ul> <p>Return <em>the result table ordered by&nbsp;</em><em>sample_id in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Samples table:</p> <pre class="example-io"> +-----------+------------------+-----------+ | sample_id | dna_sequence | species | +-----------+------------------+-----------+ | 1 | ATGCTAGCTAGCTAA | Human | | 2 | GGGTCAATCATC | Human | | 3 | ATATATCGTAGCTA | Human | | 4 | ATGGGGTCATCATAA | Mouse | | 5 | TCAGTCAGTCAG | Mouse | | 6 | ATATCGCGCTAG | Zebrafish | | 7 | CGTATGCGTCGTA | Zebrafish | +-----------+------------------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+------------------+-------------+-------------+------------+------------+------------+ | sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg | +-----------+------------------+-------------+-------------+------------+------------+------------+ | 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 | | 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 | | 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 | | 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 | | 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 | | 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 | | 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 | +-----------+------------------+-------------+-------------+------------+------------+------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Sample 1 (ATGCTAGCTAGCTAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 2 (GGGTCAATCATC): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 3 (ATATATCGTAGCTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Contains ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 4 (ATGGGGTCATCATAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 5 (TCAGTCAGTCAG): <ul> <li>Does not match any patterns (all fields = 0)</li> </ul> </li> <li>Sample 6 (ATATCGCGCTAG): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Ends with TAG&nbsp;(has_stop = 1)</li> <li>Starts with ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 7 (CGTATGCGTCGTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, &quot;TAG&quot;, or &quot;TGA&quot; (has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered by sample_id in ascending order</li> <li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT sample_id, dna_sequence, species, dna_sequence LIKE 'ATG%' AS has_start, dna_sequence REGEXP 'TAA$|TAG$|TGA$' AS has_stop, dna_sequence LIKE '%ATAT%' AS has_atat, dna_sequence REGEXP 'GGG+' AS has_ggg FROM Samples ORDER BY 1;
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: long long maxProfit(vector<int>& workers, vector<vector<int>>& tasks) { unordered_map<int, priority_queue<int>> d; for (const auto& t : tasks) { d[t[0]].push(t[1]); } long long ans = 0; for (int skill : workers) { if (d.contains(skill)) { auto& pq = d[skill]; ans += pq.top(); pq.pop(); if (pq.empty()) { d.erase(skill); } } } int mx = 0; for (const auto& [_, pq] : d) { mx = max(mx, pq.top()); } ans += mx; return ans; } };
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func maxProfit(workers []int, tasks [][]int) (ans int64) { d := make(map[int]*hp) for _, t := range tasks { skill, profit := t[0], t[1] if _, ok := d[skill]; !ok { d[skill] = &hp{} } d[skill].push(profit) } for _, skill := range workers { if _, ok := d[skill]; !ok { continue } ans += int64(d[skill].pop()) if d[skill].Len() == 0 { delete(d, skill) } } mx := 0 for _, pq := range d { for pq.Len() > 0 { mx = max(mx, pq.pop()) } } ans += int64(mx) return } 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 } func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) }
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public long maxProfit(int[] workers, int[][] tasks) { Map<Integer, PriorityQueue<Integer>> d = new HashMap<>(); for (var t : tasks) { int skill = t[0], profit = t[1]; d.computeIfAbsent(skill, k -> new PriorityQueue<>((a, b) -> b - a)).offer(profit); } long ans = 0; for (int skill : workers) { if (d.containsKey(skill)) { var pq = d.get(skill); ans += pq.poll(); if (pq.isEmpty()) { d.remove(skill); } } } int mx = 0; for (var pq : d.values()) { mx = Math.max(mx, pq.peek()); } ans += mx; return ans; } }
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def maxProfit(self, workers: List[int], tasks: List[List[int]]) -> int: d = defaultdict(SortedList) for skill, profit in tasks: d[skill].add(profit) ans = 0 for skill in workers: if not d[skill]: continue ans += d[skill].pop() mx = 0 for ls in d.values(): if ls: mx = max(mx, ls[-1]) ans += mx return ans
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
TypeScript
function maxProfit(workers: number[], tasks: number[][]): number { const d = new Map(); for (const [skill, profit] of tasks) { if (!d.has(skill)) { d.set(skill, new MaxPriorityQueue()); } d.get(skill).enqueue(profit); } let ans = 0; for (const skill of workers) { const pq = d.get(skill); if (pq) { ans += pq.dequeue(); if (pq.size() === 0) { d.delete(skill); } } } let mx = 0; for (const pq of d.values()) { mx = Math.max(mx, pq.front()); } ans += mx; return ans; }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
C++
class Solution { public: int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) { int n = fruits.size(); vector<bool> vis(n); int ans = n; for (int x : fruits) { for (int i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; } };
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Go
func numOfUnplacedFruits(fruits []int, baskets []int) int { n := len(fruits) ans := n vis := make([]bool, n) for _, x := range fruits { for i, y := range baskets { if y >= x && !vis[i] { vis[i] = true ans-- break } } } return ans }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Java
class Solution { public int numOfUnplacedFruits(int[] fruits, int[] baskets) { int n = fruits.length; boolean[] vis = new boolean[n]; int ans = n; for (int x : fruits) { for (int i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; } }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Python
class Solution: def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int: n = len(fruits) vis = [False] * n ans = n for x in fruits: for i, y in enumerate(baskets): if y >= x and not vis[i]: vis[i] = True ans -= 1 break return ans
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
TypeScript
function numOfUnplacedFruits(fruits: number[], baskets: number[]): number { const n = fruits.length; const vis: boolean[] = Array(n).fill(false); let ans = n; for (const x of fruits) { for (let i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; }
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: vector<long long> findMaxSum(vector<int>& nums1, vector<int>& nums2, int k) { int n = nums1.size(); vector<pair<int, int>> arr(n); for (int i = 0; i < n; ++i) { arr[i] = {nums1[i], i}; } ranges::sort(arr); priority_queue<int, vector<int>, greater<int>> pq; long long s = 0; int j = 0; vector<long long> ans(n); for (int h = 0; h < n; ++h) { auto [x, i] = arr[h]; while (j < h && arr[j].first < x) { int y = nums2[arr[j].second]; pq.push(y); s += y; if (pq.size() > k) { s -= pq.top(); pq.pop(); } ++j; } ans[i] = s; } return ans; } };
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Go
func findMaxSum(nums1 []int, nums2 []int, k int) []int64 { n := len(nums1) arr := make([][2]int, n) for i, x := range nums1 { arr[i] = [2]int{x, i} } ans := make([]int64, n) sort.Slice(arr, func(i, j int) bool { return arr[i][0] < arr[j][0] }) pq := hp{} var s int64 j := 0 for h, e := range arr { x, i := e[0], e[1] for j < h && arr[j][0] < x { y := nums2[arr[j][1]] heap.Push(&pq, y) s += int64(y) if pq.Len() > k { s -= int64(heap.Pop(&pq).(int)) } j++ } ans[i] = s } 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,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Java
class Solution { public long[] findMaxSum(int[] nums1, int[] nums2, int k) { int n = nums1.length; int[][] arr = new int[n][0]; for (int i = 0; i < n; ++i) { arr[i] = new int[] {nums1[i], i}; } Arrays.sort(arr, (a, b) -> a[0] - b[0]); PriorityQueue<Integer> pq = new PriorityQueue<>(); long s = 0; long[] ans = new long[n]; int j = 0; for (int h = 0; h < n; ++h) { int x = arr[h][0], i = arr[h][1]; while (j < h && arr[j][0] < x) { int y = nums2[arr[j][1]]; pq.offer(y); s += y; if (pq.size() > k) { s -= pq.poll(); } ++j; } ans[i] = s; } return ans; } }
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Python
class Solution: def findMaxSum(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: arr = [(x, i) for i, x in enumerate(nums1)] arr.sort() pq = [] s = j = 0 n = len(arr) ans = [0] * n for h, (x, i) in enumerate(arr): while j < h and arr[j][0] < x: y = nums2[arr[j][1]] heappush(pq, y) s += y if len(pq) > k: s -= heappop(pq) j += 1 ans[i] = s return ans
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
TypeScript
function findMaxSum(nums1: number[], nums2: number[], k: number): number[] { const n = nums1.length; const arr = nums1.map((x, i) => [x, i]).sort((a, b) => a[0] - b[0]); const pq = new MinPriorityQueue(); let [s, j] = [0, 0]; const ans: number[] = Array(k).fill(0); for (let h = 0; h < n; ++h) { const [x, i] = arr[h]; while (j < h && arr[j][0] < x) { const y = nums2[arr[j++][1]]; pq.enqueue(y); s += y; if (pq.size() > k) { s -= pq.dequeue(); } } ans[i] = s; } return ans; }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
C++
class Solution { public: long long maxSubarrays(int n, vector<vector<int>>& conflictingPairs) { vector<vector<int>> g(n + 1); for (auto& pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { swap(a, b); } g[a].push_back(b); } vector<long long> cnt(n + 2, 0); long long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = max(add, cnt[b1]); } ans += add; return ans; } };
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Go
func maxSubarrays(n int, conflictingPairs [][]int) (ans int64) { g := make([][]int, n+1) for _, pair := range conflictingPairs { a, b := pair[0], pair[1] if a > b { a, b = b, a } g[a] = append(g[a], b) } cnt := make([]int64, n+2) var add int64 b1, b2 := n+1, n+1 for a := n; a > 0; a-- { for _, b := range g[a] { if b < b1 { b2 = b1 b1 = b } else if b < b2 { b2 = b } } ans += int64(b1 - a) cnt[b1] += int64(b2 - b1) if cnt[b1] > add { add = cnt[b1] } } ans += add return ans }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Java
class Solution { public long maxSubarrays(int n, int[][] conflictingPairs) { List<Integer>[] g = new List[n + 1]; Arrays.setAll(g, k -> new ArrayList<>()); for (int[] pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { int c = a; a = b; b = c; } g[a].add(b); } long[] cnt = new long[n + 2]; long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Python
class Solution: def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int: g = [[] for _ in range(n + 1)] for a, b in conflictingPairs: if a > b: a, b = b, a g[a].append(b) cnt = [0] * (n + 2) ans = add = 0 b1 = b2 = n + 1 for a in range(n, 0, -1): for b in g[a]: if b < b1: b2, b1 = b1, b elif b < b2: b2 = b ans += b1 - a cnt[b1] += b2 - b1 add = max(add, cnt[b1]) ans += add return ans
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Rust
impl Solution { pub fn max_subarrays(n: i32, conflicting_pairs: Vec<Vec<i32>>) -> i64 { let mut g: Vec<Vec<i32>> = vec![vec![]; (n + 1) as usize]; for pair in conflicting_pairs { let mut a = pair[0]; let mut b = pair[1]; if a > b { std::mem::swap(&mut a, &mut b); } g[a as usize].push(b); } let mut cnt: Vec<i64> = vec![0; (n + 2) as usize]; let mut ans = 0i64; let mut add = 0i64; let mut b1 = n + 1; let mut b2 = n + 1; for a in (1..=n).rev() { for &b in &g[a as usize] { if b < b1 { b2 = b1; b1 = b; } else if b < b2 { b2 = b; } } ans += (b1 - a) as i64; cnt[b1 as usize] += (b2 - b1) as i64; add = std::cmp::max(add, cnt[b1 as usize]); } ans += add; ans } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
TypeScript
function maxSubarrays(n: number, conflictingPairs: number[][]): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); for (let [a, b] of conflictingPairs) { if (a > b) { [a, b] = [b, a]; } g[a].push(b); } const cnt: number[] = Array(n + 2).fill(0); let ans = 0, add = 0; let b1 = n + 1, b2 = n + 1; for (let a = n; a > 0; a--) { for (const b of g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
C++
class Solution { public: string applySubstitutions(vector<vector<string>>& replacements, string text) { unordered_map<string, string> d; for (const auto& e : replacements) { d[e[0]] = e[1]; } auto dfs = [&](this auto&& dfs, const string& s) -> string { size_t i = s.find('%'); if (i == string::npos) { return s; } size_t j = s.find('%', i + 1); if (j == string::npos) { return s; } string key = s.substr(i + 1, j - i - 1); string replacement = dfs(d[key]); return s.substr(0, i) + replacement + dfs(s.substr(j + 1)); }; return dfs(text); } };
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Go
func applySubstitutions(replacements [][]string, text string) string { d := make(map[string]string) for _, e := range replacements { d[e[0]] = e[1] } var dfs func(string) string dfs = func(s string) string { i := strings.Index(s, "%") if i == -1 { return s } j := strings.Index(s[i+1:], "%") if j == -1 { return s } j += i + 1 key := s[i+1 : j] replacement := dfs(d[key]) return s[:i] + replacement + dfs(s[j+1:]) } return dfs(text) }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Java
class Solution { private final Map<String, String> d = new HashMap<>(); public String applySubstitutions(List<List<String>> replacements, String text) { for (List<String> e : replacements) { d.put(e.get(0), e.get(1)); } return dfs(text); } private String dfs(String s) { int i = s.indexOf("%"); if (i == -1) { return s; } int j = s.indexOf("%", i + 1); if (j == -1) { return s; } String key = s.substring(i + 1, j); String replacement = dfs(d.getOrDefault(key, "")); return s.substring(0, i) + replacement + dfs(s.substring(j + 1)); } }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Python
class Solution: def applySubstitutions(self, replacements: List[List[str]], text: str) -> str: def dfs(s: str) -> str: i = s.find("%") if i == -1: return s j = s.find("%", i + 1) if j == -1: return s key = s[i + 1 : j] replacement = dfs(d[key]) return s[:i] + replacement + dfs(s[j + 1 :]) d = {s: t for s, t in replacements} return dfs(text)
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
TypeScript
function applySubstitutions(replacements: string[][], text: string): string { const d: Record<string, string> = {}; for (const [key, value] of replacements) { d[key] = value; } const dfs = (s: string): string => { const i = s.indexOf('%'); if (i === -1) { return s; } const j = s.indexOf('%', i + 1); if (j === -1) { return s; } const key = s.slice(i + 1, j); const replacement = dfs(d[key] ?? ''); return s.slice(0, i) + replacement + dfs(s.slice(j + 1)); }; return dfs(text); }
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
Python
import pandas as pd def analyze_organization_hierarchy(employees: pd.DataFrame) -> pd.DataFrame: # Copy the input DataFrame to avoid modifying the original employees = employees.copy() employees["level"] = None # Identify the CEO (level 1) ceo_id = employees.loc[employees["manager_id"].isna(), "employee_id"].values[0] employees.loc[employees["employee_id"] == ceo_id, "level"] = 1 # Recursively compute employee levels def compute_levels(emp_df, level): next_level_ids = emp_df[emp_df["level"] == level]["employee_id"].tolist() if not next_level_ids: return emp_df.loc[emp_df["manager_id"].isin(next_level_ids), "level"] = level + 1 compute_levels(emp_df, level + 1) compute_levels(employees, 1) # Initialize team size and budget dictionaries team_size = {eid: 0 for eid in employees["employee_id"]} budget = { eid: salary for eid, salary in zip(employees["employee_id"], employees["salary"]) } # Compute team size and budget for each employee for eid in sorted(employees["employee_id"], reverse=True): manager_id = employees.loc[ employees["employee_id"] == eid, "manager_id" ].values[0] if pd.notna(manager_id): team_size[manager_id] += team_size[eid] + 1 budget[manager_id] += budget[eid] # Map computed team size and budget to employees DataFrame employees["team_size"] = employees["employee_id"].map(team_size) employees["budget"] = employees["employee_id"].map(budget) # Sort the final result by level (ascending), budget (descending), and employee name (ascending) employees = employees.sort_values( by=["level", "budget", "employee_name"], ascending=[True, False, True] ) return employees[["employee_id", "employee_name", "level", "team_size", "budget"]]
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below WITH RECURSIVE level_cte AS ( SELECT employee_id, manager_id, 1 AS level, salary FROM Employees UNION ALL SELECT a.employee_id, b.manager_id, level + 1, a.salary FROM level_cte a JOIN Employees b ON b.employee_id = a.manager_id ), employee_with_level AS ( SELECT a.employee_id, a.employee_name, a.salary, b.level FROM Employees a, (SELECT employee_id, level FROM level_cte WHERE manager_id IS NULL) b WHERE a.employee_id = b.employee_id ) SELECT a.employee_id, a.employee_name, a.level, COALESCE(b.team_size, 0) AS team_size, a.salary + COALESCE(b.budget, 0) AS budget FROM employee_with_level a LEFT JOIN ( SELECT manager_id AS employee_id, COUNT(*) AS team_size, SUM(salary) AS budget FROM level_cte WHERE manager_id IS NOT NULL GROUP BY manager_id ) b ON a.employee_id = b.employee_id ORDER BY level, budget DESC, employee_name;
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
C++
class Solution { public: int totalNumbers(vector<int>& digits) { unordered_set<int> s; int n = digits.size(); for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.insert(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } };
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Go
func totalNumbers(digits []int) int { s := make(map[int]struct{}) for i, a := range digits { if a%2 == 1 { continue } for j, b := range digits { if i == j { continue } for k, c := range digits { if c == 0 || k == i || k == j { continue } s[c*100+b*10+a] = struct{}{} } } } return len(s) }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Java
class Solution { public int totalNumbers(int[] digits) { Set<Integer> s = new HashSet<>(); int n = digits.length; for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Python
class Solution: def totalNumbers(self, digits: List[int]) -> int: s = set() for i, a in enumerate(digits): if a & 1: continue for j, b in enumerate(digits): if i == j: continue for k, c in enumerate(digits): if c == 0 or k in (i, j): continue s.add(c * 100 + b * 10 + a) return len(s)
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
TypeScript
function totalNumbers(digits: number[]): number { const s = new Set<number>(); const n = digits.length; for (let i = 0; i < n; ++i) { if (digits[i] % 2 === 1) { continue; } for (let j = 0; j < n; ++j) { if (i === j) { continue; } for (let k = 0; k < n; ++k) { if (digits[k] === 0 || k === i || k === j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size; }
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
C++
class Spreadsheet { private: unordered_map<string, int> d; public: Spreadsheet(int rows) {} void setCell(string cell, int value) { d[cell] = value; } void resetCell(string cell) { d.erase(cell); } int getValue(string formula) { int ans = 0; stringstream ss(formula.substr(1)); string cell; while (getline(ss, cell, '+')) { if (isdigit(cell[0])) { ans += stoi(cell); } else { ans += d.count(cell) ? d[cell] : 0; } } return ans; } }; /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet* obj = new Spreadsheet(rows); * obj->setCell(cell,value); * obj->resetCell(cell); * int param_3 = obj->getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Go
type Spreadsheet struct { d map[string]int } func Constructor(rows int) Spreadsheet { return Spreadsheet{d: make(map[string]int)} } func (this *Spreadsheet) SetCell(cell string, value int) { this.d[cell] = value } func (this *Spreadsheet) ResetCell(cell string) { delete(this.d, cell) } func (this *Spreadsheet) GetValue(formula string) int { ans := 0 cells := strings.Split(formula[1:], "+") for _, cell := range cells { if val, err := strconv.Atoi(cell); err == nil { ans += val } else { ans += this.d[cell] } } return ans } /** * Your Spreadsheet object will be instantiated and called as such: * obj := Constructor(rows); * obj.SetCell(cell,value); * obj.ResetCell(cell); * param_3 := obj.GetValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Java
class Spreadsheet { private Map<String, Integer> d = new HashMap<>(); public Spreadsheet(int rows) { } public void setCell(String cell, int value) { d.put(cell, value); } public void resetCell(String cell) { d.remove(cell); } public int getValue(String formula) { int ans = 0; for (String cell : formula.substring(1).split("\\+")) { ans += Character.isDigit(cell.charAt(0)) ? Integer.parseInt(cell) : d.getOrDefault(cell, 0); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet obj = new Spreadsheet(rows); * obj.setCell(cell,value); * obj.resetCell(cell); * int param_3 = obj.getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Python
class Spreadsheet: def __init__(self, rows: int): self.d = {} def setCell(self, cell: str, value: int) -> None: self.d[cell] = value def resetCell(self, cell: str) -> None: self.d.pop(cell, None) def getValue(self, formula: str) -> int: ans = 0 for cell in formula[1:].split("+"): ans += int(cell) if cell[0].isdigit() else self.d.get(cell, 0) return ans # Your Spreadsheet object will be instantiated and called as such: # obj = Spreadsheet(rows) # obj.setCell(cell,value) # obj.resetCell(cell) # param_3 = obj.getValue(formula)
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
TypeScript
class Spreadsheet { private d: Map<string, number>; constructor(rows: number) { this.d = new Map<string, number>(); } setCell(cell: string, value: number): void { this.d.set(cell, value); } resetCell(cell: string): void { this.d.delete(cell); } getValue(formula: string): number { let ans = 0; const cells = formula.slice(1).split('+'); for (const cell of cells) { ans += isNaN(Number(cell)) ? this.d.get(cell) || 0 : Number(cell); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * var obj = new Spreadsheet(rows) * obj.setCell(cell,value) * obj.resetCell(cell) * var param_3 = obj.getValue(formula) */
3,485
Longest Common Prefix of K Strings After Removal
Hard
<p>You are given an array of strings <code>words</code> and an integer <code>k</code>.</p> <p>For each index <code>i</code> in the range <code>[0, words.length - 1]</code>, find the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> among any <code>k</code> strings (selected at <strong>distinct indices</strong>) from the remaining array after removing the <code>i<sup>th</sup></code> element.</p> <p>Return an array <code>answer</code>, where <code>answer[i]</code> is the answer for <code>i<sup>th</sup></code> element. If removing the <code>i<sup>th</sup></code> element leaves the array with fewer than <code>k</code> strings, <code>answer[i]</code> is 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;jump&quot;,&quot;run&quot;,&quot;run&quot;,&quot;jump&quot;,&quot;run&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4,4,3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing index 0 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;run&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 1 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 2 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 3 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 4 (&quot;run&quot;): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;jump&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;dog&quot;,&quot;racer&quot;,&quot;car&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing any index results in an answer of 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>4</sup></code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>The sum of <code>words[i].length</code> is smaller than or equal <code>10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
C++
class Solution { public: struct TrieNode { int count = 0; int depth = 0; int children[26] = {0}; }; class SegmentTree { public: int n; vector<int> tree; vector<int>& globalCount; SegmentTree(int n, vector<int>& globalCount) : n(n) , globalCount(globalCount) { tree.assign(4 * (n + 1), -1); build(1, 1, n); } void build(int idx, int l, int r) { if (l == r) { tree[idx] = globalCount[l] > 0 ? l : -1; return; } int mid = (l + r) / 2; build(idx * 2, l, mid); build(idx * 2 + 1, mid + 1, r); tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1]); } void update(int idx, int l, int r, int pos, int newVal) { if (l == r) { tree[idx] = newVal > 0 ? l : -1; return; } int mid = (l + r) / 2; if (pos <= mid) update(idx * 2, l, mid, pos, newVal); else update(idx * 2 + 1, mid + 1, r, pos, newVal); tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1]); } int query() { return tree[1]; } }; vector<int> longestCommonPrefix(vector<string>& words, int k) { int n = words.size(); vector<int> ans(n, 0); if (n - 1 < k) return ans; vector<TrieNode> trie(1); for (const string& word : words) { int cur = 0; for (char c : word) { int idx = c - 'a'; if (trie[cur].children[idx] == 0) { trie[cur].children[idx] = trie.size(); trie.push_back({0, trie[cur].depth + 1}); } cur = trie[cur].children[idx]; trie[cur].count++; } } int maxDepth = 0; for (int i = 1; i < trie.size(); ++i) { if (trie[i].count >= k) { maxDepth = max(maxDepth, trie[i].depth); } } vector<int> globalCount(maxDepth + 1, 0); for (int i = 1; i < trie.size(); ++i) { if (trie[i].count >= k && trie[i].depth <= maxDepth) { globalCount[trie[i].depth]++; } } vector<vector<int>> fragileList(n); for (int i = 0; i < n; ++i) { int cur = 0; for (char c : words[i]) { int idx = c - 'a'; cur = trie[cur].children[idx]; if (trie[cur].count == k) { fragileList[i].push_back(trie[cur].depth); } } } int segSize = maxDepth; if (segSize >= 1) { SegmentTree segTree(segSize, globalCount); for (int i = 0; i < n; ++i) { if (n - 1 < k) { ans[i] = 0; } else { for (int d : fragileList[i]) { segTree.update(1, 1, segSize, d, globalCount[d] - 1); } int res = segTree.query(); ans[i] = res == -1 ? 0 : res; for (int d : fragileList[i]) { segTree.update(1, 1, segSize, d, globalCount[d]); } } } } return ans; } };
3,485
Longest Common Prefix of K Strings After Removal
Hard
<p>You are given an array of strings <code>words</code> and an integer <code>k</code>.</p> <p>For each index <code>i</code> in the range <code>[0, words.length - 1]</code>, find the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> among any <code>k</code> strings (selected at <strong>distinct indices</strong>) from the remaining array after removing the <code>i<sup>th</sup></code> element.</p> <p>Return an array <code>answer</code>, where <code>answer[i]</code> is the answer for <code>i<sup>th</sup></code> element. If removing the <code>i<sup>th</sup></code> element leaves the array with fewer than <code>k</code> strings, <code>answer[i]</code> is 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;jump&quot;,&quot;run&quot;,&quot;run&quot;,&quot;jump&quot;,&quot;run&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4,4,3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing index 0 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;run&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 1 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 2 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 3 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 4 (&quot;run&quot;): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;jump&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;dog&quot;,&quot;racer&quot;,&quot;car&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing any index results in an answer of 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>4</sup></code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>The sum of <code>words[i].length</code> is smaller than or equal <code>10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
Java
class Solution { static class TrieNode { int count = 0; int depth = 0; int[] children = new int[26]; TrieNode() { for (int i = 0; i < 26; ++i) children[i] = -1; } } static class SegmentTree { int n; int[] tree; int[] globalCount; SegmentTree(int n, int[] globalCount) { this.n = n; this.globalCount = globalCount; this.tree = new int[4 * (n + 1)]; for (int i = 0; i < tree.length; i++) tree[i] = -1; build(1, 1, n); } void build(int idx, int l, int r) { if (l == r) { tree[idx] = globalCount[l] > 0 ? l : -1; return; } int mid = (l + r) / 2; build(idx * 2, l, mid); build(idx * 2 + 1, mid + 1, r); tree[idx] = Math.max(tree[idx * 2], tree[idx * 2 + 1]); } void update(int idx, int l, int r, int pos, int newVal) { if (l == r) { tree[idx] = newVal > 0 ? l : -1; return; } int mid = (l + r) / 2; if (pos <= mid) { update(idx * 2, l, mid, pos, newVal); } else { update(idx * 2 + 1, mid + 1, r, pos, newVal); } tree[idx] = Math.max(tree[idx * 2], tree[idx * 2 + 1]); } int query() { return tree[1]; } } public int[] longestCommonPrefix(String[] words, int k) { int n = words.length; int[] ans = new int[n]; if (n - 1 < k) return ans; ArrayList<TrieNode> trie = new ArrayList<>(); trie.add(new TrieNode()); for (String word : words) { int cur = 0; for (char c : word.toCharArray()) { int idx = c - 'a'; if (trie.get(cur).children[idx] == -1) { trie.get(cur).children[idx] = trie.size(); TrieNode node = new TrieNode(); node.depth = trie.get(cur).depth + 1; trie.add(node); } cur = trie.get(cur).children[idx]; trie.get(cur).count++; } } int maxDepth = 0; for (int i = 1; i < trie.size(); ++i) { if (trie.get(i).count >= k) { maxDepth = Math.max(maxDepth, trie.get(i).depth); } } int[] globalCount = new int[maxDepth + 1]; for (int i = 1; i < trie.size(); ++i) { TrieNode node = trie.get(i); if (node.count >= k && node.depth <= maxDepth) { globalCount[node.depth]++; } } List<List<Integer>> fragileList = new ArrayList<>(); for (int i = 0; i < n; ++i) { fragileList.add(new ArrayList<>()); } for (int i = 0; i < n; ++i) { int cur = 0; for (char c : words[i].toCharArray()) { int idx = c - 'a'; cur = trie.get(cur).children[idx]; if (trie.get(cur).count == k) { fragileList.get(i).add(trie.get(cur).depth); } } } int segSize = maxDepth; if (segSize >= 1) { SegmentTree segTree = new SegmentTree(segSize, globalCount); for (int i = 0; i < n; ++i) { if (n - 1 < k) { ans[i] = 0; } else { for (int d : fragileList.get(i)) { segTree.update(1, 1, segSize, d, globalCount[d] - 1); } int res = segTree.query(); ans[i] = res == -1 ? 0 : res; for (int d : fragileList.get(i)) { segTree.update(1, 1, segSize, d, globalCount[d]); } } } } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
C++
class Solution { public: int maxSum(vector<int>& nums) { int mx = ranges::max(nums); if (mx <= 0) { return mx; } unordered_set<int> s; int ans = 0; for (int x : nums) { if (x < 0 || s.contains(x)) { continue; } ans += x; s.insert(x); } return ans; } };
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
C#
public class Solution { public int MaxSum(int[] nums) { int mx = nums.Max(); if (mx <= 0) { return mx; } HashSet<int> s = new HashSet<int>(); int ans = 0; foreach (int x in nums) { if (x < 0 || s.Contains(x)) { continue; } ans += x; s.Add(x); } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Go
func maxSum(nums []int) (ans int) { mx := slices.Max(nums) if mx <= 0 { return mx } s := make(map[int]bool) for _, x := range nums { if x < 0 || s[x] { continue } ans += x s[x] = true } return }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Java
class Solution { public int maxSum(int[] nums) { int mx = Arrays.stream(nums).max().getAsInt(); if (mx <= 0) { return mx; } boolean[] s = new boolean[201]; int ans = 0; for (int x : nums) { if (x < 0 || s[x]) { continue; } ans += x; s[x] = true; } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Python
class Solution: def maxSum(self, nums: List[int]) -> int: mx = max(nums) if mx <= 0: return mx ans = 0 s = set() for x in nums: if x < 0 or x in s: continue ans += x s.add(x) return ans
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Rust
use std::collections::HashSet; impl Solution { pub fn max_sum(nums: Vec<i32>) -> i32 { let mx = *nums.iter().max().unwrap_or(&0); if mx <= 0 { return mx; } let mut s = HashSet::new(); let mut ans = 0; for &x in &nums { if x < 0 || s.contains(&x) { continue; } ans += x; s.insert(x); } ans } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</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,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
TypeScript
function maxSum(nums: number[]): number { const mx = Math.max(...nums); if (mx <= 0) { return mx; } const s = new Set<number>(); let ans: number = 0; for (const x of nums) { if (x < 0 || s.has(x)) { continue; } ans += x; s.add(x); } return ans; }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
C++
class Solution { public: vector<int> solveQueries(vector<int>& nums, vector<int>& queries) { int n = nums.size(); int m = n * 2; vector<int> d(m, m); unordered_map<int, int> left; for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.count(x)) { d[i] = min(d[i], i - left[x]); } left[x] = i; } unordered_map<int, int> right; for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.count(x)) { d[i] = min(d[i], right[x] - i); } right[x] = i; } for (int i = 0; i < n; i++) { d[i] = min(d[i], d[i + n]); } vector<int> ans; for (int query : queries) { ans.push_back(d[query] >= n ? -1 : d[query]); } return ans; } };
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
C#
public class Solution { public IList<int> SolveQueries(int[] nums, int[] queries) { int n = nums.Length; int m = n * 2; int[] d = new int[m]; Array.Fill(d, m); Dictionary<int, int> left = new Dictionary<int, int>(); for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.ContainsKey(x)) { d[i] = Math.Min(d[i], i - left[x]); } left[x] = i; } Dictionary<int, int> right = new Dictionary<int, int>(); for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.ContainsKey(x)) { d[i] = Math.Min(d[i], right[x] - i); } right[x] = i; } for (int i = 0; i < n; i++) { d[i] = Math.Min(d[i], d[i + n]); } List<int> ans = new List<int>(); foreach (int query in queries) { ans.Add(d[query] >= n ? -1 : d[query]); } return ans; } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Go
func solveQueries(nums []int, queries []int) []int { n := len(nums) m := n * 2 d := make([]int, m) for i := range d { d[i] = m } left := make(map[int]int) for i := 0; i < m; i++ { x := nums[i%n] if idx, exists := left[x]; exists { d[i] = min(d[i], i-idx) } left[x] = i } right := make(map[int]int) for i := m - 1; i >= 0; i-- { x := nums[i%n] if idx, exists := right[x]; exists { d[i] = min(d[i], idx-i) } right[x] = i } for i := 0; i < n; i++ { d[i] = min(d[i], d[i+n]) } ans := make([]int, len(queries)) for i, query := range queries { if d[query] >= n { ans[i] = -1 } else { ans[i] = d[query] } } return ans }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Java
class Solution { public List<Integer> solveQueries(int[] nums, int[] queries) { int n = nums.length; int m = n * 2; int[] d = new int[m]; Arrays.fill(d, m); Map<Integer, Integer> left = new HashMap<>(); for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.containsKey(x)) { d[i] = Math.min(d[i], i - left.get(x)); } left.put(x, i); } Map<Integer, Integer> right = new HashMap<>(); for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.containsKey(x)) { d[i] = Math.min(d[i], right.get(x) - i); } right.put(x, i); } for (int i = 0; i < n; i++) { d[i] = Math.min(d[i], d[i + n]); } List<Integer> ans = new ArrayList<>(); for (int query : queries) { ans.add(d[query] >= n ? -1 : d[query]); } return ans; } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Python
class Solution: def solveQueries(self, nums: List[int], queries: List[int]) -> List[int]: n = len(nums) m = n << 1 d = [m] * m left = {} for i in range(m): x = nums[i % n] if x in left: d[i] = min(d[i], i - left[x]) left[x] = i right = {} for i in range(m - 1, -1, -1): x = nums[i % n] if x in right: d[i] = min(d[i], right[x] - i) right[x] = i for i in range(n): d[i] = min(d[i], d[i + n]) return [-1 if d[i] >= n else d[i] for i in queries]
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Rust
use std::collections::HashMap; impl Solution { pub fn solve_queries(nums: Vec<i32>, queries: Vec<i32>) -> Vec<i32> { let n = nums.len(); let m = n * 2; let mut d = vec![m as i32; m]; let mut left = HashMap::new(); for i in 0..m { let x = nums[i % n]; if let Some(&l) = left.get(&x) { d[i] = d[i].min((i - l) as i32); } left.insert(x, i); } let mut right = HashMap::new(); for i in (0..m).rev() { let x = nums[i % n]; if let Some(&r) = right.get(&x) { d[i] = d[i].min((r - i) as i32); } right.insert(x, i); } for i in 0..n { d[i] = d[i].min(d[i + n]); } queries .iter() .map(|&query| { if d[query as usize] >= n as i32 { -1 } else { d[query as usize] } }) .collect() } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
TypeScript
function solveQueries(nums: number[], queries: number[]): number[] { const n = nums.length; const m = n * 2; const d: number[] = Array(m).fill(m); const left = new Map<number, number>(); for (let i = 0; i < m; i++) { const x = nums[i % n]; if (left.has(x)) { d[i] = Math.min(d[i], i - left.get(x)!); } left.set(x, i); } const right = new Map<number, number>(); for (let i = m - 1; i >= 0; i--) { const x = nums[i % n]; if (right.has(x)) { d[i] = Math.min(d[i], right.get(x)! - i); } right.set(x, i); } for (let i = 0; i < n; i++) { d[i] = Math.min(d[i], d[i + n]); } return queries.map(query => (d[query] >= n ? -1 : d[query])); }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
C++
#include <ranges> class Solution { public: bool phonePrefix(vector<string>& numbers) { ranges::sort(numbers, [](const string& a, const string& b) { return a.size() < b.size(); }); for (int i = 0; i < numbers.size(); i++) { if (ranges::any_of(numbers | views::take(i), [&](const string& t) { return numbers[i].starts_with(t); })) { return false; } } return true; } };
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Go
func phonePrefix(numbers []string) bool { sort.Slice(numbers, func(i, j int) bool { return len(numbers[i]) < len(numbers[j]) }) for i, s := range numbers { for _, t := range numbers[:i] { if strings.HasPrefix(s, t) { return false } } } return true }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Java
class Solution { public boolean phonePrefix(String[] numbers) { Arrays.sort(numbers, (a, b) -> Integer.compare(a.length(), b.length())); for (int i = 0; i < numbers.length; i++) { String s = numbers[i]; for (int j = 0; j < i; j++) { if (s.startsWith(numbers[j])) { return false; } } } return true; } }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Python
class Solution: def phonePrefix(self, numbers: List[str]) -> bool: numbers.sort(key=len) for i, s in enumerate(numbers): if any(s.startswith(t) for t in numbers[:i]): return False return True
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
TypeScript
function phonePrefix(numbers: string[]): boolean { numbers.sort((a, b) => a.length - b.length); for (let i = 0; i < numbers.length; i++) { for (let j = 0; j < i; j++) { if (numbers[i].startsWith(numbers[j])) { return false; } } } return true; }
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
C++
class Solution { public: int maxContainers(int n, int w, int maxWeight) { return min(n * n * w, maxWeight) / w; } };