id
int64 1
3.65k
| 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,042 |
Count Prefix and Suffix Pairs I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
C++
|
class Solution {
public:
int countPrefixSuffixPairs(vector<string>& words) {
int ans = 0;
int n = words.size();
for (int i = 0; i < n; ++i) {
string s = words[i];
for (int j = i + 1; j < n; ++j) {
string t = words[j];
if (t.find(s) == 0 && t.rfind(s) == t.length() - s.length()) {
++ans;
}
}
}
return ans;
}
};
|
3,042 |
Count Prefix and Suffix Pairs I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Go
|
func countPrefixSuffixPairs(words []string) (ans int) {
for i, s := range words {
for _, t := range words[i+1:] {
if strings.HasPrefix(t, s) && strings.HasSuffix(t, s) {
ans++
}
}
}
return
}
|
3,042 |
Count Prefix and Suffix Pairs I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Java
|
class Solution {
public int countPrefixSuffixPairs(String[] words) {
int ans = 0;
int n = words.length;
for (int i = 0; i < n; ++i) {
String s = words[i];
for (int j = i + 1; j < n; ++j) {
String t = words[j];
if (t.startsWith(s) && t.endsWith(s)) {
++ans;
}
}
}
return ans;
}
}
|
3,042 |
Count Prefix and Suffix Pairs I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Python
|
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
ans = 0
for i, s in enumerate(words):
for t in words[i + 1 :]:
ans += t.endswith(s) and t.startswith(s)
return ans
|
3,042 |
Count Prefix and Suffix Pairs I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
TypeScript
|
function countPrefixSuffixPairs(words: string[]): number {
let ans = 0;
for (let i = 0; i < words.length; ++i) {
const s = words[i];
for (const t of words.slice(i + 1)) {
if (t.startsWith(s) && t.endsWith(s)) {
++ans;
}
}
}
return ans;
}
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
C++
|
class Solution {
public:
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
unordered_set<int> s;
for (int x : arr1) {
for (; x; x /= 10) {
s.insert(x);
}
}
int ans = 0;
for (int x : arr2) {
for (; x; x /= 10) {
if (s.count(x)) {
ans = max(ans, (int) log10(x) + 1);
break;
}
}
}
return ans;
}
};
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
Go
|
func longestCommonPrefix(arr1 []int, arr2 []int) (ans int) {
s := map[int]bool{}
for _, x := range arr1 {
for ; x > 0; x /= 10 {
s[x] = true
}
}
for _, x := range arr2 {
for ; x > 0; x /= 10 {
if s[x] {
ans = max(ans, int(math.Log10(float64(x)))+1)
break
}
}
}
return
}
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
Java
|
class Solution {
public int longestCommonPrefix(int[] arr1, int[] arr2) {
Set<Integer> s = new HashSet<>();
for (int x : arr1) {
for (; x > 0; x /= 10) {
s.add(x);
}
}
int ans = 0;
for (int x : arr2) {
for (; x > 0; x /= 10) {
if (s.contains(x)) {
ans = Math.max(ans, String.valueOf(x).length());
break;
}
}
}
return ans;
}
}
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
JavaScript
|
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
var longestCommonPrefix = function (arr1, arr2) {
const s = new Set();
for (let x of arr1) {
for (; x; x = Math.floor(x / 10)) {
s.add(x);
}
}
let ans = 0;
for (let x of arr2) {
for (; x; x = Math.floor(x / 10)) {
if (s.has(x)) {
ans = Math.max(ans, Math.floor(Math.log10(x)) + 1);
}
}
}
return ans;
};
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
Python
|
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
s = set()
for x in arr1:
while x:
s.add(x)
x //= 10
ans = 0
for x in arr2:
while x:
if x in s:
ans = max(ans, len(str(x)))
break
x //= 10
return ans
|
3,043 |
Find the Length of the Longest Common Prefix
|
Medium
|
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p>
<p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p>
<p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p>
<p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p>
<p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= arr1.length, arr2.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= arr1[i], arr2[i] <= 10<sup>8</sup></code></li>
</ul>
|
Trie; Array; Hash Table; String
|
TypeScript
|
function longestCommonPrefix(arr1: number[], arr2: number[]): number {
const s: Set<number> = new Set<number>();
for (let x of arr1) {
for (; x; x = Math.floor(x / 10)) {
s.add(x);
}
}
let ans: number = 0;
for (let x of arr2) {
for (; x; x = Math.floor(x / 10)) {
if (s.has(x)) {
ans = Math.max(ans, Math.floor(Math.log10(x)) + 1);
}
}
}
return ans;
}
|
3,044 |
Most Frequent Prime
|
Medium
|
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p>
<ul>
<li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li>
<li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li>
<li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li>
</ul>
<p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p>
<p><strong>Note:</strong> It is invalid to change the direction during the move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong>
<pre>
<strong>
Input:</strong> mat = [[1,1],[9,9],[1,1]]
<strong>Output:</strong> 19
<strong>Explanation:</strong>
From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:
East: [11], South-East: [19], South: [19,191].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].
The most frequent prime number among all the created numbers is 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[7]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]]
<strong>Output:</strong> 97
<strong>Explanation:</strong>
Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].
Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].
Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].
Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].
The most frequent prime number among all the created numbers is 97.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 6</code></li>
<li><code>1 <= mat[i][j] <= 9</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
|
C++
|
class Solution {
public:
int mostFrequentPrime(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
unordered_map<int, int> cnt;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a == 0 && b == 0) {
continue;
}
int x = i + a, y = j + b, v = mat[i][j];
while (x >= 0 && x < m && y >= 0 && y < n) {
v = v * 10 + mat[x][y];
if (isPrime(v)) {
cnt[v]++;
}
x += a;
y += b;
}
}
}
}
}
int ans = -1, mx = 0;
for (auto& [v, x] : cnt) {
if (mx < x || (mx == x && ans < v)) {
mx = x;
ans = v;
}
}
return ans;
}
private:
bool isPrime(int n) {
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
};
|
3,044 |
Most Frequent Prime
|
Medium
|
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p>
<ul>
<li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li>
<li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li>
<li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li>
</ul>
<p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p>
<p><strong>Note:</strong> It is invalid to change the direction during the move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong>
<pre>
<strong>
Input:</strong> mat = [[1,1],[9,9],[1,1]]
<strong>Output:</strong> 19
<strong>Explanation:</strong>
From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:
East: [11], South-East: [19], South: [19,191].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].
The most frequent prime number among all the created numbers is 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[7]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]]
<strong>Output:</strong> 97
<strong>Explanation:</strong>
Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].
Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].
Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].
Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].
The most frequent prime number among all the created numbers is 97.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 6</code></li>
<li><code>1 <= mat[i][j] <= 9</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
|
Go
|
func mostFrequentPrime(mat [][]int) int {
m, n := len(mat), len(mat[0])
cnt := make(map[int]int)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
for a := -1; a <= 1; a++ {
for b := -1; b <= 1; b++ {
if a == 0 && b == 0 {
continue
}
x, y, v := i+a, j+b, mat[i][j]
for x >= 0 && x < m && y >= 0 && y < n {
v = v*10 + mat[x][y]
if isPrime(v) {
cnt[v]++
}
x += a
y += b
}
}
}
}
}
ans, mx := -1, 0
for v, x := range cnt {
if mx < x || (mx == x && ans < v) {
mx = x
ans = v
}
}
return ans
}
func isPrime(n int) bool {
for i := 2; i <= n/i; i++ {
if n%i == 0 {
return false
}
}
return true
}
|
3,044 |
Most Frequent Prime
|
Medium
|
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p>
<ul>
<li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li>
<li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li>
<li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li>
</ul>
<p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p>
<p><strong>Note:</strong> It is invalid to change the direction during the move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong>
<pre>
<strong>
Input:</strong> mat = [[1,1],[9,9],[1,1]]
<strong>Output:</strong> 19
<strong>Explanation:</strong>
From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:
East: [11], South-East: [19], South: [19,191].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].
The most frequent prime number among all the created numbers is 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[7]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]]
<strong>Output:</strong> 97
<strong>Explanation:</strong>
Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].
Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].
Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].
Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].
The most frequent prime number among all the created numbers is 97.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 6</code></li>
<li><code>1 <= mat[i][j] <= 9</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
|
Java
|
class Solution {
public int mostFrequentPrime(int[][] mat) {
int m = mat.length, n = mat[0].length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a == 0 && b == 0) {
continue;
}
int x = i + a, y = j + b, v = mat[i][j];
while (x >= 0 && x < m && y >= 0 && y < n) {
v = v * 10 + mat[x][y];
if (isPrime(v)) {
cnt.merge(v, 1, Integer::sum);
}
x += a;
y += b;
}
}
}
}
}
int ans = -1, mx = 0;
for (var e : cnt.entrySet()) {
int v = e.getKey(), x = e.getValue();
if (mx < x || (mx == x && ans < v)) {
mx = x;
ans = v;
}
}
return ans;
}
private boolean isPrime(int n) {
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
|
3,044 |
Most Frequent Prime
|
Medium
|
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p>
<ul>
<li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li>
<li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li>
<li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li>
</ul>
<p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p>
<p><strong>Note:</strong> It is invalid to change the direction during the move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong>
<pre>
<strong>
Input:</strong> mat = [[1,1],[9,9],[1,1]]
<strong>Output:</strong> 19
<strong>Explanation:</strong>
From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:
East: [11], South-East: [19], South: [19,191].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].
The most frequent prime number among all the created numbers is 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[7]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]]
<strong>Output:</strong> 97
<strong>Explanation:</strong>
Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].
Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].
Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].
Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].
The most frequent prime number among all the created numbers is 97.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 6</code></li>
<li><code>1 <= mat[i][j] <= 9</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
|
Python
|
class Solution:
def mostFrequentPrime(self, mat: List[List[int]]) -> int:
def is_prime(x: int) -> int:
return all(x % i != 0 for i in range(2, isqrt(x) + 1))
m, n = len(mat), len(mat[0])
cnt = Counter()
for i in range(m):
for j in range(n):
for a in range(-1, 2):
for b in range(-1, 2):
if a == 0 and b == 0:
continue
x, y, v = i + a, j + b, mat[i][j]
while 0 <= x < m and 0 <= y < n:
v = v * 10 + mat[x][y]
if is_prime(v):
cnt[v] += 1
x, y = x + a, y + b
ans, mx = -1, 0
for v, x in cnt.items():
if mx < x:
mx = x
ans = v
elif mx == x:
ans = max(ans, v)
return ans
|
3,044 |
Most Frequent Prime
|
Medium
|
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p>
<ul>
<li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li>
<li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li>
<li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li>
</ul>
<p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p>
<p><strong>Note:</strong> It is invalid to change the direction during the move.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong>
<pre>
<strong>
Input:</strong> mat = [[1,1],[9,9],[1,1]]
<strong>Output:</strong> 19
<strong>Explanation:</strong>
From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:
East: [11], South-East: [19], South: [19,191].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].
The most frequent prime number among all the created numbers is 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> mat = [[7]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]]
<strong>Output:</strong> 97
<strong>Explanation:</strong>
Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].
Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].
Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].
Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].
Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].
Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].
Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].
Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].
Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].
The most frequent prime number among all the created numbers is 97.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 <= m, n <= 6</code></li>
<li><code>1 <= mat[i][j] <= 9</code></li>
</ul>
|
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
|
TypeScript
|
function mostFrequentPrime(mat: number[][]): number {
const m: number = mat.length;
const n: number = mat[0].length;
const cnt: Map<number, number> = new Map();
const isPrime = (x: number): boolean => {
for (let i = 2; i <= x / i; ++i) {
if (x % i === 0) {
return false;
}
}
return true;
};
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
for (let a = -1; a <= 1; ++a) {
for (let b = -1; b <= 1; ++b) {
if (a === 0 && b === 0) {
continue;
}
let [x, y, v] = [i + a, j + b, mat[i][j]];
while (x >= 0 && x < m && y >= 0 && y < n) {
v = v * 10 + mat[x][y];
if (isPrime(v)) {
cnt.set(v, (cnt.get(v) || 0) + 1);
}
x += a;
y += b;
}
}
}
}
}
let [ans, mx] = [-1, 0];
cnt.forEach((x, v) => {
if (mx < x || (mx === x && ans < v)) {
mx = x;
ans = v;
}
});
return ans;
}
|
3,045 |
Count Prefix and Suffix Pairs II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>5</sup></code></li>
<li><code>1 <= words[i].length <= 10<sup>5</sup></code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
<li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
C++
|
class Node {
public:
unordered_map<int, Node*> children;
int cnt;
Node()
: cnt(0) {}
};
class Solution {
public:
long long countPrefixSuffixPairs(vector<string>& words) {
long long ans = 0;
Node* trie = new Node();
for (const string& s : words) {
Node* node = trie;
int m = s.length();
for (int i = 0; i < m; ++i) {
int p = s[i] * 32 + s[m - i - 1];
if (node->children.find(p) == node->children.end()) {
node->children[p] = new Node();
}
node = node->children[p];
ans += node->cnt;
}
++node->cnt;
}
return ans;
}
};
|
3,045 |
Count Prefix and Suffix Pairs II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>5</sup></code></li>
<li><code>1 <= words[i].length <= 10<sup>5</sup></code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
<li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Go
|
type Node struct {
children map[int]*Node
cnt int
}
func countPrefixSuffixPairs(words []string) (ans int64) {
trie := &Node{children: make(map[int]*Node)}
for _, s := range words {
node := trie
m := len(s)
for i := 0; i < m; i++ {
p := int(s[i])*32 + int(s[m-i-1])
if _, ok := node.children[p]; !ok {
node.children[p] = &Node{children: make(map[int]*Node)}
}
node = node.children[p]
ans += int64(node.cnt)
}
node.cnt++
}
return
}
|
3,045 |
Count Prefix and Suffix Pairs II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>5</sup></code></li>
<li><code>1 <= words[i].length <= 10<sup>5</sup></code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
<li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Java
|
class Node {
Map<Integer, Node> children = new HashMap<>();
int cnt;
}
class Solution {
public long countPrefixSuffixPairs(String[] words) {
long ans = 0;
Node trie = new Node();
for (String s : words) {
Node node = trie;
int m = s.length();
for (int i = 0; i < m; ++i) {
int p = s.charAt(i) * 32 + s.charAt(m - i - 1);
node.children.putIfAbsent(p, new Node());
node = node.children.get(p);
ans += node.cnt;
}
++node.cnt;
}
return ans;
}
}
|
3,045 |
Count Prefix and Suffix Pairs II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>5</sup></code></li>
<li><code>1 <= words[i].length <= 10<sup>5</sup></code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
<li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
Python
|
class Node:
__slots__ = ["children", "cnt"]
def __init__(self):
self.children = {}
self.cnt = 0
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
ans = 0
trie = Node()
for s in words:
node = trie
for p in zip(s, reversed(s)):
if p not in node.children:
node.children[p] = Node()
node = node.children[p]
ans += node.cnt
node.cnt += 1
return ans
|
3,045 |
Count Prefix and Suffix Pairs II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p>
<p>Let's define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p>
<ul>
<li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li>
</ul>
<p>For example, <code>isPrefixAndSuffix("aba", "ababa")</code> is <code>true</code> because <code>"aba"</code> is a prefix of <code>"ababa"</code> and also a suffix, but <code>isPrefixAndSuffix("abc", "abcd")</code> is <code>false</code>.</p>
<p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i < j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["a","aba","ababa","aa"]
<strong>Output:</strong> 4
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["pa","papa","ma","mama"]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2. </pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abab","ab"]
<strong>Output:</strong> 0
<strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>5</sup></code></li>
<li><code>1 <= words[i].length <= 10<sup>5</sup></code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
<li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li>
</ul>
|
Trie; Array; String; String Matching; Hash Function; Rolling Hash
|
TypeScript
|
class Node {
children: Map<number, Node> = new Map<number, Node>();
cnt: number = 0;
}
function countPrefixSuffixPairs(words: string[]): number {
let ans: number = 0;
const trie: Node = new Node();
for (const s of words) {
let node: Node = trie;
const m: number = s.length;
for (let i: number = 0; i < m; ++i) {
const p: number = s.charCodeAt(i) * 32 + s.charCodeAt(m - i - 1);
if (!node.children.has(p)) {
node.children.set(p, new Node());
}
node = node.children.get(p)!;
ans += node.cnt;
}
++node.cnt;
}
return ans;
}
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
C++
|
class Solution {
public:
bool isPossibleToSplit(vector<int>& nums) {
int cnt[101]{};
for (int x : nums) {
if (++cnt[x] >= 3) {
return false;
}
}
return true;
}
};
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
C#
|
public class Solution {
public bool IsPossibleToSplit(int[] nums) {
int[] cnt = new int[101];
foreach (int x in nums) {
if (++cnt[x] >= 3) {
return false;
}
}
return true;
}
}
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Go
|
func isPossibleToSplit(nums []int) bool {
cnt := [101]int{}
for _, x := range nums {
cnt[x]++
if cnt[x] >= 3 {
return false
}
}
return true
}
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Java
|
class Solution {
public boolean isPossibleToSplit(int[] nums) {
int[] cnt = new int[101];
for (int x : nums) {
if (++cnt[x] >= 3) {
return false;
}
}
return true;
}
}
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Python
|
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
return max(Counter(nums).values()) < 3
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn is_possible_to_split(nums: Vec<i32>) -> bool {
let mut cnt = HashMap::new();
for &x in &nums {
*cnt.entry(x).or_insert(0) += 1;
}
*cnt.values().max().unwrap_or(&0) < 3
}
}
|
3,046 |
Split the Array
|
Easy
|
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p>
<ul>
<li><code>nums1.length == nums2.length == nums.length / 2</code>.</li>
<li><code>nums1</code> should contain <strong>distinct </strong>elements.</li>
<li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li>
</ul>
<p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,2,3,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>nums.length % 2 == 0 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table; Counting
|
TypeScript
|
function isPossibleToSplit(nums: number[]): boolean {
const cnt: number[] = Array(101).fill(0);
for (const x of nums) {
if (++cnt[x] >= 3) {
return false;
}
}
return true;
}
|
3,047 |
Find the Largest Area of Square Inside Two Rectangles
|
Medium
|
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays <code>bottomLeft</code> and <code>topRight</code> where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p>
<p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 3:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code>
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p>
<p><strong class="example">Example 4:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code>
<p><strong>Input: </strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>No pair of rectangles intersect, hence, the answer is 0.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == bottomLeft.length == topRight.length</code></li>
<li><code>2 <= n <= 10<sup>3</sup></code></li>
<li><code>bottomLeft[i].length == topRight[i].length == 2</code></li>
<li><code>1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10<sup>7</sup></code></li>
<li><code>1 <= topRight[i][0], topRight[i][1] <= 10<sup>7</sup></code></li>
<li><code>bottomLeft[i][0] < topRight[i][0]</code></li>
<li><code>bottomLeft[i][1] < topRight[i][1]</code></li>
</ul>
|
Geometry; Array; Math
|
C++
|
class Solution {
public:
long long largestSquareArea(vector<vector<int>>& bottomLeft, vector<vector<int>>& topRight) {
long long ans = 0;
for (int i = 0; i < bottomLeft.size(); ++i) {
int x1 = bottomLeft[i][0], y1 = bottomLeft[i][1];
int x2 = topRight[i][0], y2 = topRight[i][1];
for (int j = i + 1; j < bottomLeft.size(); ++j) {
int x3 = bottomLeft[j][0], y3 = bottomLeft[j][1];
int x4 = topRight[j][0], y4 = topRight[j][1];
int w = min(x2, x4) - max(x1, x3);
int h = min(y2, y4) - max(y1, y3);
int e = min(w, h);
if (e > 0) {
ans = max(ans, 1LL * e * e);
}
}
}
return ans;
}
};
|
3,047 |
Find the Largest Area of Square Inside Two Rectangles
|
Medium
|
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays <code>bottomLeft</code> and <code>topRight</code> where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p>
<p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 3:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code>
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p>
<p><strong class="example">Example 4:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code>
<p><strong>Input: </strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>No pair of rectangles intersect, hence, the answer is 0.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == bottomLeft.length == topRight.length</code></li>
<li><code>2 <= n <= 10<sup>3</sup></code></li>
<li><code>bottomLeft[i].length == topRight[i].length == 2</code></li>
<li><code>1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10<sup>7</sup></code></li>
<li><code>1 <= topRight[i][0], topRight[i][1] <= 10<sup>7</sup></code></li>
<li><code>bottomLeft[i][0] < topRight[i][0]</code></li>
<li><code>bottomLeft[i][1] < topRight[i][1]</code></li>
</ul>
|
Geometry; Array; Math
|
Go
|
func largestSquareArea(bottomLeft [][]int, topRight [][]int) (ans int64) {
for i, b1 := range bottomLeft {
t1 := topRight[i]
x1, y1 := b1[0], b1[1]
x2, y2 := t1[0], t1[1]
for j := i + 1; j < len(bottomLeft); j++ {
x3, y3 := bottomLeft[j][0], bottomLeft[j][1]
x4, y4 := topRight[j][0], topRight[j][1]
w := min(x2, x4) - max(x1, x3)
h := min(y2, y4) - max(y1, y3)
e := min(w, h)
if e > 0 {
ans = max(ans, int64(e)*int64(e))
}
}
}
return
}
|
3,047 |
Find the Largest Area of Square Inside Two Rectangles
|
Medium
|
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays <code>bottomLeft</code> and <code>topRight</code> where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p>
<p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 3:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code>
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p>
<p><strong class="example">Example 4:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code>
<p><strong>Input: </strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>No pair of rectangles intersect, hence, the answer is 0.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == bottomLeft.length == topRight.length</code></li>
<li><code>2 <= n <= 10<sup>3</sup></code></li>
<li><code>bottomLeft[i].length == topRight[i].length == 2</code></li>
<li><code>1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10<sup>7</sup></code></li>
<li><code>1 <= topRight[i][0], topRight[i][1] <= 10<sup>7</sup></code></li>
<li><code>bottomLeft[i][0] < topRight[i][0]</code></li>
<li><code>bottomLeft[i][1] < topRight[i][1]</code></li>
</ul>
|
Geometry; Array; Math
|
Java
|
class Solution {
public long largestSquareArea(int[][] bottomLeft, int[][] topRight) {
long ans = 0;
for (int i = 0; i < bottomLeft.length; ++i) {
int x1 = bottomLeft[i][0], y1 = bottomLeft[i][1];
int x2 = topRight[i][0], y2 = topRight[i][1];
for (int j = i + 1; j < bottomLeft.length; ++j) {
int x3 = bottomLeft[j][0], y3 = bottomLeft[j][1];
int x4 = topRight[j][0], y4 = topRight[j][1];
int w = Math.min(x2, x4) - Math.max(x1, x3);
int h = Math.min(y2, y4) - Math.max(y1, y3);
int e = Math.min(w, h);
if (e > 0) {
ans = Math.max(ans, 1L * e * e);
}
}
}
return ans;
}
}
|
3,047 |
Find the Largest Area of Square Inside Two Rectangles
|
Medium
|
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays <code>bottomLeft</code> and <code>topRight</code> where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p>
<p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 3:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code>
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p>
<p><strong class="example">Example 4:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code>
<p><strong>Input: </strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>No pair of rectangles intersect, hence, the answer is 0.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == bottomLeft.length == topRight.length</code></li>
<li><code>2 <= n <= 10<sup>3</sup></code></li>
<li><code>bottomLeft[i].length == topRight[i].length == 2</code></li>
<li><code>1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10<sup>7</sup></code></li>
<li><code>1 <= topRight[i][0], topRight[i][1] <= 10<sup>7</sup></code></li>
<li><code>bottomLeft[i][0] < topRight[i][0]</code></li>
<li><code>bottomLeft[i][1] < topRight[i][1]</code></li>
</ul>
|
Geometry; Array; Math
|
Python
|
class Solution:
def largestSquareArea(
self, bottomLeft: List[List[int]], topRight: List[List[int]]
) -> int:
ans = 0
for ((x1, y1), (x2, y2)), ((x3, y3), (x4, y4)) in combinations(
zip(bottomLeft, topRight), 2
):
w = min(x2, x4) - max(x1, x3)
h = min(y2, y4) - max(y1, y3)
e = min(w, h)
if e > 0:
ans = max(ans, e * e)
return ans
|
3,047 |
Find the Largest Area of Square Inside Two Rectangles
|
Medium
|
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays <code>bottomLeft</code> and <code>topRight</code> where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p>
<p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p>
<p><strong class="example">Example 3:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code>
<p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong></p>
<p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p>
<p><strong class="example">Example 4:</strong></p>
<code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code>
<p><strong>Input: </strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong></p>
<p>No pair of rectangles intersect, hence, the answer is 0.</p>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == bottomLeft.length == topRight.length</code></li>
<li><code>2 <= n <= 10<sup>3</sup></code></li>
<li><code>bottomLeft[i].length == topRight[i].length == 2</code></li>
<li><code>1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10<sup>7</sup></code></li>
<li><code>1 <= topRight[i][0], topRight[i][1] <= 10<sup>7</sup></code></li>
<li><code>bottomLeft[i][0] < topRight[i][0]</code></li>
<li><code>bottomLeft[i][1] < topRight[i][1]</code></li>
</ul>
|
Geometry; Array; Math
|
TypeScript
|
function largestSquareArea(bottomLeft: number[][], topRight: number[][]): number {
let ans = 0;
for (let i = 0; i < bottomLeft.length; ++i) {
const [x1, y1] = bottomLeft[i];
const [x2, y2] = topRight[i];
for (let j = i + 1; j < bottomLeft.length; ++j) {
const [x3, y3] = bottomLeft[j];
const [x4, y4] = topRight[j];
const w = Math.min(x2, x4) - Math.max(x1, x3);
const h = Math.min(y2, y4) - Math.max(y1, y3);
const e = Math.min(w, h);
if (e > 0) {
ans = Math.max(ans, e * e);
}
}
}
return ans;
}
|
3,048 |
Earliest Second to Mark Indices I
|
Medium
|
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p>
<p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p>
<p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li>
<li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li>
<li>Do nothing.</li>
</ul>
<p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].
Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].
Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].
Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.
Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.
Second 7: Do nothing.
Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 8th second.
Hence, the answer is 8.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].
Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].
Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.
Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].
Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 6th second.
Hence, the answer is 6.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.
Hence, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == changeIndices.length <= 2000</code></li>
<li><code>1 <= changeIndices[i] <= n</code></li>
</ul>
|
Array; Binary Search
|
C++
|
class Solution {
public:
int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& changeIndices) {
int n = nums.size();
int last[n + 1];
auto check = [&](int t) {
memset(last, 0, sizeof(last));
for (int s = 0; s < t; ++s) {
last[changeIndices[s]] = s;
}
int decrement = 0, marked = 0;
for (int s = 0; s < t; ++s) {
int i = changeIndices[s];
if (last[i] == s) {
if (decrement < nums[i - 1]) {
return false;
}
decrement -= nums[i - 1];
++marked;
} else {
++decrement;
}
}
return marked == n;
};
int m = changeIndices.size();
int l = 1, r = m + 1;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l > m ? -1 : l;
}
};
|
3,048 |
Earliest Second to Mark Indices I
|
Medium
|
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p>
<p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p>
<p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li>
<li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li>
<li>Do nothing.</li>
</ul>
<p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].
Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].
Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].
Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.
Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.
Second 7: Do nothing.
Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 8th second.
Hence, the answer is 8.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].
Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].
Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.
Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].
Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 6th second.
Hence, the answer is 6.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.
Hence, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == changeIndices.length <= 2000</code></li>
<li><code>1 <= changeIndices[i] <= n</code></li>
</ul>
|
Array; Binary Search
|
Go
|
func earliestSecondToMarkIndices(nums []int, changeIndices []int) int {
n, m := len(nums), len(changeIndices)
l := sort.Search(m+1, func(t int) bool {
last := make([]int, n+1)
for s, i := range changeIndices[:t] {
last[i] = s
}
decrement, marked := 0, 0
for s, i := range changeIndices[:t] {
if last[i] == s {
if decrement < nums[i-1] {
return false
}
decrement -= nums[i-1]
marked++
} else {
decrement++
}
}
return marked == n
})
if l > m {
return -1
}
return l
}
|
3,048 |
Earliest Second to Mark Indices I
|
Medium
|
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p>
<p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p>
<p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li>
<li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li>
<li>Do nothing.</li>
</ul>
<p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].
Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].
Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].
Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.
Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.
Second 7: Do nothing.
Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 8th second.
Hence, the answer is 8.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].
Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].
Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.
Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].
Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 6th second.
Hence, the answer is 6.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.
Hence, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == changeIndices.length <= 2000</code></li>
<li><code>1 <= changeIndices[i] <= n</code></li>
</ul>
|
Array; Binary Search
|
Java
|
class Solution {
private int[] nums;
private int[] changeIndices;
public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) {
this.nums = nums;
this.changeIndices = changeIndices;
int m = changeIndices.length;
int l = 1, r = m + 1;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l > m ? -1 : l;
}
private boolean check(int t) {
int[] last = new int[nums.length + 1];
for (int s = 0; s < t; ++s) {
last[changeIndices[s]] = s;
}
int decrement = 0;
int marked = 0;
for (int s = 0; s < t; ++s) {
int i = changeIndices[s];
if (last[i] == s) {
if (decrement < nums[i - 1]) {
return false;
}
decrement -= nums[i - 1];
++marked;
} else {
++decrement;
}
}
return marked == nums.length;
}
}
|
3,048 |
Earliest Second to Mark Indices I
|
Medium
|
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p>
<p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p>
<p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li>
<li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li>
<li>Do nothing.</li>
</ul>
<p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].
Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].
Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].
Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.
Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.
Second 7: Do nothing.
Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 8th second.
Hence, the answer is 8.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].
Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].
Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.
Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].
Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 6th second.
Hence, the answer is 6.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.
Hence, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == changeIndices.length <= 2000</code></li>
<li><code>1 <= changeIndices[i] <= n</code></li>
</ul>
|
Array; Binary Search
|
Python
|
class Solution:
def earliestSecondToMarkIndices(
self, nums: List[int], changeIndices: List[int]
) -> int:
def check(t: int) -> bool:
decrement = 0
marked = 0
last = {i: s for s, i in enumerate(changeIndices[:t])}
for s, i in enumerate(changeIndices[:t]):
if last[i] == s:
if decrement < nums[i - 1]:
return False
decrement -= nums[i - 1]
marked += 1
else:
decrement += 1
return marked == len(nums)
m = len(changeIndices)
l = bisect_left(range(1, m + 2), True, key=check) + 1
return -1 if l > m else l
|
3,048 |
Earliest Second to Mark Indices I
|
Medium
|
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p>
<p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p>
<p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li>
<li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li>
<li>Do nothing.</li>
</ul>
<p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].
Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].
Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].
Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.
Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.
Second 7: Do nothing.
Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 8th second.
Hence, the answer is 8.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices:
Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].
Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].
Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].
Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.
Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].
Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.
Now all indices have been marked.
It can be shown that it is not possible to mark all indices earlier than the 6th second.
Hence, the answer is 6.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.
Hence, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 2000</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == changeIndices.length <= 2000</code></li>
<li><code>1 <= changeIndices[i] <= n</code></li>
</ul>
|
Array; Binary Search
|
TypeScript
|
function earliestSecondToMarkIndices(nums: number[], changeIndices: number[]): number {
const [n, m] = [nums.length, changeIndices.length];
let [l, r] = [1, m + 1];
const check = (t: number): boolean => {
const last: number[] = Array(n + 1).fill(0);
for (let s = 0; s < t; ++s) {
last[changeIndices[s]] = s;
}
let [decrement, marked] = [0, 0];
for (let s = 0; s < t; ++s) {
const i = changeIndices[s];
if (last[i] === s) {
if (decrement < nums[i - 1]) {
return false;
}
decrement -= nums[i - 1];
++marked;
} else {
++decrement;
}
}
return marked === n;
};
while (l < r) {
const mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l > m ? -1 : l;
}
|
3,050 |
Pizza Toppings Cost Analysis
|
Medium
|
<p>Table: <code><font face="monospace">Toppings</font></code></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| topping_name | varchar |
| cost | decimal |
+--------------+---------+
topping_name is the primary key for this table.
Each row of this table contains topping name and the cost of the topping.
</pre>
<p>Write a solution to calculate the <strong>total cost</strong> of <strong>all possible <code>3</code>-topping</strong> pizza combinations from a given list of toppings. The total cost of toppings must be <strong>rounded</strong> to <code>2</code> <strong>decimal</strong> places.</p>
<p><strong>Note:</strong></p>
<ul>
<li><strong>Do not</strong> include the pizzas where a topping is <strong>repeated</strong>. For example, ‘Pepperoni, Pepperoni, Onion Pizza’.</li>
<li>Toppings <strong>must be</strong> listed in <strong>alphabetical order</strong>. For example, 'Chicken, Onions, Sausage'. 'Onion, Sausage, Chicken' is not acceptable.</li>
</ul>
<p>Return<em> the result table ordered by total cost in</em> <em><strong>descending</strong></em> <em>order and combination of toppings in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Toppings table:
+--------------+------+
| topping_name | cost |
+--------------+------+
| Pepperoni | 0.50 |
| Sausage | 0.70 |
| Chicken | 0.55 |
| Extra Cheese | 0.40 |
+--------------+------+
<strong>Output:</strong>
+--------------------------------+------------+
| pizza | total_cost |
+--------------------------------+------------+
| Chicken,Pepperoni,Sausage | 1.75 |
| Chicken,Extra Cheese,Sausage | 1.65 |
| Extra Cheese,Pepperoni,Sausage | 1.60 |
| Chicken,Extra Cheese,Pepperoni | 1.45 |
+--------------------------------+------------+
<strong>Explanation:</strong>
There are only four different combinations possible with the three topings:
- Chicken, Pepperoni, Sausage: Total cost is $1.75 (Chicken $0.55, Pepperoni $0.50, Sausage $0.70).
- Chicken, Extra Cheese, Sausage: Total cost is $1.65 (Chicken $0.55, Extra Cheese $0.40, Sausage $0.70).
- Extra Cheese, Pepperoni, Sausage: Total cost is $1.60 (Extra Cheese $0.40, Pepperoni $0.50, Sausage $0.70).
- Chicken, Extra Cheese, Pepperoni: Total cost is $1.45 (Chicken $0.55, Extra Cheese $0.40, Pepperoni $0.50).
Output table is ordered by the total cost in descending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT *, RANK() OVER (ORDER BY topping_name) AS rk
FROM Toppings
)
SELECT
CONCAT(t1.topping_name, ',', t2.topping_name, ',', t3.topping_name) AS pizza,
t1.cost + t2.cost + t3.cost AS total_cost
FROM
T AS t1
JOIN T AS t2 ON t1.rk < t2.rk
JOIN T AS t3 ON t2.rk < t3.rk
ORDER BY 2 DESC, 1 ASC;
|
3,051 |
Find Candidates for Data Scientist Position
|
Easy
|
<p>Table: <font face="monospace"><code>Candidates</code></font></p>
<pre>
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| candidate_id | int |
| skill | varchar |
+--------------+---------+
(candidate_id, skill) is the primary key (columns with unique values) for this table.
Each row includes candidate_id and skill.
</pre>
<p>Write a query to find the <strong>candidates</strong> best suited for a Data Scientist position. The candidate must be proficient in <strong>Python</strong>, <strong>Tableau</strong>, and <strong>PostgreSQL</strong>.</p>
<p>Return <em>the result table ordered by </em><code>candidate_id</code> <em>in <strong>ascending order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Candidates table:
+---------------+--------------+
| candidate_id | skill |
+---------------+--------------+
| 123 | Python |
| 234 | R |
| 123 | Tableau |
| 123 | PostgreSQL |
| 234 | PowerBI |
| 234 | SQL Server |
| 147 | Python |
| 147 | Tableau |
| 147 | Java |
| 147 | PostgreSQL |
| 256 | Tableau |
| 102 | DataAnalysis |
+---------------+--------------+
<strong>Output:</strong>
+--------------+
| candidate_id |
+--------------+
| 123 |
| 147 |
+--------------+
<strong>Explanation:</strong>
- Candidates 123 and 147 possess the necessary skills in Python, Tableau, and PostgreSQL for the data scientist position.
- Candidates 234 and 102 do not possess any of the required skills for this position.
- Candidate 256 has proficiency in Tableau but is missing skills in Python and PostgreSQL.
The output table is sorted by candidate_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT candidate_id
FROM Candidates
WHERE skill IN ('Python', 'Tableau', 'PostgreSQL')
GROUP BY 1
HAVING COUNT(1) = 3
ORDER BY 1;
|
3,052 |
Maximize Items
|
Hard
|
<p>Table: <font face="monospace"><code>Inventory</code></font></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| item_id | int |
| item_type | varchar |
| item_category | varchar |
| square_footage | decimal |
+----------------+---------+
item_id is the column of unique values for this table.
Each row includes item id, item type, item category and sqaure footage.
</pre>
<p>Leetcode warehouse wants to maximize the number of items it can stock in a <code>500,000</code> square feet warehouse. It wants to stock as many <strong>prime</strong> items as possible, and afterwards use the <strong>remaining</strong> square footage to stock the most number of <strong>non-prime</strong> items.</p>
<p>Write a solution to find the number of <strong>prime</strong> and <strong>non-prime</strong> items that can be <strong>stored</strong> in the <code>500,000</code> square feet warehouse. Output the item type with <code>prime_eligible</code> followed by <code>not_prime</code> and the maximum number of items that can be stocked.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Item <strong>count</strong> must be a whole number (integer).</li>
<li>If the count for the <strong>not_prime</strong> category is <code>0</code>, you should <strong>output</strong> <code>0</code> for that particular category.</li>
</ul>
<p>Return <em>the result table ordered by item count in <strong>descending order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Inventory table:
+---------+----------------+---------------+----------------+
| item_id | item_type | item_category | square_footage |
+---------+----------------+---------------+----------------+
| 1374 | prime_eligible | Watches | 68.00 |
| 4245 | not_prime | Art | 26.40 |
| 5743 | prime_eligible | Software | 325.00 |
| 8543 | not_prime | Clothing | 64.50 |
| 2556 | not_prime | Shoes | 15.00 |
| 2452 | prime_eligible | Scientific | 85.00 |
| 3255 | not_prime | Furniture | 22.60 |
| 1672 | prime_eligible | Beauty | 8.50 |
| 4256 | prime_eligible | Furniture | 55.50 |
| 6325 | prime_eligible | Food | 13.20 |
+---------+----------------+---------------+----------------+
<strong>Output:</strong>
+----------------+-------------+
| item_type | item_count |
+----------------+-------------+
| prime_eligible | 5400 |
| not_prime | 8 |
+----------------+-------------+
<strong>Explanation:</strong>
- The prime-eligible category comprises a total of 6 items, amounting to a combined square footage of 555.20 (68 + 325 + 85 + 8.50 + 55.50 + 13.20). It is possible to store 900 combinations of these 6 items, totaling 5400 items and occupying 499,680 square footage.
- In the not_prime category, there are a total of 4 items with a combined square footage of 128.50. After deducting the storage used by prime-eligible items (500,000 - 499,680 = 320), there is room for 2 combinations of non-prime items, accommodating a total of 8 non-prime items within the available 320 square footage.
Output table is ordered by item count in descending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT SUM(square_footage) AS s
FROM Inventory
WHERE item_type = 'prime_eligible'
)
SELECT
'prime_eligible' AS item_type,
COUNT(1) * FLOOR(500000 / s) AS item_count
FROM
Inventory
JOIN T
WHERE item_type = 'prime_eligible'
UNION ALL
SELECT
'not_prime',
IFNULL(COUNT(1) * FLOOR(IF(s = 0, 500000, 500000 % s) / SUM(square_footage)), 0)
FROM
Inventory
JOIN T
WHERE item_type = 'not_prime';
|
3,053 |
Classifying Triangles by Lengths
|
Easy
|
<p>Table: <font face="monospace"><code>Triangles</code></font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| A | int |
| B | int |
| C | int |
+-------------+------+
(A, B, C) is the primary key for this table.
Each row include the lengths of each of a triangle's three sides.
</pre>
<p>Write a query to find the type of <strong>triangle</strong>. Output one of the following for each row:</p>
<ul>
<li><strong>Equilateral</strong>: It's a triangle with <code>3</code> sides of equal length.</li>
<li><strong>Isosceles</strong>: It's a triangle with <code>2</code> sides of equal length.</li>
<li><strong>Scalene</strong>: It's a triangle with <code>3</code> sides of differing lengths.</li>
<li><strong>Not A Triangle: </strong>The given values of <code>A</code>, <code>B</code>, and <code>C</code> don't form a triangle.</li>
</ul>
<p>Return <em>the result table in <strong>any order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Triangles table:
+----+----+----+
| A | B | C |
+----+----+----+
| 20 | 20 | 23 |
| 20 | 20 | 20 |
| 20 | 21 | 22 |
| 13 | 14 | 30 |
+----+----+----+
<strong>Output:</strong>
+----------------+
| triangle_type |
+----------------+
| Isosceles |
| Equilateral |
| Scalene |
| Not A Triangle |
+----------------+
<strong>Explanation:</strong>
- Values in the first row from an Isosceles triangle, because A = B.
- Values in the second row from an Equilateral triangle, because A = B = C.
- Values in the third row from an Scalene triangle, because A != B != C.
- Values in the fourth row cannot form a triangle, because the combined value of sides A and B is not larger than that of side C.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
CASE
WHEN A + B <= C
OR A + C <= B
OR B + C <= A THEN 'Not A Triangle'
WHEN A = B
AND B = c THEN 'Equilateral'
WHEN (A = B) + (B = C) + (A = C) = 1 THEN 'Isosceles'
ELSE 'Scalene'
END AS triangle_type
FROM Triangles;
|
3,054 |
Binary Tree Nodes
|
Medium
|
<p>Table: <font face="monospace"><code>Tree</code></font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| N | int |
| P | int |
+-------------+------+
N is the column of unique values for this table.
Each row includes N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.
</pre>
<p>Write a solution to find the node type of the Binary Tree. Output one of the following for each node:</p>
<ul>
<li><strong>Root</strong>: if the node is the root node.</li>
<li><strong>Leaf</strong>: if the node is the leaf node.</li>
<li><strong>Inner</strong>: if the node is neither root nor leaf node.</li>
</ul>
<p>Return <em>the result table ordered by node value in <strong>ascending order</strong></em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Tree table:
+---+------+
| N | P |
+---+------+
| 1 | 2 |
| 3 | 2 |
| 6 | 8 |
| 9 | 8 |
| 2 | 5 |
| 8 | 5 |
| 5 | null |
+---+------+
<strong>Output:</strong>
+---+-------+
| N | Type |
+---+-------+
| 1 | Leaf |
| 2 | Inner |
| 3 | Leaf |
| 5 | Root |
| 6 | Leaf |
| 8 | Inner |
| 9 | Leaf |
+---+-------+
<strong>Explanation:</strong>
- Node 5 is the root node since it has no parent node.
- Nodes 1, 3, 6, and 9 are leaf nodes because they don't have any child nodes.
- Nodes 2, and 8 are inner nodes as they serve as parents to some of the nodes in the structure.
</pre>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/tree-node/description/" target="_blank"> 608: Tree Node.</a></p>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT DISTINCT
t1.N AS N,
IF(t1.P IS NULL, 'Root', IF(t2.P IS NULL, 'Leaf', 'Inner')) AS Type
FROM
Tree AS t1
LEFT JOIN Tree AS t2 ON t1.N = t2.p
ORDER BY 1;
|
3,055 |
Top Percentile Fraud
|
Medium
|
<p>Table: <code>Fraud</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| policy_id | int |
| state | varchar |
| fraud_score | int |
+-------------+---------+
policy_id is column of unique values for this table.
This table contains policy id, state, and fraud score.
</pre>
<p>The Leetcode Insurance Corp has developed an ML-driven <strong>predictive model </strong>to detect the <strong>likelihood</strong> of fraudulent claims. Consequently, they allocate their most seasoned claim adjusters to address the top <code>5%</code> of <strong>claims</strong> <strong>flagged</strong> by this model.</p>
<p>Write a solution to find the top <code>5</code> <strong>percentile</strong> of claims from <strong>each state</strong>.</p>
<p>Return <em>the result table ordered by </em><code>state</code><em> in <strong>ascending</strong> order, </em><code>fraud_score</code><em> in <strong>descending</strong> order, and </em><code>policy_id</code><em> in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Fraud table:
+-----------+------------+-------------+
| policy_id | state | fraud_score |
+-----------+------------+-------------+
| 1 | California | 0.92 |
| 2 | California | 0.68 |
| 3 | California | 0.17 |
| 4 | New York | 0.94 |
| 5 | New York | 0.81 |
| 6 | New York | 0.77 |
| 7 | Texas | 0.98 |
| 8 | Texas | 0.97 |
| 9 | Texas | 0.96 |
| 10 | Florida | 0.97 |
| 11 | Florida | 0.98 |
| 12 | Florida | 0.78 |
| 13 | Florida | 0.88 |
| 14 | Florida | 0.66 |
+-----------+------------+-------------+
<strong>Output:</strong>
+-----------+------------+-------------+
| policy_id | state | fraud_score |
+-----------+------------+-------------+
| 1 | California | 0.92 |
| 11 | Florida | 0.98 |
| 4 | New York | 0.94 |
| 7 | Texas | 0.98 |
+-----------+------------+-------------+
<strong>Explanation</strong>
- For the state of California, only policy ID 1, with a fraud score of 0.92, falls within the top 5 percentile for this state.
- For the state of Florida, only policy ID 11, with a fraud score of 0.98, falls within the top 5 percentile for this state.
- For the state of New York, only policy ID 4, with a fraud score of 0.94, falls within the top 5 percentile for this state.
- For the state of Texas, only policy ID 7, with a fraud score of 0.98, falls within the top 5 percentile for this state.
Output table is ordered by state in ascending order, fraud score in descending order, and policy ID in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY state
ORDER BY fraud_score DESC
) AS rk
FROM Fraud
)
SELECT policy_id, state, fraud_score
FROM T
WHERE rk = 1
ORDER BY 2, 3 DESC, 1;
|
3,056 |
Snaps Analysis
|
Medium
|
<p>Table: <code>Activities</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| activity_id | int |
| user_id | int |
| activity_type | enum |
| time_spent | decimal |
+---------------+---------+
activity_id is column of unique values for this table.
activity_type is an ENUM (category) type of ('send', 'open').
This table contains activity id, user id, activity type and time spent.
</pre>
<p>Table: <code>Age</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| age_bucket | enum |
+-------------+------+
user_id is the column of unique values for this table.
age_bucket is an ENUM (category) type of ('21-25', '26-30', '31-35').
This table contains user id and age group.</pre>
<p>Write a solution to calculate the <strong>percentage</strong> of the total time spent on <strong>sending</strong> and <strong>opening snaps</strong> for <strong>each age group</strong>. Precentage should be <strong>rounded</strong> to <code>2</code> decimal places.</p>
<p>Return <em>the result table </em><em>in <strong>any</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Activities table:
+-------------+---------+---------------+------------+
| activity_id | user_id | activity_type | time_spent |
+-------------+---------+---------------+------------+
| 7274 | 123 | open | 4.50 |
| 2425 | 123 | send | 3.50 |
| 1413 | 456 | send | 5.67 |
| 2536 | 456 | open | 3.00 |
| 8564 | 456 | send | 8.24 |
| 5235 | 789 | send | 6.24 |
| 4251 | 123 | open | 1.25 |
| 1435 | 789 | open | 5.25 |
+-------------+---------+---------------+------------+
Age table:
+---------+------------+
| user_id | age_bucket |
+---------+------------+
| 123 | 31-35 |
| 789 | 21-25 |
| 456 | 26-30 |
+---------+------------+
<strong>Output:</strong>
+------------+-----------+-----------+
| age_bucket | send_perc | open_perc |
+------------+-----------+-----------+
| 31-35 | 37.84 | 62.16 |
| 26-30 | 82.26 | 17.74 |
| 21-25 | 54.31 | 45.69 |
+------------+-----------+-----------+
<strong>Explanation:</strong>
For age group 31-35:
- There is only one user belonging to this group with the user ID 123.
- The total time spent on sending snaps by this user is 3.50, and the time spent on opening snaps is 4.50 + 1.25 = 5.75.
- The overall time spent by this user is 3.50 + 5.75 = 9.25.
- Therefore, the sending snap percentage will be (3.50 / 9.25) * 100 = 37.84, and the opening snap percentage will be (5.75 / 9.25) * 100 = 62.16.
For age group 26-30:
- There is only one user belonging to this group with the user ID 456.
- The total time spent on sending snaps by this user is 5.67 + 8.24 = 13.91, and the time spent on opening snaps is 3.00.
- The overall time spent by this user is 13.91 + 3.00 = 16.91.
- Therefore, the sending snap percentage will be (13.91 / 16.91) * 100 = 82.26, and the opening snap percentage will be (3.00 / 16.91) * 100 = 17.74.
For age group 21-25:
- There is only one user belonging to this group with the user ID 789.
- The total time spent on sending snaps by this user is 6.24, and the time spent on opening snaps is 5.25.
- The overall time spent by this user is 6.24 + 5.25 = 11.49.
- Therefore, the sending snap percentage will be (6.24 / 11.49) * 100 = 54.31, and the opening snap percentage will be (5.25 / 11.49) * 100 = 45.69.
All percentages in output table rounded to the two decimal places.
</pre>
|
Database
|
Python
|
import pandas as pd
def snap_analysis(activities: pd.DataFrame, age: pd.DataFrame) -> pd.DataFrame:
merged_df = pd.merge(activities, age, on="user_id")
total_time_per_age_activity = (
merged_df.groupby(["age_bucket", "activity_type"])["time_spent"]
.sum()
.reset_index()
)
pivot_df = total_time_per_age_activity.pivot(
index="age_bucket", columns="activity_type", values="time_spent"
).reset_index()
pivot_df = pivot_df.fillna(0)
pivot_df["send_perc"] = round(
100 * pivot_df["send"] / (pivot_df["send"] + pivot_df["open"]), 2
)
pivot_df["open_perc"] = round(
100 * pivot_df["open"] / (pivot_df["send"] + pivot_df["open"]), 2
)
return pivot_df[["age_bucket", "send_perc", "open_perc"]]
|
3,056 |
Snaps Analysis
|
Medium
|
<p>Table: <code>Activities</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| activity_id | int |
| user_id | int |
| activity_type | enum |
| time_spent | decimal |
+---------------+---------+
activity_id is column of unique values for this table.
activity_type is an ENUM (category) type of ('send', 'open').
This table contains activity id, user id, activity type and time spent.
</pre>
<p>Table: <code>Age</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| age_bucket | enum |
+-------------+------+
user_id is the column of unique values for this table.
age_bucket is an ENUM (category) type of ('21-25', '26-30', '31-35').
This table contains user id and age group.</pre>
<p>Write a solution to calculate the <strong>percentage</strong> of the total time spent on <strong>sending</strong> and <strong>opening snaps</strong> for <strong>each age group</strong>. Precentage should be <strong>rounded</strong> to <code>2</code> decimal places.</p>
<p>Return <em>the result table </em><em>in <strong>any</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Activities table:
+-------------+---------+---------------+------------+
| activity_id | user_id | activity_type | time_spent |
+-------------+---------+---------------+------------+
| 7274 | 123 | open | 4.50 |
| 2425 | 123 | send | 3.50 |
| 1413 | 456 | send | 5.67 |
| 2536 | 456 | open | 3.00 |
| 8564 | 456 | send | 8.24 |
| 5235 | 789 | send | 6.24 |
| 4251 | 123 | open | 1.25 |
| 1435 | 789 | open | 5.25 |
+-------------+---------+---------------+------------+
Age table:
+---------+------------+
| user_id | age_bucket |
+---------+------------+
| 123 | 31-35 |
| 789 | 21-25 |
| 456 | 26-30 |
+---------+------------+
<strong>Output:</strong>
+------------+-----------+-----------+
| age_bucket | send_perc | open_perc |
+------------+-----------+-----------+
| 31-35 | 37.84 | 62.16 |
| 26-30 | 82.26 | 17.74 |
| 21-25 | 54.31 | 45.69 |
+------------+-----------+-----------+
<strong>Explanation:</strong>
For age group 31-35:
- There is only one user belonging to this group with the user ID 123.
- The total time spent on sending snaps by this user is 3.50, and the time spent on opening snaps is 4.50 + 1.25 = 5.75.
- The overall time spent by this user is 3.50 + 5.75 = 9.25.
- Therefore, the sending snap percentage will be (3.50 / 9.25) * 100 = 37.84, and the opening snap percentage will be (5.75 / 9.25) * 100 = 62.16.
For age group 26-30:
- There is only one user belonging to this group with the user ID 456.
- The total time spent on sending snaps by this user is 5.67 + 8.24 = 13.91, and the time spent on opening snaps is 3.00.
- The overall time spent by this user is 13.91 + 3.00 = 16.91.
- Therefore, the sending snap percentage will be (13.91 / 16.91) * 100 = 82.26, and the opening snap percentage will be (3.00 / 16.91) * 100 = 17.74.
For age group 21-25:
- There is only one user belonging to this group with the user ID 789.
- The total time spent on sending snaps by this user is 6.24, and the time spent on opening snaps is 5.25.
- The overall time spent by this user is 6.24 + 5.25 = 11.49.
- Therefore, the sending snap percentage will be (6.24 / 11.49) * 100 = 54.31, and the opening snap percentage will be (5.25 / 11.49) * 100 = 45.69.
All percentages in output table rounded to the two decimal places.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
age_bucket,
ROUND(100 * SUM(IF(activity_type = 'send', time_spent, 0)) / SUM(time_spent), 2) AS send_perc,
ROUND(100 * SUM(IF(activity_type = 'open', time_spent, 0)) / SUM(time_spent), 2) AS open_perc
FROM
Activities
JOIN Age USING (user_id)
GROUP BY 1;
|
3,057 |
Employees Project Allocation
|
Hard
|
<p>Table: <code>Project</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
| workload | int |
+-------------+---------+
employee_id is the primary key (column with unique values) of this table.
employee_id is a foreign key (reference column) to <code>Employee</code> table.
Each row of this table indicates that the employee with employee_id is working on the project with project_id and the workload of the project.
</pre>
<p>Table: <code>Employees</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| team | varchar |
+------------------+---------+
employee_id is the primary key (column with unique values) of this table.
Each row of this table contains information about one employee.
</pre>
<p>Write a solution to find the <strong>employees</strong> who are allocated to projects with a <strong>workload that exceeds the average</strong> workload of all employees for <strong>their respective teams</strong></p>
<p>Return t<em>he result table ordered by</em> <code>employee_id</code>, <code>project_id</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Project table:
+-------------+-------------+----------+
| project_id | employee_id | workload |
+-------------+-------------+----------+
| 1 | 1 | 45 |
| 1 | 2 | 90 |
| 2 | 3 | 12 |
| 2 | 4 | 68 |
+-------------+-------------+----------+
Employees table:
+-------------+--------+------+
| employee_id | name | team |
+-------------+--------+------+
| 1 | Khaled | A |
| 2 | Ali | B |
| 3 | John | B |
| 4 | Doe | A |
+-------------+--------+------+
<strong>Output:</strong>
+-------------+------------+---------------+------------------+
| employee_id | project_id | employee_name | project_workload |
+-------------+------------+---------------+------------------+
| 2 | 1 | Ali | 90 |
| 4 | 2 | Doe | 68 |
+-------------+------------+---------------+------------------+
<strong>Explanation:</strong>
- Employee with ID 1 has a project workload of 45 and belongs to Team A, where the average workload is 56.50. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 2 has a project workload of 90 and belongs to Team B, where the average workload is 51.00. Since his project workload does exceed the team's average workload, he will be included.
- Employee with ID 3 has a project workload of 12 and belongs to Team B, where the average workload is 51.00. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 4 has a project workload of 68 and belongs to Team A, where the average workload is 56.50. Since his project workload does exceed the team's average workload, he will be included.
Result table orderd by employee_id, project_id in ascending order.
</pre>
|
Database
|
Python
|
import pandas as pd
def employees_with_above_avg_workload(
project: pd.DataFrame, employees: pd.DataFrame
) -> pd.DataFrame:
merged_df = pd.merge(project, employees, on="employee_id")
avg_workload_per_team = merged_df.groupby("team")["workload"].mean().reset_index()
merged_df = pd.merge(
merged_df, avg_workload_per_team, on="team", suffixes=("", "_avg")
)
ans = merged_df[merged_df["workload"] > merged_df["workload_avg"]]
ans = ans[["employee_id", "project_id", "name", "workload"]]
ans = ans.rename(columns={"name": "employee_name", "workload": "project_workload"})
return ans.sort_values(by=["employee_id", "project_id"])
|
3,057 |
Employees Project Allocation
|
Hard
|
<p>Table: <code>Project</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
| workload | int |
+-------------+---------+
employee_id is the primary key (column with unique values) of this table.
employee_id is a foreign key (reference column) to <code>Employee</code> table.
Each row of this table indicates that the employee with employee_id is working on the project with project_id and the workload of the project.
</pre>
<p>Table: <code>Employees</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| team | varchar |
+------------------+---------+
employee_id is the primary key (column with unique values) of this table.
Each row of this table contains information about one employee.
</pre>
<p>Write a solution to find the <strong>employees</strong> who are allocated to projects with a <strong>workload that exceeds the average</strong> workload of all employees for <strong>their respective teams</strong></p>
<p>Return t<em>he result table ordered by</em> <code>employee_id</code>, <code>project_id</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Project table:
+-------------+-------------+----------+
| project_id | employee_id | workload |
+-------------+-------------+----------+
| 1 | 1 | 45 |
| 1 | 2 | 90 |
| 2 | 3 | 12 |
| 2 | 4 | 68 |
+-------------+-------------+----------+
Employees table:
+-------------+--------+------+
| employee_id | name | team |
+-------------+--------+------+
| 1 | Khaled | A |
| 2 | Ali | B |
| 3 | John | B |
| 4 | Doe | A |
+-------------+--------+------+
<strong>Output:</strong>
+-------------+------------+---------------+------------------+
| employee_id | project_id | employee_name | project_workload |
+-------------+------------+---------------+------------------+
| 2 | 1 | Ali | 90 |
| 4 | 2 | Doe | 68 |
+-------------+------------+---------------+------------------+
<strong>Explanation:</strong>
- Employee with ID 1 has a project workload of 45 and belongs to Team A, where the average workload is 56.50. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 2 has a project workload of 90 and belongs to Team B, where the average workload is 51.00. Since his project workload does exceed the team's average workload, he will be included.
- Employee with ID 3 has a project workload of 12 and belongs to Team B, where the average workload is 51.00. Since his project workload does not exceed the team's average workload, he will be excluded.
- Employee with ID 4 has a project workload of 68 and belongs to Team A, where the average workload is 56.50. Since his project workload does exceed the team's average workload, he will be included.
Result table orderd by employee_id, project_id in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT team, AVG(workload) AS avg_workload
FROM
Project
JOIN Employees USING (employee_id)
GROUP BY 1
)
SELECT
employee_id,
project_id,
name AS employee_name,
workload AS project_workload
FROM
Project
JOIN Employees USING (employee_id)
JOIN T USING (team)
WHERE workload > avg_workload
ORDER BY 1, 2;
|
3,058 |
Friends With No Mutual Friends
|
Medium
|
<p>Table: <code>Friends</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id1 | int |
| user_id2 | int |
+-------------+------+
(user_id1, user_id2) is the primary key (combination of columns with unique values) for this table.
Each row contains user id1, user id2, both of whom are friends with each other.
</pre>
<p>Write a solution to find <strong>all</strong> <strong>pairs</strong> of users who are friends with each other and have <strong>no mutual</strong> friends.</p>
<p>Return <em>the result table ordered by </em><code>user_id1,</code> <code>user_id2</code><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Friends table:
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 1 | 5 |
| 6 | 7 |
| 3 | 4 |
| 2 | 5 |
| 8 | 9 |
+----------+----------+
<strong>Output:</strong>
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 6 | 7 |
| 8 | 9 |
+----------+----------+
<strong>Explanation:</strong>
- Users 1 and 2 are friends with each other, but they share a mutual friend with user ID 5, so this pair is not included.
- Users 2 and 3 are friends, they both share a mutual friend with user ID 4, resulting in exclusion, similarly for users 2 and 4 who share a mutual friend with user ID 3, hence not included.
- Users 1 and 5 are friends with each other, but they share a mutual friend with user ID 2, so this pair is not included.
- Users 6 and 7, as well as users 8 and 9, are friends with each other, and they don't have any mutual friends, hence included.
- Users 3 and 4 are friends with each other, but their mutual connection with user ID 2 means they are not included, similarly for users 2 and 5 are friends but are excluded due to their mutual connection with user ID 1.
Output table is ordered by user_id1 in ascending order.</pre>
|
Database
|
Python
|
import pandas as pd
def friends_with_no_mutual_friends(friends: pd.DataFrame) -> pd.DataFrame:
cp = friends.copy()
t = cp[["user_id1", "user_id2"]].copy()
t = pd.concat(
[
t,
cp[["user_id2", "user_id1"]].rename(
columns={"user_id2": "user_id1", "user_id1": "user_id2"}
),
]
)
merged = t.merge(t, left_on="user_id2", right_on="user_id2")
ans = cp[
~cp.apply(
lambda x: (x["user_id1"], x["user_id2"])
in zip(merged["user_id1_x"], merged["user_id1_y"]),
axis=1,
)
]
return ans.sort_values(by=["user_id1", "user_id2"])
|
3,058 |
Friends With No Mutual Friends
|
Medium
|
<p>Table: <code>Friends</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id1 | int |
| user_id2 | int |
+-------------+------+
(user_id1, user_id2) is the primary key (combination of columns with unique values) for this table.
Each row contains user id1, user id2, both of whom are friends with each other.
</pre>
<p>Write a solution to find <strong>all</strong> <strong>pairs</strong> of users who are friends with each other and have <strong>no mutual</strong> friends.</p>
<p>Return <em>the result table ordered by </em><code>user_id1,</code> <code>user_id2</code><em> in <strong>ascending</strong></em><em><strong> </strong>order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Friends table:
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 1 | 5 |
| 6 | 7 |
| 3 | 4 |
| 2 | 5 |
| 8 | 9 |
+----------+----------+
<strong>Output:</strong>
+----------+----------+
| user_id1 | user_id2 |
+----------+----------+
| 6 | 7 |
| 8 | 9 |
+----------+----------+
<strong>Explanation:</strong>
- Users 1 and 2 are friends with each other, but they share a mutual friend with user ID 5, so this pair is not included.
- Users 2 and 3 are friends, they both share a mutual friend with user ID 4, resulting in exclusion, similarly for users 2 and 4 who share a mutual friend with user ID 3, hence not included.
- Users 1 and 5 are friends with each other, but they share a mutual friend with user ID 2, so this pair is not included.
- Users 6 and 7, as well as users 8 and 9, are friends with each other, and they don't have any mutual friends, hence included.
- Users 3 and 4 are friends with each other, but their mutual connection with user ID 2 means they are not included, similarly for users 2 and 5 are friends but are excluded due to their mutual connection with user ID 1.
Output table is ordered by user_id1 in ascending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT user_id1, user_id2 FROM Friends
UNION ALL
SELECT user_id2, user_id1 FROM Friends
)
SELECT user_id1, user_id2
FROM Friends
WHERE
(user_id1, user_id2) NOT IN (
SELECT t1.user_id1, t2.user_id1
FROM
T AS t1
JOIN T AS t2 ON t1.user_id2 = t2.user_id2
)
ORDER BY 1, 2;
|
3,059 |
Find All Unique Email Domains
|
Easy
|
<p>Table: <code>Emails</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
</pre>
<p>Write a solution to find all <strong>unique email domains</strong> and count the number of <strong>individuals</strong> associated with each domain. <strong>Consider only</strong> those domains that <strong>end</strong> with <strong>.com</strong>.</p>
<p>Return <em>the result table orderd by email domains in </em><strong>ascending</strong><em> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Emails table:
+-----+-----------------------+
| id | email |
+-----+-----------------------+
| 336 | [email protected] |
| 489 | [email protected] |
| 449 | [email protected] |
| 95 | [email protected] |
| 320 | [email protected] |
| 411 | [email protected] |
+----+------------------------+
<strong>Output:</strong>
+--------------+-------+
| email_domain | count |
+--------------+-------+
| outlook.com | 2 |
| yahoo.com | 1 |
+--------------+-------+
<strong>Explanation:</strong>
- The valid domains ending with ".com" are only "outlook.com" and "yahoo.com", with respective counts of 2 and 1.
Output table is ordered by email_domains in ascending order.
</pre>
|
Database
|
Python
|
import pandas as pd
def find_unique_email_domains(emails: pd.DataFrame) -> pd.DataFrame:
emails["email_domain"] = emails["email"].str.split("@").str[-1]
emails = emails[emails["email"].str.contains(".com")]
return (
emails.groupby("email_domain")
.size()
.reset_index(name="count")
.sort_values(by="email_domain")
)
|
3,059 |
Find All Unique Email Domains
|
Easy
|
<p>Table: <code>Emails</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
</pre>
<p>Write a solution to find all <strong>unique email domains</strong> and count the number of <strong>individuals</strong> associated with each domain. <strong>Consider only</strong> those domains that <strong>end</strong> with <strong>.com</strong>.</p>
<p>Return <em>the result table orderd by email domains in </em><strong>ascending</strong><em> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Emails table:
+-----+-----------------------+
| id | email |
+-----+-----------------------+
| 336 | [email protected] |
| 489 | [email protected] |
| 449 | [email protected] |
| 95 | [email protected] |
| 320 | [email protected] |
| 411 | [email protected] |
+----+------------------------+
<strong>Output:</strong>
+--------------+-------+
| email_domain | count |
+--------------+-------+
| outlook.com | 2 |
| yahoo.com | 1 |
+--------------+-------+
<strong>Explanation:</strong>
- The valid domains ending with ".com" are only "outlook.com" and "yahoo.com", with respective counts of 2 and 1.
Output table is ordered by email_domains in ascending order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT SUBSTRING_INDEX(email, '@', -1) AS email_domain, COUNT(1) AS count
FROM Emails
WHERE email LIKE '%.com'
GROUP BY 1
ORDER BY 1;
|
3,060 |
User Activities within Time Bounds
|
Hard
|
<p>Table: <code>Sessions</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| user_id | int |
| session_start | datetime |
| session_end | datetime |
| session_id | int |
| session_type | enum |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.
</pre>
<p>Write a solution to find the the <strong>users</strong> who have had <strong>at least two</strong><strong> session</strong> of the <strong>same</strong> type (either '<strong>Viewer</strong>' or '<strong>Streamer</strong>') with a <strong>maximum</strong> gap of <code>12</code> hours <strong>between</strong> sessions.</p>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <b>ascending</b> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<pre>
<strong>Input:</strong>
Sessions table:
+---------+---------------------+---------------------+------------+--------------+
| user_id | session_start | session_end | session_id | session_type |
+---------+---------------------+---------------------+------------+--------------+
| 101 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 1 | Viewer |
| 101 | 2023-11-01 10:00:00 | 2023-11-01 11:00:00 | 2 | Streamer |
| 102 | 2023-11-01 13:00:00 | 2023-11-01 14:00:00 | 3 | Viewer |
| 102 | 2023-11-01 15:00:00 | 2023-11-01 16:00:00 | 4 | Viewer |
| 101 | 2023-11-02 09:00:00 | 2023-11-02 10:00:00 | 5 | Viewer |
| 102 | 2023-11-02 12:00:00 | 2023-11-02 13:00:00 | 6 | Streamer |
| 101 | 2023-11-02 13:00:00 | 2023-11-02 14:00:00 | 7 | Streamer |
| 102 | 2023-11-02 16:00:00 | 2023-11-02 17:00:00 | 8 | Viewer |
| 103 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 9 | Viewer |
| 103 | 2023-11-02 20:00:00 | 2023-11-02 23:00:00 | 10 | Viewer |
| 103 | 2023-11-03 09:00:00 | 2023-11-03 10:00:00 | 11 | Viewer |
+---------+---------------------+---------------------+------------+--------------+
<strong>Output:</strong>
+---------+
| user_id |
+---------+
| 102 |
| 103 |
+---------+
<strong>Explanation:</strong>
- User ID 101 will not be included in the final output as they do not have any two sessions of the same session type.
- User ID 102 will be included in the final output as they had two viewer sessions with session IDs 3 and 4, respectively, and the time gap between them was less than 12 hours.
- User ID 103 participated in two viewer sessions with a gap of less than 12 hours between them, identified by session IDs 10 and 11. Therefore, user 103 will be included in the final output.
Output table is ordered by user_id in increasing order.
</pre>
|
Database
|
Python
|
import pandas as pd
def user_activities(sessions: pd.DataFrame) -> pd.DataFrame:
sessions = sessions.sort_values(by=["user_id", "session_start"])
sessions["prev_session_end"] = sessions.groupby(["user_id", "session_type"])[
"session_end"
].shift(1)
sessions_filtered = sessions[
sessions["session_start"] - sessions["prev_session_end"]
<= pd.Timedelta(hours=12)
]
return pd.DataFrame({"user_id": sessions_filtered["user_id"].unique()})
|
3,060 |
User Activities within Time Bounds
|
Hard
|
<p>Table: <code>Sessions</code></p>
<pre>
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| user_id | int |
| session_start | datetime |
| session_end | datetime |
| session_id | int |
| session_type | enum |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.
</pre>
<p>Write a solution to find the the <strong>users</strong> who have had <strong>at least two</strong><strong> session</strong> of the <strong>same</strong> type (either '<strong>Viewer</strong>' or '<strong>Streamer</strong>') with a <strong>maximum</strong> gap of <code>12</code> hours <strong>between</strong> sessions.</p>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <b>ascending</b> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<pre>
<strong>Input:</strong>
Sessions table:
+---------+---------------------+---------------------+------------+--------------+
| user_id | session_start | session_end | session_id | session_type |
+---------+---------------------+---------------------+------------+--------------+
| 101 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 1 | Viewer |
| 101 | 2023-11-01 10:00:00 | 2023-11-01 11:00:00 | 2 | Streamer |
| 102 | 2023-11-01 13:00:00 | 2023-11-01 14:00:00 | 3 | Viewer |
| 102 | 2023-11-01 15:00:00 | 2023-11-01 16:00:00 | 4 | Viewer |
| 101 | 2023-11-02 09:00:00 | 2023-11-02 10:00:00 | 5 | Viewer |
| 102 | 2023-11-02 12:00:00 | 2023-11-02 13:00:00 | 6 | Streamer |
| 101 | 2023-11-02 13:00:00 | 2023-11-02 14:00:00 | 7 | Streamer |
| 102 | 2023-11-02 16:00:00 | 2023-11-02 17:00:00 | 8 | Viewer |
| 103 | 2023-11-01 08:00:00 | 2023-11-01 09:00:00 | 9 | Viewer |
| 103 | 2023-11-02 20:00:00 | 2023-11-02 23:00:00 | 10 | Viewer |
| 103 | 2023-11-03 09:00:00 | 2023-11-03 10:00:00 | 11 | Viewer |
+---------+---------------------+---------------------+------------+--------------+
<strong>Output:</strong>
+---------+
| user_id |
+---------+
| 102 |
| 103 |
+---------+
<strong>Explanation:</strong>
- User ID 101 will not be included in the final output as they do not have any two sessions of the same session type.
- User ID 102 will be included in the final output as they had two viewer sessions with session IDs 3 and 4, respectively, and the time gap between them was less than 12 hours.
- User ID 103 participated in two viewer sessions with a gap of less than 12 hours between them, identified by session IDs 10 and 11. Therefore, user 103 will be included in the final output.
Output table is ordered by user_id in increasing order.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
user_id,
session_start,
LAG(session_end) OVER (
PARTITION BY user_id, session_type
ORDER BY session_end
) AS prev_session_end
FROM Sessions
)
SELECT DISTINCT
user_id
FROM T
WHERE TIMESTAMPDIFF(HOUR, prev_session_end, session_start) <= 12;
|
3,061 |
Calculate Trapping Rain Water
|
Hard
|
<p>Table: <font face="monospace">Heights</font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| height | int |
+-------------+------+
id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
Each row of this table contains an id and height.
</pre>
<p>Write a solution to calculate the amount of rainwater can be <strong>trapped between the bars</strong> in the landscape, considering that each bar has a <strong>width</strong> of <code>1</code> unit.</p>
<p>Return <em>the result table in </em><strong>any</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Heights table:
+-----+--------+
| id | height |
+-----+--------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| 9 | 2 |
| 10 | 1 |
| 11 | 2 |
| 12 | 1 |
+-----+--------+
<strong>Output:</strong>
+---------------------+
| total_trapped_water |
+---------------------+
| 6 |
+---------------------+
<strong>Explanation:</strong>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3061.Calculate%20Trapping%20Rain%20Water/images/trapping_rain_water.png" style="width:500px; height:200px;" />
The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
</pre>
|
Database
|
Python
|
import pandas as pd
def calculate_trapped_rain_water(heights: pd.DataFrame) -> pd.DataFrame:
heights["l"] = heights["height"].cummax()
heights["r"] = heights["height"][::-1].cummax()[::-1]
heights["trapped_water"] = heights[["l", "r"]].min(axis=1) - heights["height"]
return pd.DataFrame({"total_trapped_water": [heights["trapped_water"].sum()]})
|
3,061 |
Calculate Trapping Rain Water
|
Hard
|
<p>Table: <font face="monospace">Heights</font></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| height | int |
+-------------+------+
id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
Each row of this table contains an id and height.
</pre>
<p>Write a solution to calculate the amount of rainwater can be <strong>trapped between the bars</strong> in the landscape, considering that each bar has a <strong>width</strong> of <code>1</code> unit.</p>
<p>Return <em>the result table in </em><strong>any</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Heights table:
+-----+--------+
| id | height |
+-----+--------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| 9 | 2 |
| 10 | 1 |
| 11 | 2 |
| 12 | 1 |
+-----+--------+
<strong>Output:</strong>
+---------------------+
| total_trapped_water |
+---------------------+
| 6 |
+---------------------+
<strong>Explanation:</strong>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3061.Calculate%20Trapping%20Rain%20Water/images/trapping_rain_water.png" style="width:500px; height:200px;" />
The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
MAX(height) OVER (ORDER BY id) AS l,
MAX(height) OVER (ORDER BY id DESC) AS r
FROM Heights
)
SELECT SUM(LEAST(l, r) - height) AS total_trapped_water
FROM T;
|
3,062 |
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
string gameResult(ListNode* head) {
int odd = 0, even = 0;
for (; head != nullptr; head = head->next->next) {
int a = head->val;
int b = head->next->val;
odd += a < b;
even += a > b;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
};
|
3,062 |
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func gameResult(head *ListNode) string {
var odd, even int
for ; head != nil; head = head.Next.Next {
a, b := head.Val, head.Next.Val
if a < b {
odd++
}
if a > b {
even++
}
}
if odd > even {
return "Odd"
}
if odd < even {
return "Even"
}
return "Tie"
}
|
3,062 |
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Java
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public String gameResult(ListNode head) {
int odd = 0, even = 0;
for (; head != null; head = head.next.next) {
int a = head.val;
int b = head.next.val;
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return "Odd";
}
if (odd < even) {
return "Even";
}
return "Tie";
}
}
|
3,062 |
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def gameResult(self, head: Optional[ListNode]) -> str:
odd = even = 0
while head:
a = head.val
b = head.next.val
odd += a < b
even += a > b
head = head.next.next
if odd > even:
return "Odd"
if odd < even:
return "Even"
return "Tie"
|
3,062 |
Winner of the Linked List Game
|
Easy
|
<p>You are given the <code>head</code> of a linked list of <strong>even</strong> length containing integers.</p>
<p>Each <strong>odd-indexed</strong> node contains an odd integer and each <strong>even-indexed</strong> node contains an even integer.</p>
<p>We call each even-indexed node and its next node a <strong>pair</strong>, e.g., the nodes with indices <code>0</code> and <code>1</code> are a pair, the nodes with indices <code>2</code> and <code>3</code> are a pair, and so on.</p>
<p>For every <strong>pair</strong>, we compare the values of the nodes in the pair:</p>
<ul>
<li>If the odd-indexed node is higher, the <code>"Odd"</code> team gets a point.</li>
<li>If the even-indexed node is higher, the <code>"Even"</code> team gets a point.</li>
</ul>
<p>Return <em>the name of the team with the <strong>higher</strong> points, if the points are equal, return</em> <code>"Tie"</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Even" </span></p>
<p><strong>Explanation: </strong> There is only one pair in this linked list and that is <code>(2,1)</code>. Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Hence, the answer would be <code>"Even"</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [2,5,4,7,20,5] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Odd" </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(2,5)</code> -> Since <code>2 < 5</code>, The Odd team gets the point.</p>
<p><code>(4,7)</code> -> Since <code>4 < 7</code>, The Odd team gets the point.</p>
<p><code>(20,5)</code> -> Since <code>20 > 5</code>, The Even team gets the point.</p>
<p>The Odd team earned <code>2</code> points while the Even team got <code>1</code> point and the Odd team has the higher points.</p>
<p>Hence, the answer would be <code>"Odd"</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [4,5,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> "Tie" </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> pairs in this linked list. Let's investigate each pair individually:</p>
<p><code>(4,5)</code> -> Since <code>4 < 5</code>, the Odd team gets the point.</p>
<p><code>(2,1)</code> -> Since <code>2 > 1</code>, the Even team gets the point.</p>
<p>Both teams earned <code>1</code> point.</p>
<p>Hence, the answer would be <code>"Tie"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[2, 100]</code>.</li>
<li>The number of nodes in the list is even.</li>
<li><code>1 <= Node.val <= 100</code></li>
<li>The value of each odd-indexed node is odd.</li>
<li>The value of each even-indexed node is even.</li>
</ul>
|
Linked List
|
TypeScript
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function gameResult(head: ListNode | null): string {
let [odd, even] = [0, 0];
for (; head; head = head.next.next) {
const [a, b] = [head.val, head.next.val];
odd += a < b ? 1 : 0;
even += a > b ? 1 : 0;
}
if (odd > even) {
return 'Odd';
}
if (odd < even) {
return 'Even';
}
return 'Tie';
}
|
3,063 |
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* frequenciesOfElements(ListNode* head) {
unordered_map<int, int> cnt;
for (; head; head = head->next) {
cnt[head->val]++;
}
ListNode* dummy = new ListNode();
for (auto& [_, val] : cnt) {
dummy->next = new ListNode(val, dummy->next);
}
return dummy->next;
}
};
|
3,063 |
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func frequenciesOfElements(head *ListNode) *ListNode {
cnt := map[int]int{}
for ; head != nil; head = head.Next {
cnt[head.Val]++
}
dummy := &ListNode{}
for _, val := range cnt {
dummy.Next = &ListNode{val, dummy.Next}
}
return dummy.Next
}
|
3,063 |
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Java
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode frequenciesOfElements(ListNode head) {
Map<Integer, Integer> cnt = new HashMap<>();
for (; head != null; head = head.next) {
cnt.merge(head.val, 1, Integer::sum);
}
ListNode dummy = new ListNode();
for (int val : cnt.values()) {
dummy.next = new ListNode(val, dummy.next);
}
return dummy.next;
}
}
|
3,063 |
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]:
cnt = Counter()
while head:
cnt[head.val] += 1
head = head.next
dummy = ListNode()
for val in cnt.values():
dummy.next = ListNode(val, dummy.next)
return dummy.next
|
3,063 |
Linked List Frequency
|
Easy
|
<p>Given the <code>head</code> of a linked list containing <code>k</code> <strong>distinct</strong> elements, return <em>the head to a linked list of length </em><code>k</code><em> containing the <span data-keyword="frequency-linkedlist">frequency</span> of each <strong>distinct</strong> element in the given linked list in <strong>any order</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,1,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [3,2,1] </span></p>
<p><strong>Explanation: </strong> There are <code>3</code> distinct elements in the list. The frequency of <code>1</code> is <code>3</code>, the frequency of <code>2</code> is <code>2</code> and the frequency of <code>3</code> is <code>1</code>. Hence, we return <code>3 -> 2 -> 1</code>.</p>
<p>Note that <code>1 -> 2 -> 3</code>, <code>1 -> 3 -> 2</code>, <code>2 -> 1 -> 3</code>, <code>2 -> 3 -> 1</code>, and <code>3 -> 1 -> 2</code> are also valid answers.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [1,1,2,2,2] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [2,3] </span></p>
<p><strong>Explanation: </strong> There are <code>2</code> distinct elements in the list. The frequency of <code>1</code> is <code>2</code> and the frequency of <code>2</code> is <code>3</code>. Hence, we return <code>2 -> 3</code>.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> head = [6,5,4,3,2,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> [1,1,1,1,1,1] </span></p>
<p><strong>Explanation: </strong> There are <code>6</code> distinct elements in the list. The frequency of each of them is <code>1</code>. Hence, we return <code>1 -> 1 -> 1 -> 1 -> 1 -> 1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
</ul>
|
Hash Table; Linked List; Counting
|
TypeScript
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function frequenciesOfElements(head: ListNode | null): ListNode | null {
const cnt: Map<number, number> = new Map();
for (; head; head = head.next) {
cnt.set(head.val, (cnt.get(head.val) || 0) + 1);
}
const dummy = new ListNode();
for (const val of cnt.values()) {
dummy.next = new ListNode(val, dummy.next);
}
return dummy.next;
}
|
3,064 |
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
C++
|
/**
* Definition of commonSetBits API.
* int commonSetBits(int num);
*/
class Solution {
public:
int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
if (commonSetBits(1 << i)) {
n |= 1 << i;
}
}
return n;
}
};
|
3,064 |
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Go
|
/**
* Definition of commonSetBits API.
* func commonSetBits(num int) int;
*/
func findNumber() (n int) {
for i := 0; i < 32; i++ {
if commonSetBits(1<<i) > 0 {
n |= 1 << i
}
}
return
}
|
3,064 |
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Java
|
/**
* Definition of commonSetBits API (defined in the parent class Problem).
* int commonSetBits(int num);
*/
public class Solution extends Problem {
public int findNumber() {
int n = 0;
for (int i = 0; i < 32; ++i) {
if (commonSetBits(1 << i) > 0) {
n |= 1 << i;
}
}
return n;
}
}
|
3,064 |
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
Python
|
# Definition of commonSetBits API.
# def commonSetBits(num: int) -> int:
class Solution:
def findNumber(self) -> int:
return sum(1 << i for i in range(32) if commonSetBits(1 << i))
|
3,064 |
Guess the Number Using Bitwise Questions I
|
Medium
|
<p>There is a number <code>n</code> that you have to find.</p>
<p>There is also a pre-defined API <code>int commonSetBits(int num)</code>, which returns the number of bits where both <code>n</code> and <code>num</code> are <code>1</code> in that position of their binary representation. In other words, it returns the number of <span data-keyword="set-bit">set bits</span> in <code>n & num</code>, where <code>&</code> is the bitwise <code>AND</code> operator.</p>
<p>Return <em>the number</em> <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 31 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 31 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>31</code> using the provided API.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> n = 33 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 33 </span></p>
<p><strong>Explanation: </strong> It can be proven that it's possible to find <code>33</code> using the provided API.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>30</sup> - 1</code></li>
<li><code>0 <= num <= 2<sup>30</sup> - 1</code></li>
<li>If you ask for some <code>num</code> out of the given range, the output wouldn't be reliable.</li>
</ul>
|
Bit Manipulation; Interactive
|
TypeScript
|
/**
* Definition of commonSetBits API.
* var commonSetBits = function(num: number): number {}
*/
function findNumber(): number {
let n = 0;
for (let i = 0; i < 32; ++i) {
if (commonSetBits(1 << i)) {
n |= 1 << i;
}
}
return n;
}
|
3,065 |
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
int ans = 0;
for (int x : nums) {
if (x < k) {
++ans;
}
}
return ans;
}
};
|
3,065 |
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Go
|
func minOperations(nums []int, k int) (ans int) {
for _, x := range nums {
if x < k {
ans++
}
}
return
}
|
3,065 |
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
int ans = 0;
for (int x : nums) {
if (x < k) {
++ans;
}
}
return ans;
}
}
|
3,065 |
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(x < k for x in nums)
|
3,065 |
Minimum Operations to Exceed Threshold Value I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>In one operation, you can remove one occurrence of the smallest element of <code>nums</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations needed so that all elements of the array are greater than or equal to</em> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,11,10,1,3], k = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2,4,9], k = 9
<strong>Output:</strong> 4
<strong>Explanation:</strong> only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that there is at least one index <code>i</code> such that <code>nums[i] >= k</code>.</li>
</ul>
|
Array
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
return nums.filter(x => x < k).length;
}
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
using ll = long long;
priority_queue<ll, vector<ll>, greater<ll>> pq;
for (int x : nums) {
pq.push(x);
}
int ans = 0;
for (; pq.size() > 1 && pq.top() < k; ++ans) {
ll x = pq.top();
pq.pop();
ll y = pq.top();
pq.pop();
pq.push(x * 2 + y);
}
return ans;
}
};
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Go
|
func minOperations(nums []int, k int) (ans int) {
pq := &hp{nums}
heap.Init(pq)
for ; pq.Len() > 1 && pq.IntSlice[0] < k; ans++ {
x, y := heap.Pop(pq).(int), heap.Pop(pq).(int)
heap.Push(pq, x*2+y)
}
return
}
type hp struct{ sort.IntSlice }
func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Pop() interface{} {
old := h.IntSlice
n := len(old)
x := old[n-1]
h.IntSlice = old[0 : n-1]
return x
}
func (h *hp) Push(x interface{}) {
h.IntSlice = append(h.IntSlice, x.(int))
}
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
PriorityQueue<Long> pq = new PriorityQueue<>();
for (int x : nums) {
pq.offer((long) x);
}
int ans = 0;
for (; pq.size() > 1 && pq.peek() < k; ++ans) {
long x = pq.poll(), y = pq.poll();
pq.offer(x * 2 + y);
}
return ans;
}
}
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
heapify(nums)
ans = 0
while len(nums) > 1 and nums[0] < k:
x, y = heappop(nums), heappop(nums)
heappush(nums, x * 2 + y)
ans += 1
return ans
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Rust
|
use std::collections::BinaryHeap;
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
let mut pq = BinaryHeap::new();
for &x in &nums {
pq.push(-(x as i64));
}
let mut ans = 0;
while pq.len() > 1 && -pq.peek().unwrap() < k as i64 {
let x = -pq.pop().unwrap();
let y = -pq.pop().unwrap();
pq.push(-(x * 2 + y));
ans += 1;
}
ans
}
}
|
3,066 |
Minimum Operations to Exceed Threshold Value II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and an integer <code>k</code>.</p>
<p>You are allowed to perform some operations on <code>nums</code>, where in a single operation, you can:</p>
<ul>
<li>Select the two <strong>smallest</strong> integers <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Remove <code>x</code> and <code>y</code> from <code>nums</code>.</li>
<li>Insert <code>(min(x, y) * 2 + max(x, y))</code> at any position in the array.</li>
</ul>
<p><strong>Note</strong> that you can only apply the described operation if <code>nums</code> contains <strong>at least</strong> two elements.</p>
<p>Return the <strong>minimum</strong> number of operations needed so that all elements of the array are <strong>greater than or equal to</strong> <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,11,10,1,3], k = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>In the first operation, we remove elements 1 and 2, then add <code>1 * 2 + 2</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[4, 11, 10, 3]</code>.</li>
<li>In the second operation, we remove elements 3 and 4, then add <code>3 * 2 + 4</code> to <code>nums</code>. <code>nums</code> becomes equal to <code>[10, 11, 10]</code>.</li>
</ol>
<p>At this stage, all the elements of nums are greater than or equal to 10 so we can stop. </p>
<p>It can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.</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,2,4,9], k = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ol>
<li>After one operation, <code>nums</code> becomes equal to <code>[2, 4, 9, 3]</code>. </li>
<li>After two operations, <code>nums</code> becomes equal to <code>[7, 4, 9]</code>. </li>
<li>After three operations, <code>nums</code> becomes equal to <code>[15, 9]</code>. </li>
<li>After four operations, <code>nums</code> becomes equal to <code>[33]</code>.</li>
</ol>
<p>At this stage, all the elements of <code>nums</code> are greater than 20 so we can stop. </p>
<p>It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li>The input is generated such that an answer always exists. That is, after performing some number of operations, all elements of the array are greater than or equal to <code>k</code>.</li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
const pq = new MinPriorityQueue();
for (const x of nums) {
pq.enqueue(x);
}
let ans = 0;
for (; pq.size() > 1 && pq.front().element < k; ++ans) {
const x = pq.dequeue().element;
const y = pq.dequeue().element;
pq.enqueue(x * 2 + y);
}
return ans;
}
|
3,067 |
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
C++
|
class Solution {
public:
vector<int> countPairsOfConnectableServers(vector<vector<int>>& edges, int signalSpeed) {
int n = edges.size() + 1;
vector<pair<int, int>> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1], w = e[2];
g[a].emplace_back(b, w);
g[b].emplace_back(a, w);
}
function<int(int, int, int)> dfs = [&](int a, int fa, int ws) {
int cnt = ws % signalSpeed == 0;
for (auto& [b, w] : g[a]) {
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
};
vector<int> ans(n);
for (int a = 0; a < n; ++a) {
int s = 0;
for (auto& [b, w] : g[a]) {
int t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
};
|
3,067 |
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Go
|
func countPairsOfConnectableServers(edges [][]int, signalSpeed int) []int {
n := len(edges) + 1
type pair struct{ x, w int }
g := make([][]pair, n)
for _, e := range edges {
a, b, w := e[0], e[1], e[2]
g[a] = append(g[a], pair{b, w})
g[b] = append(g[b], pair{a, w})
}
var dfs func(a, fa, ws int) int
dfs = func(a, fa, ws int) int {
cnt := 0
if ws%signalSpeed == 0 {
cnt++
}
for _, e := range g[a] {
b, w := e.x, e.w
if b != fa {
cnt += dfs(b, a, ws+w)
}
}
return cnt
}
ans := make([]int, n)
for a := 0; a < n; a++ {
s := 0
for _, e := range g[a] {
b, w := e.x, e.w
t := dfs(b, a, w)
ans[a] += s * t
s += t
}
}
return ans
}
|
3,067 |
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Java
|
class Solution {
private int signalSpeed;
private List<int[]>[] g;
public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {
int n = edges.length + 1;
g = new List[n];
this.signalSpeed = signalSpeed;
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1], w = e[2];
g[a].add(new int[] {b, w});
g[b].add(new int[] {a, w});
}
int[] ans = new int[n];
for (int a = 0; a < n; ++a) {
int s = 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
int t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
private int dfs(int a, int fa, int ws) {
int cnt = ws % signalSpeed == 0 ? 1 : 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
}
}
|
3,067 |
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
Python
|
class Solution:
def countPairsOfConnectableServers(
self, edges: List[List[int]], signalSpeed: int
) -> List[int]:
def dfs(a: int, fa: int, ws: int) -> int:
cnt = 0 if ws % signalSpeed else 1
for b, w in g[a]:
if b != fa:
cnt += dfs(b, a, ws + w)
return cnt
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b, w in edges:
g[a].append((b, w))
g[b].append((a, w))
ans = [0] * n
for a in range(n):
s = 0
for b, w in g[a]:
t = dfs(b, a, w)
ans[a] += s * t
s += t
return ans
|
3,067 |
Count Pairs of Connectable Servers in a Weighted Tree Network
|
Medium
|
<p>You are given an unrooted weighted tree with <code>n</code> vertices representing servers numbered from <code>0</code> to <code>n - 1</code>, an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code> represents a bidirectional edge between vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> of weight <code>weight<sub>i</sub></code>. You are also given an integer <code>signalSpeed</code>.</p>
<p>Two servers <code>a</code> and <code>b</code> are <strong>connectable</strong> through a server <code>c</code> if:</p>
<ul>
<li><code>a < b</code>, <code>a != c</code> and <code>b != c</code>.</li>
<li>The distance from <code>c</code> to <code>a</code> is divisible by <code>signalSpeed</code>.</li>
<li>The distance from <code>c</code> to <code>b</code> is divisible by <code>signalSpeed</code>.</li>
<li>The path from <code>c</code> to <code>b</code> and the path from <code>c</code> to <code>a</code> do not share any edges.</li>
</ul>
<p>Return <em>an integer array</em> <code>count</code> <em>of length</em> <code>n</code> <em>where</em> <code>count[i]</code> <em>is the <strong>number</strong> of server pairs that are <strong>connectable</strong> through</em> <em>the server</em> <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example22.png" style="width: 438px; height: 243px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
<strong>Output:</strong> [0,4,6,6,4,0]
<strong>Explanation:</strong> Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3067.Count%20Pairs%20of%20Connectable%20Servers%20in%20a%20Weighted%20Tree%20Network/images/example11.png" style="width: 495px; height: 484px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
<strong>Output:</strong> [2,0,0,0,0,0,2]
<strong>Explanation:</strong> Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, weight<sub>i</sub>]</code><!-- notionvc: a2623897-1bb1-4c07-84b6-917ffdcd83ec --></li>
<li><code>1 <= weight<sub>i</sub> <= 10<sup>6</sup></code></li>
<li><code>1 <= signalSpeed <= 10<sup>6</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Array
|
TypeScript
|
function countPairsOfConnectableServers(edges: number[][], signalSpeed: number): number[] {
const n = edges.length + 1;
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (const [a, b, w] of edges) {
g[a].push([b, w]);
g[b].push([a, w]);
}
const dfs = (a: number, fa: number, ws: number): number => {
let cnt = ws % signalSpeed === 0 ? 1 : 0;
for (const [b, w] of g[a]) {
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
};
const ans: number[] = Array(n).fill(0);
for (let a = 0; a < n; ++a) {
let s = 0;
for (const [b, w] of g[a]) {
const t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
C++
|
class Solution {
public:
long long maximumValueSum(vector<int>& nums, int k, vector<vector<int>>& edges) {
long long f0 = 0, f1 = -0x3f3f3f3f;
for (int x : nums) {
long long tmp = f0;
f0 = max(f0 + x, f1 + (x ^ k));
f1 = max(f1 + x, tmp + (x ^ k));
}
return f0;
}
};
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
C#
|
public class Solution {
public long MaximumValueSum(int[] nums, int k, int[][] edges) {
long f0 = 0, f1 = -0x3f3f3f3f;
foreach (int x in nums) {
long tmp = f0;
f0 = Math.Max(f0 + x, f1 + (x ^ k));
f1 = Math.Max(f1 + x, tmp + (x ^ k));
}
return f0;
}
}
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Go
|
func maximumValueSum(nums []int, k int, edges [][]int) int64 {
f0, f1 := 0, -0x3f3f3f3f
for _, x := range nums {
f0, f1 = max(f0+x, f1+(x^k)), max(f1+x, f0+(x^k))
}
return int64(f0)
}
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Java
|
class Solution {
public long maximumValueSum(int[] nums, int k, int[][] edges) {
long f0 = 0, f1 = -0x3f3f3f3f;
for (int x : nums) {
long tmp = f0;
f0 = Math.max(f0 + x, f1 + (x ^ k));
f1 = Math.max(f1 + x, tmp + (x ^ k));
}
return f0;
}
}
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Python
|
class Solution:
def maximumValueSum(self, nums: List[int], k: int, edges: List[List[int]]) -> int:
f0, f1 = 0, -inf
for x in nums:
f0, f1 = max(f0 + x, f1 + (x ^ k)), max(f1 + x, f0 + (x ^ k))
return f0
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
Rust
|
impl Solution {
pub fn maximum_value_sum(nums: Vec<i32>, k: i32, edges: Vec<Vec<i32>>) -> i64 {
let mut f0: i64 = 0;
let mut f1: i64 = i64::MIN;
for &x in &nums {
let tmp = f0;
f0 = std::cmp::max(f0 + x as i64, f1 + (x ^ k) as i64);
f1 = std::cmp::max(f1 + x as i64, tmp + (x ^ k) as i64);
}
f0
}
}
|
3,068 |
Find the Maximum Sum of Node Values
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree. You are also given a <strong>positive</strong> integer <code>k</code>, and a <strong>0-indexed</strong> array of <strong>non-negative</strong> integers <code>nums</code> of length <code>n</code>, where <code>nums[i]</code> represents the <strong>value</strong> of the node numbered <code>i</code>.</p>
<p>Alice wants the sum of values of tree nodes to be <strong>maximum</strong>, for which Alice can perform the following operation <strong>any</strong> number of times (<strong>including zero</strong>) on the tree:</p>
<ul>
<li>Choose any edge <code>[u, v]</code> connecting the nodes <code>u</code> and <code>v</code>, and update their values as follows:
<ul>
<li><code>nums[u] = nums[u] XOR k</code></li>
<li><code>nums[v] = nums[v] XOR k</code></li>
</ul>
</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible <strong>sum</strong> of the <strong>values</strong> Alice can achieve by performing the operation <strong>any</strong> number of times</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Alice can achieve the maximum sum of 6 using a single operation:
- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
The total sum of values is 2 + 2 + 2 = 6.
It can be shown that 6 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2024-01-09-220017.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 300px; height: 239px;" />
<pre>
<strong>Input:</strong> nums = [2,3], k = 7, edges = [[0,1]]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Alice can achieve the maximum sum of 9 using a single operation:
- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
The total sum of values is 5 + 4 = 9.
It can be shown that 9 is the maximum achievable sum of values.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3068.Find%20the%20Maximum%20Sum%20of%20Node%20Values/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
<strong>Output:</strong> 42
<strong>Explanation:</strong> The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edges[i][0], edges[i][1] <= n - 1</code></li>
<li>The input is generated such that <code>edges</code> represent a valid tree.</li>
</ul>
|
Greedy; Bit Manipulation; Tree; Array; Dynamic Programming; Sorting
|
TypeScript
|
function maximumValueSum(nums: number[], k: number, edges: number[][]): number {
let [f0, f1] = [0, -Infinity];
for (const x of nums) {
[f0, f1] = [Math.max(f0 + x, f1 + (x ^ k)), Math.max(f1 + x, f0 + (x ^ k))];
}
return f0;
}
|
3,069 |
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
vector<int> resultArray(vector<int>& nums) {
int n = nums.size();
vector<int> arr1 = {nums[0]};
vector<int> arr2 = {nums[1]};
for (int k = 2; k < n; ++k) {
if (arr1.back() > arr2.back()) {
arr1.push_back(nums[k]);
} else {
arr2.push_back(nums[k]);
}
}
arr1.insert(arr1.end(), arr2.begin(), arr2.end());
return arr1;
}
};
|
3,069 |
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Go
|
func resultArray(nums []int) []int {
arr1 := []int{nums[0]}
arr2 := []int{nums[1]}
for _, x := range nums[2:] {
if arr1[len(arr1)-1] > arr2[len(arr2)-1] {
arr1 = append(arr1, x)
} else {
arr2 = append(arr2, x)
}
}
return append(arr1, arr2...)
}
|
3,069 |
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int[] resultArray(int[] nums) {
int n = nums.length;
int[] arr1 = new int[n];
int[] arr2 = new int[n];
arr1[0] = nums[0];
arr2[0] = nums[1];
int i = 0, j = 0;
for (int k = 2; k < n; ++k) {
if (arr1[i] > arr2[j]) {
arr1[++i] = nums[k];
} else {
arr2[++j] = nums[k];
}
}
for (int k = 0; k <= j; ++k) {
arr1[++i] = arr2[k];
}
return arr1;
}
}
|
3,069 |
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def resultArray(self, nums: List[int]) -> List[int]:
arr1 = [nums[0]]
arr2 = [nums[1]]
for x in nums[2:]:
if arr1[-1] > arr2[-1]:
arr1.append(x)
else:
arr2.append(x)
return arr1 + arr2
|
3,069 |
Distribute Elements Into Two Arrays I
|
Easy
|
<p>You are given a <strong>1-indexed</strong> array of <strong>distinct</strong> integers <code>nums</code> of length <code>n</code>.</p>
<p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p>
<ul>
<li>If the last element of <code>arr1</code> is<strong> greater</strong> than the last element of <code>arr2</code>, append <code>nums[i]</code> to <code>arr1</code>. Otherwise, append <code>nums[i]</code> to <code>arr2</code>.</li>
</ul>
<p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p>
<p>Return <em>the array</em> <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> [2,3,1]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.
After 3 operations, arr1 = [2,3] and arr2 = [1].
Hence, the array result formed by concatenation is [2,3,1].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,3,8]
<strong>Output:</strong> [5,3,4,8]
<strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [4].
In the 3<sup>rd</sup> operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].
In the 4<sup>th</sup> operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].
After 4 operations, arr1 = [5,3] and arr2 = [4,8].
Hence, the array result formed by concatenation is [5,3,4,8].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>All elements in <code>nums</code> are distinct.</li>
</ul>
|
Array; Simulation
|
TypeScript
|
function resultArray(nums: number[]): number[] {
const arr1: number[] = [nums[0]];
const arr2: number[] = [nums[1]];
for (const x of nums.slice(2)) {
if (arr1.at(-1)! > arr2.at(-1)!) {
arr1.push(x);
} else {
arr2.push(x);
}
}
return arr1.concat(arr2);
}
|
3,070 |
Count Submatrices with Top-Left Element and Sum Less Than k
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p>
<p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length </code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= n, m <= 1000 </code></li>
<li><code>0 <= grid[i][j] <= 1000</code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
C++
|
class Solution {
public:
int countSubmatrices(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
int s[m + 1][n + 1];
memset(s, 0, sizeof(s));
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1];
if (s[i][j] <= k) {
++ans;
}
}
}
return ans;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.