id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
2,754
Bind Function to Context
Medium
<p>Enhance all functions to have the&nbsp;<code>bindPolyfill</code>&nbsp;method. When&nbsp;<code>bindPolyfill</code>&nbsp;is called with a passed&nbsp;object <code>obj</code>, that object becomes the&nbsp;<code>this</code>&nbsp;context for the function.</p> <p>For example, if you had the code:</p> <pre> function f() { console.log(&#39;My context is &#39; + this.ctx); } f(); </pre> <p>The output would be <code>&quot;My context is undefined&quot;</code>. However, if you bound the function:</p> <pre> function f() { console.log(&#39;My context is &#39; + this.ctx); } const boundFunc = f.boundPolyfill({ &quot;ctx&quot;: &quot;My Object&quot; }) boundFunc(); </pre> <p>The output should be&nbsp;<code>&quot;My context is My Object&quot;</code>.</p> <p>You may assume that a single non-null object will be passed to the&nbsp;<code>bindPolyfill</code> method.</p> <p>Please solve it without the built-in&nbsp;<code>Function.bind</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = function f(multiplier) { &nbsp; return this.x * multiplier; } obj = {&quot;x&quot;: 10} inputs = [5] <strong>Output:</strong> 50 <strong>Explanation:</strong> const boundFunc = f.bindPolyfill({&quot;x&quot;: 10}); boundFunc(5); // 50 A multiplier of 5 is passed as a parameter. The context is set to {&quot;x&quot;: 10}. Multiplying those two numbers yields 50.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = function speak() { &nbsp; return &quot;My name is &quot; + this.name; } obj = {&quot;name&quot;: &quot;Kathy&quot;} inputs = [] <strong>Output:</strong> &quot;My name is Kathy&quot; <strong>Explanation:</strong> const boundFunc = f.bindPolyfill({&quot;name&quot;: &quot;Kathy&quot;}); boundFunc(); // &quot;My name is Kathy&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a non-null object</li> <li><code>0 &lt;= inputs.length &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Can you solve it without using any built-in methods?</strong>
JavaScript
TypeScript
type Fn = (...args) => any; declare global { interface Function { bindPolyfill(obj: Record<any, any>): Fn; } } Function.prototype.bindPolyfill = function (obj) { return (...args) => { return this.call(obj, ...args); }; };
2,755
Deep Merge of Two Objects
Medium
<p>Given two values&nbsp;<code>obj1</code> and <code>obj2</code>, return a&nbsp;<strong>deepmerged</strong>&nbsp;value.</p> <p>Values should be <strong>deepmerged</strong> according to these rules:</p> <ul> <li>If the two values are objects, the resulting object should have all the keys that exist on either object.&nbsp;If a key belongs to both objects, <strong>deepmerge</strong> the two associated values. Otherwise, add the key-value pair to the resulting object.</li> <li>If the two values are arrays, the resulting array should be the same length as the longer array.&nbsp;Apply the same logic as you would with objects, but treat the indices as keys.</li> <li>Otherwise the resulting value is&nbsp;<code>obj2</code>.</li> </ul> <p>You can assume&nbsp;<code>obj1</code> and <code>obj2</code>&nbsp;are the output of&nbsp;<code>JSON.parse()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj1 = {&quot;a&quot;: 1, &quot;c&quot;: 3}, obj2 = {&quot;a&quot;: 2, &quot;b&quot;: 2} <strong>Output:</strong> {&quot;a&quot;: 2, &quot;c&quot;: 3, &quot;b&quot;: 2} <strong>Explanation:</strong> The value of obj1[&quot;a&quot;] changed to 2 because if both objects have the same key and their value is not an array or object then we change the obj1 value to the obj2 value. Key &quot;b&quot; with value was added to obj1 as it doesn&#39;t exist in obj1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj1 = [{}, 2, 3], obj2 = [[], 5] <strong>Output:</strong> [[], 5, 3] <strong>Explanation:</strong> result[0] = obj2[0] because obj1[0] and obj2[0] have different types. result[2] = obj1[2] because obj2[2] does not exist. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj1 = {&quot;a&quot;: 1, &quot;b&quot;: {&quot;c&quot;: [1 , [2, 7], 5], &quot;d&quot;: 2}}, obj2 = {&quot;a&quot;: 1, &quot;b&quot;: {&quot;c&quot;: [6, [6], [9]], &quot;e&quot;: 3}} <strong>Output:</strong> {&quot;a&quot;: 1, &quot;b&quot;: {&quot;c&quot;: [6, [6, 7], [9]], &quot;d&quot;: 2, &quot;e&quot;: 3}} <strong>Explanation:</strong> Arrays obj1[&quot;b&quot;][&quot;c&quot;] and obj2[&quot;b&quot;][&quot;c&quot;] have been merged in way that obj2 values overwrite obj1 values deeply only if they are not arrays or objects. obj2[&quot;b&quot;][&quot;c&quot;] has key &quot;e&quot; that obj1 doesn&#39;t have so it&#39;s added to obj1. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> obj1 = true, obj2 = null <strong>Output:</strong> null </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj1</code> and <code>obj2</code> are valid JSON values</li> <li><code>1 &lt;= JSON.stringify(obj1).length &lt;= 5&nbsp;* 10<sup>5</sup></code></li> <li><code>1 &lt;= JSON.stringify(obj2).length &lt;= 5&nbsp;* 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
function deepMerge(obj1: any, obj2: any): any { const isObj = (obj: any) => obj && typeof obj === 'object'; const isArr = (obj: any) => Array.isArray(obj); if (!isObj(obj1) || !isObj(obj2)) { return obj2; } if (isArr(obj1) !== isArr(obj2)) { return obj2; } for (const key in obj2) { obj1[key] = deepMerge(obj1[key], obj2[key]); } return obj1; } /** * let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2}; * deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2} */
2,757
Generate Circular Array Values
Medium
<p>Given a <strong>circular</strong> array <code>arr</code> and an integer&nbsp;<code>startIndex</code>, return a generator object&nbsp;<code>gen</code> that yields values from <code>arr</code>.</p> <p>The first time <code>gen.next()</code> is called on the generator, it should should yield&nbsp;<code>arr[startIndex]</code>.</p> <p>Each subsequent time&nbsp;<code>gen.next()</code>&nbsp;is called, an integer <code>jump</code>&nbsp;will be passed into the function (Ex: <code>gen.next(-3)</code>).</p> <ul> <li>If&nbsp;<code>jump</code>&nbsp;is positive, the index should increase by that value, however if the current index is the last index, it should instead jump to the first index.</li> <li>If&nbsp;<code>jump</code>&nbsp;is negative, the index should decrease&nbsp;by the magnitude of that value, however if the current index is the first index, it should instead jump to the last&nbsp;index.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3,4,5], steps = [1,2,6], startIndex = 0 <strong>Output:</strong> [1,2,4,5] <strong>Explanation:</strong> &nbsp; &nbsp;const gen = cycleGenerator(arr, startIndex); &nbsp;gen.next().value; &nbsp;// 1, index = startIndex = 0 &nbsp;gen.next(1).value; // 2, index = 1, 0 -&gt; 1 &nbsp;gen.next(2).value; // 4, index = 3, 1 -&gt; 2 -&gt; 3 &nbsp;gen.next(6).value; // 5, index = 4, 3 -&gt; 4 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [10,11,12,13,14,15], steps = [1,4,0,-1,-3], startIndex = 1 <strong>Output:</strong> [11,12,10,10,15,12] <strong>Explanation:</strong> &nbsp;const gen = cycleGenerator(arr, startIndex); &nbsp;gen.next().value; &nbsp; // 11, index = 1 &nbsp;gen.next(1).value; // 12, index = 2 &nbsp;gen.next(4).value; // 10, index = 0 &nbsp;gen.next(0).value; // 10, index = 0 &nbsp;gen.next(-1).value; // 15, index = 5 &nbsp;gen.next(-3).value; // 12, index = 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [2,4,6,7,8,10], steps = [-4,5,-3,10], startIndex = 3 <strong>Output:</strong> [7,10,8,4,10] <strong>Explanation:</strong> &nbsp; &nbsp;const gen = cycleGenerator(arr, startIndex); &nbsp;gen.next().value &nbsp; // 7, index = 3 &nbsp;gen.next(-4).value // 10, index = 5 &nbsp;gen.next(5).value // 8, index = 4 &nbsp;gen.next(-3).value // 4, index = 1 &nbsp; &nbsp;gen.next(10).value // 10, index = 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= steps.length &lt;= 100</code></li> <li><code>-10<sup>4</sup>&nbsp;&lt;= steps[i],&nbsp;arr[i] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= startIndex &lt;&nbsp;arr.length</code></li> </ul>
JavaScript
TypeScript
function* cycleGenerator(arr: number[], startIndex: number): Generator<number, void, number> { const n = arr.length; while (true) { const jump = yield arr[startIndex]; startIndex = (((startIndex + jump) % n) + n) % n; } } /** * const gen = cycleGenerator([1,2,3,4,5], 0); * gen.next().value // 1 * gen.next(1).value // 2 * gen.next(2).value // 4 * gen.next(6).value // 5 */
2,758
Next Day
Easy
<p>Write code that enhances all date objects such that you can call the <code>date.nextDay()</code>&nbsp;method on any date object and it will return&nbsp;the next day in the format <em>YYYY-MM-DD</em> as a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> date = &quot;2014-06-20&quot; <strong>Output:</strong> &quot;2014-06-21&quot; <strong>Explanation:</strong> const date = new Date(&quot;2014-06-20&quot;); date.nextDay(); // &quot;2014-06-21&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> date = &quot;2017-10-31&quot; <strong>Output:</strong> &quot;2017-11-01&quot; <strong>Explanation:</strong> The day after 2017-10-31 is 2017-11-01. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>new Date(date)</code> is a valid date object</li> </ul>
JavaScript
TypeScript
declare global { interface Date { nextDay(): string; } } Date.prototype.nextDay = function () { const date = new Date(this.valueOf()); date.setDate(date.getDate() + 1); return date.toISOString().slice(0, 10); }; /** * const date = new Date("2014-06-20"); * date.nextDay(); // "2014-06-21" */
2,759
Convert JSON String to Object
Hard
<p>Given a string <code>str</code>, return parsed JSON&nbsp;<code>parsedStr</code>.&nbsp;You may assume the <code>str</code>&nbsp;is a valid JSON string hence it only includes strings, numbers, arrays, objects, booleans, and null. <code>str</code>&nbsp;will not include invisible characters and escape characters.&nbsp;</p> <p>Please solve it without using the built-in&nbsp;<code>JSON.parse</code>&nbsp;method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> str = &#39;{&quot;a&quot;:2,&quot;b&quot;:[1,2,3]}&#39; <strong>Output:</strong> {&quot;a&quot;:2,&quot;b&quot;:[1,2,3]} <strong>Explanation:</strong>&nbsp;Returns the object represented by the JSON string.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> str = &#39;true&#39; <strong>Output:</strong> true <strong>Explanation:</strong> Primitive types are valid JSON.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> str = &#39;[1,5,&quot;false&quot;,{&quot;a&quot;:2}]&#39; <strong>Output:</strong> [1,5,&quot;false&quot;,{&quot;a&quot;:2}] <strong>Explanation:</strong> Returns the array represented by the JSON string.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>str</code> is a valid JSON string</li> <li><code>1 &lt;= str.length &lt;= 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
function jsonParse(str: string): any { const n = str.length; let i = 0; const parseTrue = (): boolean => { i += 4; return true; }; const parseFalse = (): boolean => { i += 5; return false; }; const parseNull = (): null => { i += 4; return null; }; const parseNumber = (): number => { let s = ''; while (i < n) { const c = str[i]; if (c === ',' || c === '}' || c === ']') { break; } s += c; i++; } return Number(s); }; const parseArray = (): any[] => { const arr: any[] = []; i++; while (i < n) { const c = str[i]; if (c === ']') { i++; break; } if (c === ',') { i++; continue; } const value = parseValue(); arr.push(value); } return arr; }; const parseString = (): string => { let s = ''; i++; while (i < n) { const c = str[i]; if (c === '"') { i++; break; } if (c === '\\') { i++; s += str[i]; } else { s += c; } i++; } return s; }; const parseObject = (): any => { const obj: any = {}; i++; while (i < n) { const c = str[i]; if (c === '}') { i++; break; } if (c === ',') { i++; continue; } const key = parseString(); i++; const value = parseValue(); obj[key] = value; } return obj; }; const parseValue = (): any => { const c = str[i]; if (c === '{') { return parseObject(); } if (c === '[') { return parseArray(); } if (c === '"') { return parseString(); } if (c === 't') { return parseTrue(); } if (c === 'f') { return parseFalse(); } if (c === 'n') { return parseNull(); } return parseNumber(); }; return parseValue(); }
2,760
Longest Even Odd Subarray With Threshold
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>threshold</code>.</p> <p>Find the length of the <strong>longest subarray</strong> of <code>nums</code> starting at index <code>l</code> and ending at index <code>r</code> <code>(0 &lt;= l &lt;= r &lt; nums.length)</code> that satisfies the following conditions:</p> <ul> <li><code>nums[l] % 2 == 0</code></li> <li>For all indices <code>i</code> in the range <code>[l, r - 1]</code>, <code>nums[i] % 2 != nums[i + 1] % 2</code></li> <li>For all indices <code>i</code> in the range <code>[l, r]</code>, <code>nums[i] &lt;= threshold</code></li> </ul> <p>Return <em>an integer denoting the length of the longest such subarray.</em></p> <p><strong>Note:</strong> A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,4], threshold = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 3 =&gt; [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2], threshold = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 1 =&gt; [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4,5], threshold = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 0 and ends at r = 2 =&gt; [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100 </code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array; Sliding Window
C++
class Solution { public: int longestAlternatingSubarray(vector<int>& nums, int threshold) { int ans = 0, n = nums.size(); for (int l = 0; l < n; ++l) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } ans = max(ans, r - l); } } return ans; } };
2,760
Longest Even Odd Subarray With Threshold
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>threshold</code>.</p> <p>Find the length of the <strong>longest subarray</strong> of <code>nums</code> starting at index <code>l</code> and ending at index <code>r</code> <code>(0 &lt;= l &lt;= r &lt; nums.length)</code> that satisfies the following conditions:</p> <ul> <li><code>nums[l] % 2 == 0</code></li> <li>For all indices <code>i</code> in the range <code>[l, r - 1]</code>, <code>nums[i] % 2 != nums[i + 1] % 2</code></li> <li>For all indices <code>i</code> in the range <code>[l, r]</code>, <code>nums[i] &lt;= threshold</code></li> </ul> <p>Return <em>an integer denoting the length of the longest such subarray.</em></p> <p><strong>Note:</strong> A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,4], threshold = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 3 =&gt; [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2], threshold = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 1 =&gt; [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4,5], threshold = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 0 and ends at r = 2 =&gt; [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100 </code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array; Sliding Window
Go
func longestAlternatingSubarray(nums []int, threshold int) (ans int) { n := len(nums) for l := range nums { if nums[l]%2 == 0 && nums[l] <= threshold { r := l + 1 for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { r++ } ans = max(ans, r-l) } } return }
2,760
Longest Even Odd Subarray With Threshold
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>threshold</code>.</p> <p>Find the length of the <strong>longest subarray</strong> of <code>nums</code> starting at index <code>l</code> and ending at index <code>r</code> <code>(0 &lt;= l &lt;= r &lt; nums.length)</code> that satisfies the following conditions:</p> <ul> <li><code>nums[l] % 2 == 0</code></li> <li>For all indices <code>i</code> in the range <code>[l, r - 1]</code>, <code>nums[i] % 2 != nums[i + 1] % 2</code></li> <li>For all indices <code>i</code> in the range <code>[l, r]</code>, <code>nums[i] &lt;= threshold</code></li> </ul> <p>Return <em>an integer denoting the length of the longest such subarray.</em></p> <p><strong>Note:</strong> A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,4], threshold = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 3 =&gt; [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2], threshold = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 1 =&gt; [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4,5], threshold = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 0 and ends at r = 2 =&gt; [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100 </code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array; Sliding Window
Java
class Solution { public int longestAlternatingSubarray(int[] nums, int threshold) { int ans = 0, n = nums.length; for (int l = 0; l < n; ++l) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } ans = Math.max(ans, r - l); } } return ans; } }
2,760
Longest Even Odd Subarray With Threshold
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>threshold</code>.</p> <p>Find the length of the <strong>longest subarray</strong> of <code>nums</code> starting at index <code>l</code> and ending at index <code>r</code> <code>(0 &lt;= l &lt;= r &lt; nums.length)</code> that satisfies the following conditions:</p> <ul> <li><code>nums[l] % 2 == 0</code></li> <li>For all indices <code>i</code> in the range <code>[l, r - 1]</code>, <code>nums[i] % 2 != nums[i + 1] % 2</code></li> <li>For all indices <code>i</code> in the range <code>[l, r]</code>, <code>nums[i] &lt;= threshold</code></li> </ul> <p>Return <em>an integer denoting the length of the longest such subarray.</em></p> <p><strong>Note:</strong> A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,4], threshold = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 3 =&gt; [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2], threshold = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 1 =&gt; [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4,5], threshold = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 0 and ends at r = 2 =&gt; [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100 </code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array; Sliding Window
Python
class Solution: def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: ans, n = 0, len(nums) for l in range(n): if nums[l] % 2 == 0 and nums[l] <= threshold: r = l + 1 while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: r += 1 ans = max(ans, r - l) return ans
2,760
Longest Even Odd Subarray With Threshold
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>threshold</code>.</p> <p>Find the length of the <strong>longest subarray</strong> of <code>nums</code> starting at index <code>l</code> and ending at index <code>r</code> <code>(0 &lt;= l &lt;= r &lt; nums.length)</code> that satisfies the following conditions:</p> <ul> <li><code>nums[l] % 2 == 0</code></li> <li>For all indices <code>i</code> in the range <code>[l, r - 1]</code>, <code>nums[i] % 2 != nums[i + 1] % 2</code></li> <li>For all indices <code>i</code> in the range <code>[l, r]</code>, <code>nums[i] &lt;= threshold</code></li> </ul> <p>Return <em>an integer denoting the length of the longest such subarray.</em></p> <p><strong>Note:</strong> A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,4], threshold = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 3 =&gt; [2,5,4]. This subarray satisfies the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2], threshold = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 1 and ends at r = 1 =&gt; [2]. It satisfies all the conditions and we can show that 1 is the maximum possible achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4,5], threshold = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we can select the subarray that starts at l = 0 and ends at r = 2 =&gt; [2,3,4]. It satisfies all the conditions. Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100 </code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array; Sliding Window
TypeScript
function longestAlternatingSubarray(nums: number[], threshold: number): number { const n = nums.length; let ans = 0; for (let l = 0; l < n; ++l) { if (nums[l] % 2 === 0 && nums[l] <= threshold) { let r = l + 1; while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } ans = Math.max(ans, r - l); } } return ans; }
2,761
Prime Pairs With Target Sum
Medium
<p>You are given an integer <code>n</code>. We say that two integers <code>x</code> and <code>y</code> form a prime number pair if:</p> <ul> <li><code>1 &lt;= x &lt;= y &lt;= n</code></li> <li><code>x + y == n</code></li> <li><code>x</code> and <code>y</code> are prime numbers</li> </ul> <p>Return <em>the 2D sorted list of prime number pairs</em> <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The list should be sorted in <strong>increasing</strong> order of <code>x<sub>i</sub></code>. If there are no prime number pairs at all, return <em>an empty array</em>.</p> <p><strong>Note:</strong> A prime number is a natural number greater than <code>1</code> with only two factors, itself and <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> [[3,7],[5,5]] <strong>Explanation:</strong> In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
C++
class Solution { public: vector<vector<int>> findPrimePairs(int n) { bool primes[n]; memset(primes, true, sizeof(primes)); for (int i = 2; i < n; ++i) { if (primes[i]) { for (int j = i + i; j < n; j += i) { primes[j] = false; } } } vector<vector<int>> ans; for (int x = 2; x <= n / 2; ++x) { int y = n - x; if (primes[x] && primes[y]) { ans.push_back({x, y}); } } return ans; } };
2,761
Prime Pairs With Target Sum
Medium
<p>You are given an integer <code>n</code>. We say that two integers <code>x</code> and <code>y</code> form a prime number pair if:</p> <ul> <li><code>1 &lt;= x &lt;= y &lt;= n</code></li> <li><code>x + y == n</code></li> <li><code>x</code> and <code>y</code> are prime numbers</li> </ul> <p>Return <em>the 2D sorted list of prime number pairs</em> <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The list should be sorted in <strong>increasing</strong> order of <code>x<sub>i</sub></code>. If there are no prime number pairs at all, return <em>an empty array</em>.</p> <p><strong>Note:</strong> A prime number is a natural number greater than <code>1</code> with only two factors, itself and <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> [[3,7],[5,5]] <strong>Explanation:</strong> In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Go
func findPrimePairs(n int) (ans [][]int) { primes := make([]bool, n) for i := range primes { primes[i] = true } for i := 2; i < n; i++ { if primes[i] { for j := i + i; j < n; j += i { primes[j] = false } } } for x := 2; x <= n/2; x++ { y := n - x if primes[x] && primes[y] { ans = append(ans, []int{x, y}) } } return }
2,761
Prime Pairs With Target Sum
Medium
<p>You are given an integer <code>n</code>. We say that two integers <code>x</code> and <code>y</code> form a prime number pair if:</p> <ul> <li><code>1 &lt;= x &lt;= y &lt;= n</code></li> <li><code>x + y == n</code></li> <li><code>x</code> and <code>y</code> are prime numbers</li> </ul> <p>Return <em>the 2D sorted list of prime number pairs</em> <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The list should be sorted in <strong>increasing</strong> order of <code>x<sub>i</sub></code>. If there are no prime number pairs at all, return <em>an empty array</em>.</p> <p><strong>Note:</strong> A prime number is a natural number greater than <code>1</code> with only two factors, itself and <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> [[3,7],[5,5]] <strong>Explanation:</strong> In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Java
class Solution { public List<List<Integer>> findPrimePairs(int n) { boolean[] primes = new boolean[n]; Arrays.fill(primes, true); for (int i = 2; i < n; ++i) { if (primes[i]) { for (int j = i + i; j < n; j += i) { primes[j] = false; } } } List<List<Integer>> ans = new ArrayList<>(); for (int x = 2; x <= n / 2; ++x) { int y = n - x; if (primes[x] && primes[y]) { ans.add(List.of(x, y)); } } return ans; } }
2,761
Prime Pairs With Target Sum
Medium
<p>You are given an integer <code>n</code>. We say that two integers <code>x</code> and <code>y</code> form a prime number pair if:</p> <ul> <li><code>1 &lt;= x &lt;= y &lt;= n</code></li> <li><code>x + y == n</code></li> <li><code>x</code> and <code>y</code> are prime numbers</li> </ul> <p>Return <em>the 2D sorted list of prime number pairs</em> <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The list should be sorted in <strong>increasing</strong> order of <code>x<sub>i</sub></code>. If there are no prime number pairs at all, return <em>an empty array</em>.</p> <p><strong>Note:</strong> A prime number is a natural number greater than <code>1</code> with only two factors, itself and <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> [[3,7],[5,5]] <strong>Explanation:</strong> In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
Python
class Solution: def findPrimePairs(self, n: int) -> List[List[int]]: primes = [True] * n for i in range(2, n): if primes[i]: for j in range(i + i, n, i): primes[j] = False ans = [] for x in range(2, n // 2 + 1): y = n - x if primes[x] and primes[y]: ans.append([x, y]) return ans
2,761
Prime Pairs With Target Sum
Medium
<p>You are given an integer <code>n</code>. We say that two integers <code>x</code> and <code>y</code> form a prime number pair if:</p> <ul> <li><code>1 &lt;= x &lt;= y &lt;= n</code></li> <li><code>x + y == n</code></li> <li><code>x</code> and <code>y</code> are prime numbers</li> </ul> <p>Return <em>the 2D sorted list of prime number pairs</em> <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The list should be sorted in <strong>increasing</strong> order of <code>x<sub>i</sub></code>. If there are no prime number pairs at all, return <em>an empty array</em>.</p> <p><strong>Note:</strong> A prime number is a natural number greater than <code>1</code> with only two factors, itself and <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> [[3,7],[5,5]] <strong>Explanation:</strong> In this example, there are two prime pairs that satisfy the criteria. These pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Enumeration; Number Theory
TypeScript
function findPrimePairs(n: number): number[][] { const primes: boolean[] = new Array(n).fill(true); for (let i = 2; i < n; ++i) { if (primes[i]) { for (let j = i + i; j < n; j += i) { primes[j] = false; } } } const ans: number[][] = []; for (let x = 2; x <= n / 2; ++x) { const y = n - x; if (primes[x] && primes[y]) { ans.push([x, y]); } } return ans; }
2,762
Continuous Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray of <code>nums</code> is called <strong>continuous</strong> if:</p> <ul> <li>Let <code>i</code>, <code>i + 1</code>, ..., <code>j</code><sub> </sub>be the indices in the subarray. Then, for each pair of indices <code>i &lt;= i<sub>1</sub>, i<sub>2</sub> &lt;= j</code>, <code><font face="monospace">0 &lt;=</font> |nums[i<sub>1</sub>] - nums[i<sub>2</sub>]| &lt;= 2</code>.</li> </ul> <p>Return <em>the total number of <strong>continuous</strong> subarrays.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. There are no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays. </pre> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Ordered Set; Sliding Window; Monotonic Queue; Heap (Priority Queue)
C++
class Solution { public: long long continuousSubarrays(vector<int>& nums) { long long ans = 0; int i = 0, n = nums.size(); multiset<int> s; for (int j = 0; j < n; ++j) { s.insert(nums[j]); while (*s.rbegin() - *s.begin() > 2) { s.erase(s.find(nums[i++])); } ans += j - i + 1; } return ans; } };
2,762
Continuous Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray of <code>nums</code> is called <strong>continuous</strong> if:</p> <ul> <li>Let <code>i</code>, <code>i + 1</code>, ..., <code>j</code><sub> </sub>be the indices in the subarray. Then, for each pair of indices <code>i &lt;= i<sub>1</sub>, i<sub>2</sub> &lt;= j</code>, <code><font face="monospace">0 &lt;=</font> |nums[i<sub>1</sub>] - nums[i<sub>2</sub>]| &lt;= 2</code>.</li> </ul> <p>Return <em>the total number of <strong>continuous</strong> subarrays.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. There are no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays. </pre> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Ordered Set; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Go
func continuousSubarrays(nums []int) (ans int64) { i := 0 tm := treemap.NewWithIntComparator() for j, x := range nums { if v, ok := tm.Get(x); ok { tm.Put(x, v.(int)+1) } else { tm.Put(x, 1) } for { a, _ := tm.Min() b, _ := tm.Max() if b.(int)-a.(int) > 2 { if v, _ := tm.Get(nums[i]); v.(int) == 1 { tm.Remove(nums[i]) } else { tm.Put(nums[i], v.(int)-1) } i++ } else { break } } ans += int64(j - i + 1) } return }
2,762
Continuous Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray of <code>nums</code> is called <strong>continuous</strong> if:</p> <ul> <li>Let <code>i</code>, <code>i + 1</code>, ..., <code>j</code><sub> </sub>be the indices in the subarray. Then, for each pair of indices <code>i &lt;= i<sub>1</sub>, i<sub>2</sub> &lt;= j</code>, <code><font face="monospace">0 &lt;=</font> |nums[i<sub>1</sub>] - nums[i<sub>2</sub>]| &lt;= 2</code>.</li> </ul> <p>Return <em>the total number of <strong>continuous</strong> subarrays.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. There are no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays. </pre> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Ordered Set; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Java
class Solution { public long continuousSubarrays(int[] nums) { long ans = 0; int i = 0, n = nums.length; TreeMap<Integer, Integer> tm = new TreeMap<>(); for (int j = 0; j < n; ++j) { tm.merge(nums[j], 1, Integer::sum); while (tm.lastEntry().getKey() - tm.firstEntry().getKey() > 2) { tm.merge(nums[i], -1, Integer::sum); if (tm.get(nums[i]) == 0) { tm.remove(nums[i]); } ++i; } ans += j - i + 1; } return ans; } }
2,762
Continuous Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray of <code>nums</code> is called <strong>continuous</strong> if:</p> <ul> <li>Let <code>i</code>, <code>i + 1</code>, ..., <code>j</code><sub> </sub>be the indices in the subarray. Then, for each pair of indices <code>i &lt;= i<sub>1</sub>, i<sub>2</sub> &lt;= j</code>, <code><font face="monospace">0 &lt;=</font> |nums[i<sub>1</sub>] - nums[i<sub>2</sub>]| &lt;= 2</code>.</li> </ul> <p>Return <em>the total number of <strong>continuous</strong> subarrays.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> Continuous subarray of size 1: [5], [4], [2], [4]. Continuous subarray of size 2: [5,4], [4,2], [2,4]. Continuous subarray of size 3: [4,2,4]. There are no subarrys of size 4. Total continuous subarrays = 4 + 3 + 1 = 8. It can be shown that there are no more continuous subarrays. </pre> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 6 <strong>Explanation:</strong> Continuous subarray of size 1: [1], [2], [3]. Continuous subarray of size 2: [1,2], [2,3]. Continuous subarray of size 3: [1,2,3]. Total continuous subarrays = 3 + 2 + 1 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Ordered Set; Sliding Window; Monotonic Queue; Heap (Priority Queue)
Python
class Solution: def continuousSubarrays(self, nums: List[int]) -> int: ans = i = 0 sl = SortedList() for x in nums: sl.add(x) while sl[-1] - sl[0] > 2: sl.remove(nums[i]) i += 1 ans += len(sl) return ans
2,763
Sum of Imbalance Numbers of All Subarrays
Hard
<p>The <strong>imbalance number</strong> of a <strong>0-indexed</strong> integer array <code>arr</code> of length <code>n</code> is defined as the number of indices in <code>sarr = sorted(arr)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code>, and</li> <li><code>sarr[i+1] - sarr[i] &gt; 1</code></li> </ul> <p>Here, <code>sorted(arr)</code> is the function that returns the sorted version of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, return <em>the <strong>sum of imbalance numbers</strong> of all its <strong>subarrays</strong></em>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 subarrays with non-zero<strong> </strong>imbalance numbers: - Subarray [3, 1] with an imbalance number of 1. - Subarray [3, 1, 4] with an imbalance number of 1. - Subarray [1, 4] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,3,3,5] <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 7 subarrays with non-zero imbalance numbers: - Subarray [1, 3] with an imbalance number of 1. - Subarray [1, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. - Subarray [3, 3, 3, 5] with an imbalance number of 1. - Subarray [3, 3, 5] with an imbalance number of 1. - Subarray [3, 5] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table; Ordered Set
C++
class Solution { public: int sumImbalanceNumbers(vector<int>& nums) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { multiset<int> s; int cnt = 0; for (int j = i; j < n; ++j) { auto it = s.lower_bound(nums[j]); if (it != s.end() && *it - nums[j] > 1) { ++cnt; } if (it != s.begin() && nums[j] - *prev(it) > 1) { ++cnt; } if (it != s.end() && it != s.begin() && *it - *prev(it) > 1) { --cnt; } s.insert(nums[j]); ans += cnt; } } return ans; } };
2,763
Sum of Imbalance Numbers of All Subarrays
Hard
<p>The <strong>imbalance number</strong> of a <strong>0-indexed</strong> integer array <code>arr</code> of length <code>n</code> is defined as the number of indices in <code>sarr = sorted(arr)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code>, and</li> <li><code>sarr[i+1] - sarr[i] &gt; 1</code></li> </ul> <p>Here, <code>sorted(arr)</code> is the function that returns the sorted version of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, return <em>the <strong>sum of imbalance numbers</strong> of all its <strong>subarrays</strong></em>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 subarrays with non-zero<strong> </strong>imbalance numbers: - Subarray [3, 1] with an imbalance number of 1. - Subarray [3, 1, 4] with an imbalance number of 1. - Subarray [1, 4] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,3,3,5] <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 7 subarrays with non-zero imbalance numbers: - Subarray [1, 3] with an imbalance number of 1. - Subarray [1, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. - Subarray [3, 3, 3, 5] with an imbalance number of 1. - Subarray [3, 3, 5] with an imbalance number of 1. - Subarray [3, 5] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table; Ordered Set
Java
class Solution { public int sumImbalanceNumbers(int[] nums) { int n = nums.length; int ans = 0; for (int i = 0; i < n; ++i) { TreeMap<Integer, Integer> tm = new TreeMap<>(); int cnt = 0; for (int j = i; j < n; ++j) { Integer k = tm.ceilingKey(nums[j]); if (k != null && k - nums[j] > 1) { ++cnt; } Integer h = tm.floorKey(nums[j]); if (h != null && nums[j] - h > 1) { ++cnt; } if (h != null && k != null && k - h > 1) { --cnt; } tm.merge(nums[j], 1, Integer::sum); ans += cnt; } } return ans; } }
2,763
Sum of Imbalance Numbers of All Subarrays
Hard
<p>The <strong>imbalance number</strong> of a <strong>0-indexed</strong> integer array <code>arr</code> of length <code>n</code> is defined as the number of indices in <code>sarr = sorted(arr)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code>, and</li> <li><code>sarr[i+1] - sarr[i] &gt; 1</code></li> </ul> <p>Here, <code>sorted(arr)</code> is the function that returns the sorted version of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, return <em>the <strong>sum of imbalance numbers</strong> of all its <strong>subarrays</strong></em>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,1,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 subarrays with non-zero<strong> </strong>imbalance numbers: - Subarray [3, 1] with an imbalance number of 1. - Subarray [3, 1, 4] with an imbalance number of 1. - Subarray [1, 4] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,3,3,5] <strong>Output:</strong> 8 <strong>Explanation:</strong> There are 7 subarrays with non-zero imbalance numbers: - Subarray [1, 3] with an imbalance number of 1. - Subarray [1, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3] with an imbalance number of 1. - Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. - Subarray [3, 3, 3, 5] with an imbalance number of 1. - Subarray [3, 3, 5] with an imbalance number of 1. - Subarray [3, 5] with an imbalance number of 1. The imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table; Ordered Set
Python
class Solution: def sumImbalanceNumbers(self, nums: List[int]) -> int: n = len(nums) ans = 0 for i in range(n): sl = SortedList() cnt = 0 for j in range(i, n): k = sl.bisect_left(nums[j]) h = k - 1 if h >= 0 and nums[j] - sl[h] > 1: cnt += 1 if k < len(sl) and sl[k] - nums[j] > 1: cnt += 1 if h >= 0 and k < len(sl) and sl[k] - sl[h] > 1: cnt -= 1 sl.add(nums[j]) ans += cnt return ans
2,764
Is Array a Preorder of Some ‌Binary Tree
Medium
<p>Given a <strong>0-indexed</strong> integer <strong>2D array</strong> <code>nodes</code>, your task is to determine if the given array represents the <strong>preorder</strong> traversal of some <strong>binary</strong> tree.</p> <p>For each index <code>i</code>, <code>nodes[i] = [id, parentId]</code>, where <code>id</code> is the id of the node at the index <code>i</code> and <code>parentId</code> is the id of its parent in the tree (if the node has no parent, then <code>parentId == -1</code>).</p> <p>Return <code>true</code> <em>if the given array </em><em>represents the preorder traversal of some tree, and</em> <code>false</code> <em>otherwise.</em></p> <p><strong>Note:</strong> the <strong>preorder</strong> traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] <strong>Output:</strong> true <strong>Explanation:</strong> The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4]. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/1.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] <strong>Output:</strong> false <strong>Explanation:</strong> The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it&#39;s not the preorder traversal of the tree. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/2.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nodes.length &lt;= 10<sup>5</sup></code></li> <li><code>nodes[i].length == 2</code></li> <li><code>0 &lt;= nodes[i][0] &lt;= 10<sup>5</sup></code></li> <li><code>-1 &lt;= nodes[i][1] &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that <code>nodes</code> make a binary tree.</li> </ul>
Stack; Tree; Depth-First Search; Binary Tree
C++
class Solution { public: bool isPreorder(vector<vector<int>>& nodes) { int k = 0; unordered_map<int, vector<int>> g; for (auto& node : nodes) { g[node[1]].push_back(node[0]); } function<bool(int)> dfs = [&](int i) { if (i != nodes[k][0]) { return false; } ++k; for (int j : g[i]) { if (!dfs(j)) { return false; } } return true; }; return dfs(nodes[0][0]) && k == nodes.size(); } };
2,764
Is Array a Preorder of Some ‌Binary Tree
Medium
<p>Given a <strong>0-indexed</strong> integer <strong>2D array</strong> <code>nodes</code>, your task is to determine if the given array represents the <strong>preorder</strong> traversal of some <strong>binary</strong> tree.</p> <p>For each index <code>i</code>, <code>nodes[i] = [id, parentId]</code>, where <code>id</code> is the id of the node at the index <code>i</code> and <code>parentId</code> is the id of its parent in the tree (if the node has no parent, then <code>parentId == -1</code>).</p> <p>Return <code>true</code> <em>if the given array </em><em>represents the preorder traversal of some tree, and</em> <code>false</code> <em>otherwise.</em></p> <p><strong>Note:</strong> the <strong>preorder</strong> traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] <strong>Output:</strong> true <strong>Explanation:</strong> The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4]. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/1.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] <strong>Output:</strong> false <strong>Explanation:</strong> The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it&#39;s not the preorder traversal of the tree. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/2.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nodes.length &lt;= 10<sup>5</sup></code></li> <li><code>nodes[i].length == 2</code></li> <li><code>0 &lt;= nodes[i][0] &lt;= 10<sup>5</sup></code></li> <li><code>-1 &lt;= nodes[i][1] &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that <code>nodes</code> make a binary tree.</li> </ul>
Stack; Tree; Depth-First Search; Binary Tree
Go
func isPreorder(nodes [][]int) bool { k := 0 g := map[int][]int{} for _, node := range nodes { g[node[1]] = append(g[node[1]], node[0]) } var dfs func(int) bool dfs = func(i int) bool { if i != nodes[k][0] { return false } k++ for _, j := range g[i] { if !dfs(j) { return false } } return true } return dfs(nodes[0][0]) && k == len(nodes) }
2,764
Is Array a Preorder of Some ‌Binary Tree
Medium
<p>Given a <strong>0-indexed</strong> integer <strong>2D array</strong> <code>nodes</code>, your task is to determine if the given array represents the <strong>preorder</strong> traversal of some <strong>binary</strong> tree.</p> <p>For each index <code>i</code>, <code>nodes[i] = [id, parentId]</code>, where <code>id</code> is the id of the node at the index <code>i</code> and <code>parentId</code> is the id of its parent in the tree (if the node has no parent, then <code>parentId == -1</code>).</p> <p>Return <code>true</code> <em>if the given array </em><em>represents the preorder traversal of some tree, and</em> <code>false</code> <em>otherwise.</em></p> <p><strong>Note:</strong> the <strong>preorder</strong> traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] <strong>Output:</strong> true <strong>Explanation:</strong> The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4]. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/1.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] <strong>Output:</strong> false <strong>Explanation:</strong> The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it&#39;s not the preorder traversal of the tree. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/2.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nodes.length &lt;= 10<sup>5</sup></code></li> <li><code>nodes[i].length == 2</code></li> <li><code>0 &lt;= nodes[i][0] &lt;= 10<sup>5</sup></code></li> <li><code>-1 &lt;= nodes[i][1] &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that <code>nodes</code> make a binary tree.</li> </ul>
Stack; Tree; Depth-First Search; Binary Tree
Java
class Solution { private Map<Integer, List<Integer>> g = new HashMap<>(); private List<List<Integer>> nodes; private int k; public boolean isPreorder(List<List<Integer>> nodes) { this.nodes = nodes; for (var node : nodes) { g.computeIfAbsent(node.get(1), key -> new ArrayList<>()).add(node.get(0)); } return dfs(nodes.get(0).get(0)) && k == nodes.size(); } private boolean dfs(int i) { if (i != nodes.get(k).get(0)) { return false; } ++k; for (int j : g.getOrDefault(i, List.of())) { if (!dfs(j)) { return false; } } return true; } }
2,764
Is Array a Preorder of Some ‌Binary Tree
Medium
<p>Given a <strong>0-indexed</strong> integer <strong>2D array</strong> <code>nodes</code>, your task is to determine if the given array represents the <strong>preorder</strong> traversal of some <strong>binary</strong> tree.</p> <p>For each index <code>i</code>, <code>nodes[i] = [id, parentId]</code>, where <code>id</code> is the id of the node at the index <code>i</code> and <code>parentId</code> is the id of its parent in the tree (if the node has no parent, then <code>parentId == -1</code>).</p> <p>Return <code>true</code> <em>if the given array </em><em>represents the preorder traversal of some tree, and</em> <code>false</code> <em>otherwise.</em></p> <p><strong>Note:</strong> the <strong>preorder</strong> traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] <strong>Output:</strong> true <strong>Explanation:</strong> The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4]. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/1.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] <strong>Output:</strong> false <strong>Explanation:</strong> The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it&#39;s not the preorder traversal of the tree. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/2.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nodes.length &lt;= 10<sup>5</sup></code></li> <li><code>nodes[i].length == 2</code></li> <li><code>0 &lt;= nodes[i][0] &lt;= 10<sup>5</sup></code></li> <li><code>-1 &lt;= nodes[i][1] &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that <code>nodes</code> make a binary tree.</li> </ul>
Stack; Tree; Depth-First Search; Binary Tree
Python
class Solution: def isPreorder(self, nodes: List[List[int]]) -> bool: def dfs(i: int) -> int: nonlocal k if i != nodes[k][0]: return False k += 1 return all(dfs(j) for j in g[i]) g = defaultdict(list) for i, p in nodes: g[p].append(i) k = 0 return dfs(nodes[0][0]) and k == len(nodes)
2,764
Is Array a Preorder of Some ‌Binary Tree
Medium
<p>Given a <strong>0-indexed</strong> integer <strong>2D array</strong> <code>nodes</code>, your task is to determine if the given array represents the <strong>preorder</strong> traversal of some <strong>binary</strong> tree.</p> <p>For each index <code>i</code>, <code>nodes[i] = [id, parentId]</code>, where <code>id</code> is the id of the node at the index <code>i</code> and <code>parentId</code> is the id of its parent in the tree (if the node has no parent, then <code>parentId == -1</code>).</p> <p>Return <code>true</code> <em>if the given array </em><em>represents the preorder traversal of some tree, and</em> <code>false</code> <em>otherwise.</em></p> <p><strong>Note:</strong> the <strong>preorder</strong> traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] <strong>Output:</strong> true <strong>Explanation:</strong> The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4]. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/1.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] <strong>Output:</strong> false <strong>Explanation:</strong> The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it&#39;s not the preorder traversal of the tree. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2764.Is%20Array%20a%20Preorder%20of%20Some%20%E2%80%8CBinary%20Tree/images/2.png" style="padding: 10px; background: #fff; border-radius: .5rem; width: 250px; height: 251px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nodes.length &lt;= 10<sup>5</sup></code></li> <li><code>nodes[i].length == 2</code></li> <li><code>0 &lt;= nodes[i][0] &lt;= 10<sup>5</sup></code></li> <li><code>-1 &lt;= nodes[i][1] &lt;= 10<sup>5</sup></code></li> <li>The input is generated such that <code>nodes</code> make a binary tree.</li> </ul>
Stack; Tree; Depth-First Search; Binary Tree
TypeScript
function isPreorder(nodes: number[][]): boolean { let k = 0; const g: Map<number, number[]> = new Map(); for (const [i, p] of nodes) { if (!g.has(p)) { g.set(p, []); } g.get(p)!.push(i); } const dfs = (i: number): boolean => { if (i !== nodes[k][0]) { return false; } ++k; for (const j of g.get(i) ?? []) { if (!dfs(j)) { return false; } } return true; }; return dfs(nodes[0][0]) && k === nodes.length; }
2,765
Longest Alternating Subarray
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p> <ul> <li><code>m</code> is greater than <code>1</code>.</li> <li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li> <li>The <strong>0-indexed</strong> subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li> </ul> <p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The alternating subarrays are <code>[2, 3]</code>, <code>[3,4]</code>, <code>[3,4,3]</code>, and <code>[3,4,3,4]</code>. The longest of these is <code>[3,4,3,4]</code>, which is of length 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>[4,5]</code> and <code>[5,6]</code> are the only two alternating subarrays. They are both of length 2.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Enumeration
C++
class Solution { public: int alternatingSubarray(vector<int>& nums) { int ans = -1, n = nums.size(); for (int i = 0; i < n; ++i) { int k = 1; int j = i; for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) { k *= -1; } if (j - i + 1 > 1) { ans = max(ans, j - i + 1); } } return ans; } };
2,765
Longest Alternating Subarray
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p> <ul> <li><code>m</code> is greater than <code>1</code>.</li> <li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li> <li>The <strong>0-indexed</strong> subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li> </ul> <p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The alternating subarrays are <code>[2, 3]</code>, <code>[3,4]</code>, <code>[3,4,3]</code>, and <code>[3,4,3,4]</code>. The longest of these is <code>[3,4,3,4]</code>, which is of length 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>[4,5]</code> and <code>[5,6]</code> are the only two alternating subarrays. They are both of length 2.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Enumeration
Go
func alternatingSubarray(nums []int) int { ans, n := -1, len(nums) for i := range nums { k := 1 j := i for ; j+1 < n && nums[j+1]-nums[j] == k; j++ { k *= -1 } if t := j - i + 1; t > 1 && ans < t { ans = t } } return ans }
2,765
Longest Alternating Subarray
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p> <ul> <li><code>m</code> is greater than <code>1</code>.</li> <li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li> <li>The <strong>0-indexed</strong> subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li> </ul> <p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The alternating subarrays are <code>[2, 3]</code>, <code>[3,4]</code>, <code>[3,4,3]</code>, and <code>[3,4,3,4]</code>. The longest of these is <code>[3,4,3,4]</code>, which is of length 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>[4,5]</code> and <code>[5,6]</code> are the only two alternating subarrays. They are both of length 2.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Enumeration
Java
class Solution { public int alternatingSubarray(int[] nums) { int ans = -1, n = nums.length; for (int i = 0; i < n; ++i) { int k = 1; int j = i; for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) { k *= -1; } if (j - i + 1 > 1) { ans = Math.max(ans, j - i + 1); } } return ans; } }
2,765
Longest Alternating Subarray
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p> <ul> <li><code>m</code> is greater than <code>1</code>.</li> <li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li> <li>The <strong>0-indexed</strong> subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li> </ul> <p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The alternating subarrays are <code>[2, 3]</code>, <code>[3,4]</code>, <code>[3,4,3]</code>, and <code>[3,4,3,4]</code>. The longest of these is <code>[3,4,3,4]</code>, which is of length 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>[4,5]</code> and <code>[5,6]</code> are the only two alternating subarrays. They are both of length 2.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Enumeration
Python
class Solution: def alternatingSubarray(self, nums: List[int]) -> int: ans, n = -1, len(nums) for i in range(n): k = 1 j = i while j + 1 < n and nums[j + 1] - nums[j] == k: j += 1 k *= -1 if j - i + 1 > 1: ans = max(ans, j - i + 1) return ans
2,765
Longest Alternating Subarray
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray <code>s</code> of length <code>m</code> is called <strong>alternating</strong> if:</p> <ul> <li><code>m</code> is greater than <code>1</code>.</li> <li><code>s<sub>1</sub> = s<sub>0</sub> + 1</code>.</li> <li>The <strong>0-indexed</strong> subarray <code>s</code> looks like <code>[s<sub>0</sub>, s<sub>1</sub>, s<sub>0</sub>, s<sub>1</sub>,...,s<sub>(m-1) % 2</sub>]</code>. In other words, <code>s<sub>1</sub> - s<sub>0</sub> = 1</code>, <code>s<sub>2</sub> - s<sub>1</sub> = -1</code>, <code>s<sub>3</sub> - s<sub>2</sub> = 1</code>, <code>s<sub>4</sub> - s<sub>3</sub> = -1</code>, and so on up to <code>s[m - 1] - s[m - 2] = (-1)<sup>m</sup></code>.</li> </ul> <p>Return <em>the maximum length of all <strong>alternating</strong> subarrays present in </em><code>nums</code> <em>or </em><code>-1</code><em> if no such subarray exists</em><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The alternating subarrays are <code>[2, 3]</code>, <code>[3,4]</code>, <code>[3,4,3]</code>, and <code>[3,4,3,4]</code>. The longest of these is <code>[3,4,3,4]</code>, which is of length 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>[4,5]</code> and <code>[5,6]</code> are the only two alternating subarrays. They are both of length 2.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Array; Enumeration
TypeScript
function alternatingSubarray(nums: number[]): number { let ans = -1; const n = nums.length; for (let i = 0; i < n; ++i) { let k = 1; let j = i; for (; j + 1 < n && nums[j + 1] - nums[j] === k; ++j) { k *= -1; } if (j - i + 1 > 1) { ans = Math.max(ans, j - i + 1); } } return ans; }
2,766
Relocate Marbles
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the initial positions of some marbles. You are also given two <strong>0-indexed </strong>integer arrays <code>moveFrom</code> and <code>moveTo</code> of <strong>equal</strong> length.</p> <p>Throughout <code>moveFrom.length</code> steps, you will change the positions of the marbles. On the <code>i<sup>th</sup></code> step, you will move <strong>all</strong> marbles at position <code>moveFrom[i]</code> to position <code>moveTo[i]</code>.</p> <p>After completing all the steps, return <em>the sorted list of <strong>occupied</strong> positions</em>.</p> <p><strong>Notes:</strong></p> <ul> <li>We call a position <strong>occupied</strong> if there is at least one marble in that position.</li> <li>There may be multiple marbles in a single position.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] <strong>Output:</strong> [5,6,8,9] <strong>Explanation:</strong> Initially, the marbles are at positions 1,6,7,8. At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. At the end, the final positions containing at least one marbles are [5,6,8,9].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] <strong>Output:</strong> [2] <strong>Explanation:</strong> Initially, the marbles are at positions [1,1,3,3]. At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. Since 2 is the only occupied position, we return [2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= moveFrom.length &lt;= 10<sup>5</sup></code></li> <li><code>moveFrom.length == moveTo.length</code></li> <li><code>1 &lt;= nums[i], moveFrom[i], moveTo[i] &lt;= 10<sup>9</sup></code></li> <li>The test cases are generated such that there is at least a marble in&nbsp;<code>moveFrom[i]</code>&nbsp;at the moment we want to apply&nbsp;the <code>i<sup>th</sup></code>&nbsp;move.</li> </ul>
Array; Hash Table; Sorting; Simulation
C++
class Solution { public: vector<int> relocateMarbles(vector<int>& nums, vector<int>& moveFrom, vector<int>& moveTo) { unordered_set<int> pos(nums.begin(), nums.end()); for (int i = 0; i < moveFrom.size(); ++i) { pos.erase(moveFrom[i]); pos.insert(moveTo[i]); } vector<int> ans(pos.begin(), pos.end()); sort(ans.begin(), ans.end()); return ans; } };
2,766
Relocate Marbles
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the initial positions of some marbles. You are also given two <strong>0-indexed </strong>integer arrays <code>moveFrom</code> and <code>moveTo</code> of <strong>equal</strong> length.</p> <p>Throughout <code>moveFrom.length</code> steps, you will change the positions of the marbles. On the <code>i<sup>th</sup></code> step, you will move <strong>all</strong> marbles at position <code>moveFrom[i]</code> to position <code>moveTo[i]</code>.</p> <p>After completing all the steps, return <em>the sorted list of <strong>occupied</strong> positions</em>.</p> <p><strong>Notes:</strong></p> <ul> <li>We call a position <strong>occupied</strong> if there is at least one marble in that position.</li> <li>There may be multiple marbles in a single position.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] <strong>Output:</strong> [5,6,8,9] <strong>Explanation:</strong> Initially, the marbles are at positions 1,6,7,8. At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. At the end, the final positions containing at least one marbles are [5,6,8,9].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] <strong>Output:</strong> [2] <strong>Explanation:</strong> Initially, the marbles are at positions [1,1,3,3]. At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. Since 2 is the only occupied position, we return [2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= moveFrom.length &lt;= 10<sup>5</sup></code></li> <li><code>moveFrom.length == moveTo.length</code></li> <li><code>1 &lt;= nums[i], moveFrom[i], moveTo[i] &lt;= 10<sup>9</sup></code></li> <li>The test cases are generated such that there is at least a marble in&nbsp;<code>moveFrom[i]</code>&nbsp;at the moment we want to apply&nbsp;the <code>i<sup>th</sup></code>&nbsp;move.</li> </ul>
Array; Hash Table; Sorting; Simulation
Go
func relocateMarbles(nums []int, moveFrom []int, moveTo []int) (ans []int) { pos := map[int]bool{} for _, x := range nums { pos[x] = true } for i, f := range moveFrom { t := moveTo[i] pos[f] = false pos[t] = true } for x, ok := range pos { if ok { ans = append(ans, x) } } sort.Ints(ans) return }
2,766
Relocate Marbles
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the initial positions of some marbles. You are also given two <strong>0-indexed </strong>integer arrays <code>moveFrom</code> and <code>moveTo</code> of <strong>equal</strong> length.</p> <p>Throughout <code>moveFrom.length</code> steps, you will change the positions of the marbles. On the <code>i<sup>th</sup></code> step, you will move <strong>all</strong> marbles at position <code>moveFrom[i]</code> to position <code>moveTo[i]</code>.</p> <p>After completing all the steps, return <em>the sorted list of <strong>occupied</strong> positions</em>.</p> <p><strong>Notes:</strong></p> <ul> <li>We call a position <strong>occupied</strong> if there is at least one marble in that position.</li> <li>There may be multiple marbles in a single position.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] <strong>Output:</strong> [5,6,8,9] <strong>Explanation:</strong> Initially, the marbles are at positions 1,6,7,8. At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. At the end, the final positions containing at least one marbles are [5,6,8,9].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] <strong>Output:</strong> [2] <strong>Explanation:</strong> Initially, the marbles are at positions [1,1,3,3]. At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. Since 2 is the only occupied position, we return [2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= moveFrom.length &lt;= 10<sup>5</sup></code></li> <li><code>moveFrom.length == moveTo.length</code></li> <li><code>1 &lt;= nums[i], moveFrom[i], moveTo[i] &lt;= 10<sup>9</sup></code></li> <li>The test cases are generated such that there is at least a marble in&nbsp;<code>moveFrom[i]</code>&nbsp;at the moment we want to apply&nbsp;the <code>i<sup>th</sup></code>&nbsp;move.</li> </ul>
Array; Hash Table; Sorting; Simulation
Java
class Solution { public List<Integer> relocateMarbles(int[] nums, int[] moveFrom, int[] moveTo) { Set<Integer> pos = new HashSet<>(); for (int x : nums) { pos.add(x); } for (int i = 0; i < moveFrom.length; ++i) { pos.remove(moveFrom[i]); pos.add(moveTo[i]); } List<Integer> ans = new ArrayList<>(pos); ans.sort((a, b) -> a - b); return ans; } }
2,766
Relocate Marbles
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the initial positions of some marbles. You are also given two <strong>0-indexed </strong>integer arrays <code>moveFrom</code> and <code>moveTo</code> of <strong>equal</strong> length.</p> <p>Throughout <code>moveFrom.length</code> steps, you will change the positions of the marbles. On the <code>i<sup>th</sup></code> step, you will move <strong>all</strong> marbles at position <code>moveFrom[i]</code> to position <code>moveTo[i]</code>.</p> <p>After completing all the steps, return <em>the sorted list of <strong>occupied</strong> positions</em>.</p> <p><strong>Notes:</strong></p> <ul> <li>We call a position <strong>occupied</strong> if there is at least one marble in that position.</li> <li>There may be multiple marbles in a single position.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] <strong>Output:</strong> [5,6,8,9] <strong>Explanation:</strong> Initially, the marbles are at positions 1,6,7,8. At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. At the end, the final positions containing at least one marbles are [5,6,8,9].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] <strong>Output:</strong> [2] <strong>Explanation:</strong> Initially, the marbles are at positions [1,1,3,3]. At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. Since 2 is the only occupied position, we return [2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= moveFrom.length &lt;= 10<sup>5</sup></code></li> <li><code>moveFrom.length == moveTo.length</code></li> <li><code>1 &lt;= nums[i], moveFrom[i], moveTo[i] &lt;= 10<sup>9</sup></code></li> <li>The test cases are generated such that there is at least a marble in&nbsp;<code>moveFrom[i]</code>&nbsp;at the moment we want to apply&nbsp;the <code>i<sup>th</sup></code>&nbsp;move.</li> </ul>
Array; Hash Table; Sorting; Simulation
Python
class Solution: def relocateMarbles( self, nums: List[int], moveFrom: List[int], moveTo: List[int] ) -> List[int]: pos = set(nums) for f, t in zip(moveFrom, moveTo): pos.remove(f) pos.add(t) return sorted(pos)
2,766
Relocate Marbles
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the initial positions of some marbles. You are also given two <strong>0-indexed </strong>integer arrays <code>moveFrom</code> and <code>moveTo</code> of <strong>equal</strong> length.</p> <p>Throughout <code>moveFrom.length</code> steps, you will change the positions of the marbles. On the <code>i<sup>th</sup></code> step, you will move <strong>all</strong> marbles at position <code>moveFrom[i]</code> to position <code>moveTo[i]</code>.</p> <p>After completing all the steps, return <em>the sorted list of <strong>occupied</strong> positions</em>.</p> <p><strong>Notes:</strong></p> <ul> <li>We call a position <strong>occupied</strong> if there is at least one marble in that position.</li> <li>There may be multiple marbles in a single position.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] <strong>Output:</strong> [5,6,8,9] <strong>Explanation:</strong> Initially, the marbles are at positions 1,6,7,8. At the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied. At the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied. At the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied. At the end, the final positions containing at least one marbles are [5,6,8,9].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] <strong>Output:</strong> [2] <strong>Explanation:</strong> Initially, the marbles are at positions [1,1,3,3]. At the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3]. At the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2]. Since 2 is the only occupied position, we return [2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= moveFrom.length &lt;= 10<sup>5</sup></code></li> <li><code>moveFrom.length == moveTo.length</code></li> <li><code>1 &lt;= nums[i], moveFrom[i], moveTo[i] &lt;= 10<sup>9</sup></code></li> <li>The test cases are generated such that there is at least a marble in&nbsp;<code>moveFrom[i]</code>&nbsp;at the moment we want to apply&nbsp;the <code>i<sup>th</sup></code>&nbsp;move.</li> </ul>
Array; Hash Table; Sorting; Simulation
TypeScript
function relocateMarbles(nums: number[], moveFrom: number[], moveTo: number[]): number[] { const pos: Set<number> = new Set(nums); for (let i = 0; i < moveFrom.length; i++) { pos.delete(moveFrom[i]); pos.add(moveTo[i]); } return [...pos].sort((a, b) => a - b); }
2,767
Partition String Into Minimum Beautiful Substrings
Medium
<p>Given a binary string <code>s</code>, partition the string into one or more <strong>substrings</strong> such that each substring is <strong>beautiful</strong>.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It doesn&#39;t contain leading zeros.</li> <li>It&#39;s the <strong>binary</strong> representation of a number that is a power of <code>5</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of substrings in such partition. </em>If it is impossible to partition the string <code>s</code> into beautiful substrings,&nbsp;return <code>-1</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can paritition the given string into [&quot;101&quot;, &quot;1&quot;]. - The string &quot;101&quot; does not contain leading zeros and is the binary representation of integer 5<sup>1</sup> = 5. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can paritition the given string into [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;]. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;0&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> We can not partition the given string into beautiful substrings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Hash Table; String; Dynamic Programming; Backtracking
C++
class Solution { public: int minimumBeautifulSubstrings(string s) { unordered_set<long long> ss; int n = s.size(); long long x = 1; for (int i = 0; i <= n; ++i) { ss.insert(x); x *= 5; } int f[n]; memset(f, -1, sizeof(f)); function<int(int)> dfs = [&](int i) { if (i >= n) { return 0; } if (s[i] == '0') { return n + 1; } if (f[i] != -1) { return f[i]; } long long x = 0; int ans = n + 1; for (int j = i; j < n; ++j) { x = x << 1 | (s[j] - '0'); if (ss.count(x)) { ans = min(ans, 1 + dfs(j + 1)); } } return f[i] = ans; }; int ans = dfs(0); return ans > n ? -1 : ans; } };
2,767
Partition String Into Minimum Beautiful Substrings
Medium
<p>Given a binary string <code>s</code>, partition the string into one or more <strong>substrings</strong> such that each substring is <strong>beautiful</strong>.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It doesn&#39;t contain leading zeros.</li> <li>It&#39;s the <strong>binary</strong> representation of a number that is a power of <code>5</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of substrings in such partition. </em>If it is impossible to partition the string <code>s</code> into beautiful substrings,&nbsp;return <code>-1</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can paritition the given string into [&quot;101&quot;, &quot;1&quot;]. - The string &quot;101&quot; does not contain leading zeros and is the binary representation of integer 5<sup>1</sup> = 5. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can paritition the given string into [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;]. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;0&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> We can not partition the given string into beautiful substrings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Hash Table; String; Dynamic Programming; Backtracking
Go
func minimumBeautifulSubstrings(s string) int { ss := map[int]bool{} n := len(s) x := 1 f := make([]int, n+1) for i := 0; i <= n; i++ { ss[x] = true x *= 5 f[i] = -1 } var dfs func(int) int dfs = func(i int) int { if i >= n { return 0 } if s[i] == '0' { return n + 1 } if f[i] != -1 { return f[i] } f[i] = n + 1 x := 0 for j := i; j < n; j++ { x = x<<1 | int(s[j]-'0') if ss[x] { f[i] = min(f[i], 1+dfs(j+1)) } } return f[i] } ans := dfs(0) if ans > n { return -1 } return ans }
2,767
Partition String Into Minimum Beautiful Substrings
Medium
<p>Given a binary string <code>s</code>, partition the string into one or more <strong>substrings</strong> such that each substring is <strong>beautiful</strong>.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It doesn&#39;t contain leading zeros.</li> <li>It&#39;s the <strong>binary</strong> representation of a number that is a power of <code>5</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of substrings in such partition. </em>If it is impossible to partition the string <code>s</code> into beautiful substrings,&nbsp;return <code>-1</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can paritition the given string into [&quot;101&quot;, &quot;1&quot;]. - The string &quot;101&quot; does not contain leading zeros and is the binary representation of integer 5<sup>1</sup> = 5. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can paritition the given string into [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;]. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;0&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> We can not partition the given string into beautiful substrings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Hash Table; String; Dynamic Programming; Backtracking
Java
class Solution { private Integer[] f; private String s; private Set<Long> ss = new HashSet<>(); private int n; public int minimumBeautifulSubstrings(String s) { n = s.length(); this.s = s; f = new Integer[n]; long x = 1; for (int i = 0; i <= n; ++i) { ss.add(x); x *= 5; } int ans = dfs(0); return ans > n ? -1 : ans; } private int dfs(int i) { if (i >= n) { return 0; } if (s.charAt(i) == '0') { return n + 1; } if (f[i] != null) { return f[i]; } long x = 0; int ans = n + 1; for (int j = i; j < n; ++j) { x = x << 1 | (s.charAt(j) - '0'); if (ss.contains(x)) { ans = Math.min(ans, 1 + dfs(j + 1)); } } return f[i] = ans; } }
2,767
Partition String Into Minimum Beautiful Substrings
Medium
<p>Given a binary string <code>s</code>, partition the string into one or more <strong>substrings</strong> such that each substring is <strong>beautiful</strong>.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It doesn&#39;t contain leading zeros.</li> <li>It&#39;s the <strong>binary</strong> representation of a number that is a power of <code>5</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of substrings in such partition. </em>If it is impossible to partition the string <code>s</code> into beautiful substrings,&nbsp;return <code>-1</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can paritition the given string into [&quot;101&quot;, &quot;1&quot;]. - The string &quot;101&quot; does not contain leading zeros and is the binary representation of integer 5<sup>1</sup> = 5. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can paritition the given string into [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;]. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;0&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> We can not partition the given string into beautiful substrings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Hash Table; String; Dynamic Programming; Backtracking
Python
class Solution: def minimumBeautifulSubstrings(self, s: str) -> int: @cache def dfs(i: int) -> int: if i >= n: return 0 if s[i] == "0": return inf x = 0 ans = inf for j in range(i, n): x = x << 1 | int(s[j]) if x in ss: ans = min(ans, 1 + dfs(j + 1)) return ans n = len(s) x = 1 ss = {x} for i in range(n): x *= 5 ss.add(x) ans = dfs(0) return -1 if ans == inf else ans
2,767
Partition String Into Minimum Beautiful Substrings
Medium
<p>Given a binary string <code>s</code>, partition the string into one or more <strong>substrings</strong> such that each substring is <strong>beautiful</strong>.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It doesn&#39;t contain leading zeros.</li> <li>It&#39;s the <strong>binary</strong> representation of a number that is a power of <code>5</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of substrings in such partition. </em>If it is impossible to partition the string <code>s</code> into beautiful substrings,&nbsp;return <code>-1</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can paritition the given string into [&quot;101&quot;, &quot;1&quot;]. - The string &quot;101&quot; does not contain leading zeros and is the binary representation of integer 5<sup>1</sup> = 5. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can paritition the given string into [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;]. - The string &quot;1&quot; does not contain leading zeros and is the binary representation of integer 5<sup>0</sup> = 1. It can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;0&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> We can not partition the given string into beautiful substrings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Hash Table; String; Dynamic Programming; Backtracking
TypeScript
function minimumBeautifulSubstrings(s: string): number { const ss: Set<number> = new Set(); const n = s.length; const f: number[] = new Array(n).fill(-1); for (let i = 0, x = 1; i <= n; ++i) { ss.add(x); x *= 5; } const dfs = (i: number): number => { if (i === n) { return 0; } if (s[i] === '0') { return n + 1; } if (f[i] !== -1) { return f[i]; } f[i] = n + 1; for (let j = i, x = 0; j < n; ++j) { x = (x << 1) | (s[j] === '1' ? 1 : 0); if (ss.has(x)) { f[i] = Math.min(f[i], 1 + dfs(j + 1)); } } return f[i]; }; const ans = dfs(0); return ans > n ? -1 : ans; }
2,768
Number of Black Blocks
Medium
<p>You are given two integers <code>m</code> and <code>n</code> representing the dimensions of a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code> grid.</p> <p>You are also given a <strong>0-indexed</strong> 2D integer matrix <code>coordinates</code>, where <code>coordinates[i] = [x, y]</code> indicates that the cell with coordinates <code>[x, y]</code> is colored <strong>black</strong>. All cells in the grid that do not appear in <code>coordinates</code> are <strong>white</strong>.</p> <p>A block is defined as a <code>2 x 2</code> submatrix of the grid. More formally, a block with cell <code>[x, y]</code> as its top-left corner where <code>0 &lt;= x &lt; m - 1</code> and <code>0 &lt;= y &lt; n - 1</code> contains the coordinates <code>[x, y]</code>, <code>[x + 1, y]</code>, <code>[x, y + 1]</code>, and <code>[x + 1, y + 1]</code>.</p> <p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of size</em> <code>5</code> <em>such that</em> <code>arr[i]</code> <em>is the number of blocks that contains exactly</em> <code>i</code> <em><strong>black</strong> cells</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0]] <strong>Output:</strong> [3,1,0,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-44656-am.png" style="width: 150px; height: 128px;" /> There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]] <strong>Output:</strong> [0,2,2,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-45018-am.png" style="width: 150px; height: 128px;" /> There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. Therefore, we return [0,2,2,0,0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= coordinates.length &lt;= 10<sup>4</sup></code></li> <li><code>coordinates[i].length == 2</code></li> <li><code>0 &lt;= coordinates[i][0] &lt; m</code></li> <li><code>0 &lt;= coordinates[i][1] &lt; n</code></li> <li>It is guaranteed that <code>coordinates</code> contains pairwise distinct coordinates.</li> </ul>
Array; Hash Table; Enumeration
C++
class Solution { public: vector<long long> countBlackBlocks(int m, int n, vector<vector<int>>& coordinates) { unordered_map<long long, int> cnt; int dirs[5] = {0, 0, -1, -1, 0}; for (auto& e : coordinates) { int x = e[0], y = e[1]; for (int k = 0; k < 4; ++k) { int i = x + dirs[k], j = y + dirs[k + 1]; if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { ++cnt[1LL * i * n + j]; } } } vector<long long> ans(5); ans[0] = (m - 1LL) * (n - 1); for (auto& [_, x] : cnt) { ++ans[x]; --ans[0]; } return ans; } };
2,768
Number of Black Blocks
Medium
<p>You are given two integers <code>m</code> and <code>n</code> representing the dimensions of a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code> grid.</p> <p>You are also given a <strong>0-indexed</strong> 2D integer matrix <code>coordinates</code>, where <code>coordinates[i] = [x, y]</code> indicates that the cell with coordinates <code>[x, y]</code> is colored <strong>black</strong>. All cells in the grid that do not appear in <code>coordinates</code> are <strong>white</strong>.</p> <p>A block is defined as a <code>2 x 2</code> submatrix of the grid. More formally, a block with cell <code>[x, y]</code> as its top-left corner where <code>0 &lt;= x &lt; m - 1</code> and <code>0 &lt;= y &lt; n - 1</code> contains the coordinates <code>[x, y]</code>, <code>[x + 1, y]</code>, <code>[x, y + 1]</code>, and <code>[x + 1, y + 1]</code>.</p> <p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of size</em> <code>5</code> <em>such that</em> <code>arr[i]</code> <em>is the number of blocks that contains exactly</em> <code>i</code> <em><strong>black</strong> cells</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0]] <strong>Output:</strong> [3,1,0,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-44656-am.png" style="width: 150px; height: 128px;" /> There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]] <strong>Output:</strong> [0,2,2,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-45018-am.png" style="width: 150px; height: 128px;" /> There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. Therefore, we return [0,2,2,0,0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= coordinates.length &lt;= 10<sup>4</sup></code></li> <li><code>coordinates[i].length == 2</code></li> <li><code>0 &lt;= coordinates[i][0] &lt; m</code></li> <li><code>0 &lt;= coordinates[i][1] &lt; n</code></li> <li>It is guaranteed that <code>coordinates</code> contains pairwise distinct coordinates.</li> </ul>
Array; Hash Table; Enumeration
Go
func countBlackBlocks(m int, n int, coordinates [][]int) []int64 { cnt := map[int64]int{} dirs := [5]int{0, 0, -1, -1, 0} for _, e := range coordinates { x, y := e[0], e[1] for k := 0; k < 4; k++ { i, j := x+dirs[k], y+dirs[k+1] if i >= 0 && i < m-1 && j >= 0 && j < n-1 { cnt[int64(i*n+j)]++ } } } ans := make([]int64, 5) ans[0] = int64((m - 1) * (n - 1)) for _, x := range cnt { ans[x]++ ans[0]-- } return ans }
2,768
Number of Black Blocks
Medium
<p>You are given two integers <code>m</code> and <code>n</code> representing the dimensions of a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code> grid.</p> <p>You are also given a <strong>0-indexed</strong> 2D integer matrix <code>coordinates</code>, where <code>coordinates[i] = [x, y]</code> indicates that the cell with coordinates <code>[x, y]</code> is colored <strong>black</strong>. All cells in the grid that do not appear in <code>coordinates</code> are <strong>white</strong>.</p> <p>A block is defined as a <code>2 x 2</code> submatrix of the grid. More formally, a block with cell <code>[x, y]</code> as its top-left corner where <code>0 &lt;= x &lt; m - 1</code> and <code>0 &lt;= y &lt; n - 1</code> contains the coordinates <code>[x, y]</code>, <code>[x + 1, y]</code>, <code>[x, y + 1]</code>, and <code>[x + 1, y + 1]</code>.</p> <p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of size</em> <code>5</code> <em>such that</em> <code>arr[i]</code> <em>is the number of blocks that contains exactly</em> <code>i</code> <em><strong>black</strong> cells</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0]] <strong>Output:</strong> [3,1,0,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-44656-am.png" style="width: 150px; height: 128px;" /> There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]] <strong>Output:</strong> [0,2,2,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-45018-am.png" style="width: 150px; height: 128px;" /> There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. Therefore, we return [0,2,2,0,0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= coordinates.length &lt;= 10<sup>4</sup></code></li> <li><code>coordinates[i].length == 2</code></li> <li><code>0 &lt;= coordinates[i][0] &lt; m</code></li> <li><code>0 &lt;= coordinates[i][1] &lt; n</code></li> <li>It is guaranteed that <code>coordinates</code> contains pairwise distinct coordinates.</li> </ul>
Array; Hash Table; Enumeration
Java
class Solution { public long[] countBlackBlocks(int m, int n, int[][] coordinates) { Map<Long, Integer> cnt = new HashMap<>(coordinates.length); int[] dirs = {0, 0, -1, -1, 0}; for (var e : coordinates) { int x = e[0], y = e[1]; for (int k = 0; k < 4; ++k) { int i = x + dirs[k], j = y + dirs[k + 1]; if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { cnt.merge(1L * i * n + j, 1, Integer::sum); } } } long[] ans = new long[5]; ans[0] = (m - 1L) * (n - 1); for (int x : cnt.values()) { ++ans[x]; --ans[0]; } return ans; } }
2,768
Number of Black Blocks
Medium
<p>You are given two integers <code>m</code> and <code>n</code> representing the dimensions of a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code> grid.</p> <p>You are also given a <strong>0-indexed</strong> 2D integer matrix <code>coordinates</code>, where <code>coordinates[i] = [x, y]</code> indicates that the cell with coordinates <code>[x, y]</code> is colored <strong>black</strong>. All cells in the grid that do not appear in <code>coordinates</code> are <strong>white</strong>.</p> <p>A block is defined as a <code>2 x 2</code> submatrix of the grid. More formally, a block with cell <code>[x, y]</code> as its top-left corner where <code>0 &lt;= x &lt; m - 1</code> and <code>0 &lt;= y &lt; n - 1</code> contains the coordinates <code>[x, y]</code>, <code>[x + 1, y]</code>, <code>[x, y + 1]</code>, and <code>[x + 1, y + 1]</code>.</p> <p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of size</em> <code>5</code> <em>such that</em> <code>arr[i]</code> <em>is the number of blocks that contains exactly</em> <code>i</code> <em><strong>black</strong> cells</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0]] <strong>Output:</strong> [3,1,0,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-44656-am.png" style="width: 150px; height: 128px;" /> There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]] <strong>Output:</strong> [0,2,2,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-45018-am.png" style="width: 150px; height: 128px;" /> There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. Therefore, we return [0,2,2,0,0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= coordinates.length &lt;= 10<sup>4</sup></code></li> <li><code>coordinates[i].length == 2</code></li> <li><code>0 &lt;= coordinates[i][0] &lt; m</code></li> <li><code>0 &lt;= coordinates[i][1] &lt; n</code></li> <li>It is guaranteed that <code>coordinates</code> contains pairwise distinct coordinates.</li> </ul>
Array; Hash Table; Enumeration
Python
class Solution: def countBlackBlocks( self, m: int, n: int, coordinates: List[List[int]] ) -> List[int]: cnt = Counter() for x, y in coordinates: for a, b in pairwise((0, 0, -1, -1, 0)): i, j = x + a, y + b if 0 <= i < m - 1 and 0 <= j < n - 1: cnt[(i, j)] += 1 ans = [0] * 5 for x in cnt.values(): ans[x] += 1 ans[0] = (m - 1) * (n - 1) - len(cnt.values()) return ans
2,768
Number of Black Blocks
Medium
<p>You are given two integers <code>m</code> and <code>n</code> representing the dimensions of a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code> grid.</p> <p>You are also given a <strong>0-indexed</strong> 2D integer matrix <code>coordinates</code>, where <code>coordinates[i] = [x, y]</code> indicates that the cell with coordinates <code>[x, y]</code> is colored <strong>black</strong>. All cells in the grid that do not appear in <code>coordinates</code> are <strong>white</strong>.</p> <p>A block is defined as a <code>2 x 2</code> submatrix of the grid. More formally, a block with cell <code>[x, y]</code> as its top-left corner where <code>0 &lt;= x &lt; m - 1</code> and <code>0 &lt;= y &lt; n - 1</code> contains the coordinates <code>[x, y]</code>, <code>[x + 1, y]</code>, <code>[x, y + 1]</code>, and <code>[x + 1, y + 1]</code>.</p> <p>Return <em>a <strong>0-indexed</strong> integer array</em> <code>arr</code> <em>of size</em> <code>5</code> <em>such that</em> <code>arr[i]</code> <em>is the number of blocks that contains exactly</em> <code>i</code> <em><strong>black</strong> cells</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0]] <strong>Output:</strong> [3,1,0,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-44656-am.png" style="width: 150px; height: 128px;" /> There is only 1 block with one black cell, and it is the block starting with cell [0,0]. The other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. Thus, we return [3,1,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]] <strong>Output:</strong> [0,2,2,0,0] <strong>Explanation:</strong> The grid looks like this: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2768.Number%20of%20Black%20Blocks/images/screen-shot-2023-06-18-at-45018-am.png" style="width: 150px; height: 128px;" /> There are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]). The other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell. Therefore, we return [0,2,2,0,0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= coordinates.length &lt;= 10<sup>4</sup></code></li> <li><code>coordinates[i].length == 2</code></li> <li><code>0 &lt;= coordinates[i][0] &lt; m</code></li> <li><code>0 &lt;= coordinates[i][1] &lt; n</code></li> <li>It is guaranteed that <code>coordinates</code> contains pairwise distinct coordinates.</li> </ul>
Array; Hash Table; Enumeration
TypeScript
function countBlackBlocks(m: number, n: number, coordinates: number[][]): number[] { const cnt: Map<number, number> = new Map(); const dirs: number[] = [0, 0, -1, -1, 0]; for (const [x, y] of coordinates) { for (let k = 0; k < 4; ++k) { const [i, j] = [x + dirs[k], y + dirs[k + 1]]; if (i >= 0 && i < m - 1 && j >= 0 && j < n - 1) { const key = i * n + j; cnt.set(key, (cnt.get(key) || 0) + 1); } } } const ans: number[] = Array(5).fill(0); ans[0] = (m - 1) * (n - 1); for (const [_, x] of cnt) { ++ans[x]; --ans[0]; } return ans; }
2,769
Find the Maximum Achievable Number
Easy
<p>Given two integers, <code>num</code> and <code>t</code>. A <strong>number </strong><code>x</code><strong> </strong>is<strong> achievable</strong> if it can become equal to <code>num</code> after applying the following operation <strong>at most</strong> <code>t</code> times:</p> <ul> <li>Increase or decrease <code>x</code> by <code>1</code>, and <em>simultaneously</em> increase or decrease <code>num</code> by <code>1</code>.</li> </ul> <p>Return the <strong>maximum </strong>possible value of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 4, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation once to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation twice to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li> </ul>
Math
C++
class Solution { public: int theMaximumAchievableX(int num, int t) { return num + t * 2; } };
2,769
Find the Maximum Achievable Number
Easy
<p>Given two integers, <code>num</code> and <code>t</code>. A <strong>number </strong><code>x</code><strong> </strong>is<strong> achievable</strong> if it can become equal to <code>num</code> after applying the following operation <strong>at most</strong> <code>t</code> times:</p> <ul> <li>Increase or decrease <code>x</code> by <code>1</code>, and <em>simultaneously</em> increase or decrease <code>num</code> by <code>1</code>.</li> </ul> <p>Return the <strong>maximum </strong>possible value of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 4, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation once to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation twice to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li> </ul>
Math
Go
func theMaximumAchievableX(num int, t int) int { return num + t*2 }
2,769
Find the Maximum Achievable Number
Easy
<p>Given two integers, <code>num</code> and <code>t</code>. A <strong>number </strong><code>x</code><strong> </strong>is<strong> achievable</strong> if it can become equal to <code>num</code> after applying the following operation <strong>at most</strong> <code>t</code> times:</p> <ul> <li>Increase or decrease <code>x</code> by <code>1</code>, and <em>simultaneously</em> increase or decrease <code>num</code> by <code>1</code>.</li> </ul> <p>Return the <strong>maximum </strong>possible value of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 4, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation once to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation twice to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li> </ul>
Math
Java
class Solution { public int theMaximumAchievableX(int num, int t) { return num + t * 2; } }
2,769
Find the Maximum Achievable Number
Easy
<p>Given two integers, <code>num</code> and <code>t</code>. A <strong>number </strong><code>x</code><strong> </strong>is<strong> achievable</strong> if it can become equal to <code>num</code> after applying the following operation <strong>at most</strong> <code>t</code> times:</p> <ul> <li>Increase or decrease <code>x</code> by <code>1</code>, and <em>simultaneously</em> increase or decrease <code>num</code> by <code>1</code>.</li> </ul> <p>Return the <strong>maximum </strong>possible value of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 4, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation once to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation twice to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li> </ul>
Math
Python
class Solution: def theMaximumAchievableX(self, num: int, t: int) -> int: return num + t * 2
2,769
Find the Maximum Achievable Number
Easy
<p>Given two integers, <code>num</code> and <code>t</code>. A <strong>number </strong><code>x</code><strong> </strong>is<strong> achievable</strong> if it can become equal to <code>num</code> after applying the following operation <strong>at most</strong> <code>t</code> times:</p> <ul> <li>Increase or decrease <code>x</code> by <code>1</code>, and <em>simultaneously</em> increase or decrease <code>num</code> by <code>1</code>.</li> </ul> <p>Return the <strong>maximum </strong>possible value of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 4, t = 1</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation once to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Apply the following operation twice to make the maximum achievable number equal to <code>num</code>:</p> <ul> <li>Decrease the maximum achievable number by 1, and increase <code>num</code> by 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li> </ul>
Math
TypeScript
function theMaximumAchievableX(num: number, t: number): number { return num + t * 2; }
2,770
Maximum Number of Jumps to Reach the Last Index
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <code>n</code> integers and an integer <code>target</code>.</p> <p>You are initially positioned at index <code>0</code>. In one step, you can jump from index <code>i</code> to any index <code>j</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code></li> <li><code>-target &lt;= nums[j] - nums[i] &lt;= target</code></li> </ul> <p>Return <em>the <strong>maximum number of jumps</strong> you can make to reach index</em> <code>n - 1</code>.</p> <p>If there is no way to reach index <code>n - 1</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 3. - Jump from index 3 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 2. - Jump from index 2 to index 3. - Jump from index 3 to index 4. - Jump from index 4 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 0 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= target &lt;= 2 * 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maximumJumps(vector<int>& nums, int target) { int n = nums.size(); int f[n]; memset(f, -1, sizeof(f)); function<int(int)> dfs = [&](int i) { if (i == n - 1) { return 0; } if (f[i] != -1) { return f[i]; } f[i] = -(1 << 30); for (int j = i + 1; j < n; ++j) { if (abs(nums[i] - nums[j]) <= target) { f[i] = max(f[i], 1 + dfs(j)); } } return f[i]; }; int ans = dfs(0); return ans < 0 ? -1 : ans; } };
2,770
Maximum Number of Jumps to Reach the Last Index
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <code>n</code> integers and an integer <code>target</code>.</p> <p>You are initially positioned at index <code>0</code>. In one step, you can jump from index <code>i</code> to any index <code>j</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code></li> <li><code>-target &lt;= nums[j] - nums[i] &lt;= target</code></li> </ul> <p>Return <em>the <strong>maximum number of jumps</strong> you can make to reach index</em> <code>n - 1</code>.</p> <p>If there is no way to reach index <code>n - 1</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 3. - Jump from index 3 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 2. - Jump from index 2 to index 3. - Jump from index 3 to index 4. - Jump from index 4 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 0 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= target &lt;= 2 * 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumJumps(nums []int, target int) int { n := len(nums) f := make([]int, n) for i := range f { f[i] = -1 } var dfs func(int) int dfs = func(i int) int { if i == n-1 { return 0 } if f[i] != -1 { return f[i] } f[i] = -(1 << 30) for j := i + 1; j < n; j++ { if abs(nums[i]-nums[j]) <= target { f[i] = max(f[i], 1+dfs(j)) } } return f[i] } ans := dfs(0) if ans < 0 { return -1 } return ans } func abs(x int) int { if x < 0 { return -x } return x }
2,770
Maximum Number of Jumps to Reach the Last Index
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <code>n</code> integers and an integer <code>target</code>.</p> <p>You are initially positioned at index <code>0</code>. In one step, you can jump from index <code>i</code> to any index <code>j</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code></li> <li><code>-target &lt;= nums[j] - nums[i] &lt;= target</code></li> </ul> <p>Return <em>the <strong>maximum number of jumps</strong> you can make to reach index</em> <code>n - 1</code>.</p> <p>If there is no way to reach index <code>n - 1</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 3. - Jump from index 3 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 2. - Jump from index 2 to index 3. - Jump from index 3 to index 4. - Jump from index 4 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 0 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= target &lt;= 2 * 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private Integer[] f; private int[] nums; private int n; private int target; public int maximumJumps(int[] nums, int target) { n = nums.length; this.target = target; this.nums = nums; f = new Integer[n]; int ans = dfs(0); return ans < 0 ? -1 : ans; } private int dfs(int i) { if (i == n - 1) { return 0; } if (f[i] != null) { return f[i]; } int ans = -(1 << 30); for (int j = i + 1; j < n; ++j) { if (Math.abs(nums[i] - nums[j]) <= target) { ans = Math.max(ans, 1 + dfs(j)); } } return f[i] = ans; } }
2,770
Maximum Number of Jumps to Reach the Last Index
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <code>n</code> integers and an integer <code>target</code>.</p> <p>You are initially positioned at index <code>0</code>. In one step, you can jump from index <code>i</code> to any index <code>j</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code></li> <li><code>-target &lt;= nums[j] - nums[i] &lt;= target</code></li> </ul> <p>Return <em>the <strong>maximum number of jumps</strong> you can make to reach index</em> <code>n - 1</code>.</p> <p>If there is no way to reach index <code>n - 1</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 3. - Jump from index 3 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 2. - Jump from index 2 to index 3. - Jump from index 3 to index 4. - Jump from index 4 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 0 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= target &lt;= 2 * 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumJumps(self, nums: List[int], target: int) -> int: @cache def dfs(i: int) -> int: if i == n - 1: return 0 ans = -inf for j in range(i + 1, n): if abs(nums[i] - nums[j]) <= target: ans = max(ans, 1 + dfs(j)) return ans n = len(nums) ans = dfs(0) return -1 if ans < 0 else ans
2,770
Maximum Number of Jumps to Reach the Last Index
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <code>n</code> integers and an integer <code>target</code>.</p> <p>You are initially positioned at index <code>0</code>. In one step, you can jump from index <code>i</code> to any index <code>j</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code></li> <li><code>-target &lt;= nums[j] - nums[i] &lt;= target</code></li> </ul> <p>Return <em>the <strong>maximum number of jumps</strong> you can make to reach index</em> <code>n - 1</code>.</p> <p>If there is no way to reach index <code>n - 1</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 3. - Jump from index 3 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: - Jump from index 0 to index 1. - Jump from index 1 to index 2. - Jump from index 2 to index 3. - Jump from index 3 to index 4. - Jump from index 4 to index 5. It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,6,4,1,2], target = 0 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= target &lt;= 2 * 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumJumps(nums: number[], target: number): number { const n = nums.length; const f: number[] = Array(n).fill(-1); const dfs = (i: number): number => { if (i === n - 1) { return 0; } if (f[i] !== -1) { return f[i]; } f[i] = -(1 << 30); for (let j = i + 1; j < n; ++j) { if (Math.abs(nums[i] - nums[j]) <= target) { f[i] = Math.max(f[i], 1 + dfs(j)); } } return f[i]; }; const ans = dfs(0); return ans < 0 ? -1 : ans; }
2,771
Longest Non-decreasing Subarray From Two Arrays
Medium
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>.</p> <p>Let&#39;s define another <strong>0-indexed</strong> integer array, <code>nums3</code>, of length <code>n</code>. For each index <code>i</code> in the range <code>[0, n - 1]</code>, you can assign either <code>nums1[i]</code> or <code>nums2[i]</code> to <code>nums3[i]</code>.</p> <p>Your task is to maximize the length of the <strong>longest non-decreasing subarray</strong> in <code>nums3</code> by choosing its values optimally.</p> <p>Return <em>an integer representing the length of the <strong>longest non-decreasing</strong> subarray in</em> <code>nums3</code>.</p> <p><strong>Note: </strong>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [2,3,1], nums2 = [1,2,1] <strong>Output:</strong> 2 <strong>Explanation: </strong>One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2]] =&gt; [2,2,1]. The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. We can show that 2 is the maximum achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3,2,1], nums2 = [2,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] =&gt; [1,2,3,4]. The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1], nums2 = [2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums1[1]] =&gt; [1,1]. The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length == nums2.length == n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int f = 1, g = 1; int ans = 1; for (int i = 1; i < n; ++i) { int ff = 1, gg = 1; if (nums1[i] >= nums1[i - 1]) { ff = max(ff, f + 1); } if (nums1[i] >= nums2[i - 1]) { ff = max(ff, g + 1); } if (nums2[i] >= nums1[i - 1]) { gg = max(gg, f + 1); } if (nums2[i] >= nums2[i - 1]) { gg = max(gg, g + 1); } f = ff; g = gg; ans = max(ans, max(f, g)); } return ans; } };
2,771
Longest Non-decreasing Subarray From Two Arrays
Medium
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>.</p> <p>Let&#39;s define another <strong>0-indexed</strong> integer array, <code>nums3</code>, of length <code>n</code>. For each index <code>i</code> in the range <code>[0, n - 1]</code>, you can assign either <code>nums1[i]</code> or <code>nums2[i]</code> to <code>nums3[i]</code>.</p> <p>Your task is to maximize the length of the <strong>longest non-decreasing subarray</strong> in <code>nums3</code> by choosing its values optimally.</p> <p>Return <em>an integer representing the length of the <strong>longest non-decreasing</strong> subarray in</em> <code>nums3</code>.</p> <p><strong>Note: </strong>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [2,3,1], nums2 = [1,2,1] <strong>Output:</strong> 2 <strong>Explanation: </strong>One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2]] =&gt; [2,2,1]. The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. We can show that 2 is the maximum achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3,2,1], nums2 = [2,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] =&gt; [1,2,3,4]. The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1], nums2 = [2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums1[1]] =&gt; [1,1]. The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length == nums2.length == n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxNonDecreasingLength(nums1 []int, nums2 []int) int { n := len(nums1) f, g, ans := 1, 1, 1 for i := 1; i < n; i++ { ff, gg := 1, 1 if nums1[i] >= nums1[i-1] { ff = max(ff, f+1) } if nums1[i] >= nums2[i-1] { ff = max(ff, g+1) } if nums2[i] >= nums1[i-1] { gg = max(gg, f+1) } if nums2[i] >= nums2[i-1] { gg = max(gg, g+1) } f, g = ff, gg ans = max(ans, max(f, g)) } return ans }
2,771
Longest Non-decreasing Subarray From Two Arrays
Medium
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>.</p> <p>Let&#39;s define another <strong>0-indexed</strong> integer array, <code>nums3</code>, of length <code>n</code>. For each index <code>i</code> in the range <code>[0, n - 1]</code>, you can assign either <code>nums1[i]</code> or <code>nums2[i]</code> to <code>nums3[i]</code>.</p> <p>Your task is to maximize the length of the <strong>longest non-decreasing subarray</strong> in <code>nums3</code> by choosing its values optimally.</p> <p>Return <em>an integer representing the length of the <strong>longest non-decreasing</strong> subarray in</em> <code>nums3</code>.</p> <p><strong>Note: </strong>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [2,3,1], nums2 = [1,2,1] <strong>Output:</strong> 2 <strong>Explanation: </strong>One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2]] =&gt; [2,2,1]. The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. We can show that 2 is the maximum achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3,2,1], nums2 = [2,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] =&gt; [1,2,3,4]. The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1], nums2 = [2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums1[1]] =&gt; [1,1]. The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length == nums2.length == n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maxNonDecreasingLength(int[] nums1, int[] nums2) { int n = nums1.length; int f = 1, g = 1; int ans = 1; for (int i = 1; i < n; ++i) { int ff = 1, gg = 1; if (nums1[i] >= nums1[i - 1]) { ff = Math.max(ff, f + 1); } if (nums1[i] >= nums2[i - 1]) { ff = Math.max(ff, g + 1); } if (nums2[i] >= nums1[i - 1]) { gg = Math.max(gg, f + 1); } if (nums2[i] >= nums2[i - 1]) { gg = Math.max(gg, g + 1); } f = ff; g = gg; ans = Math.max(ans, Math.max(f, g)); } return ans; } }
2,771
Longest Non-decreasing Subarray From Two Arrays
Medium
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>.</p> <p>Let&#39;s define another <strong>0-indexed</strong> integer array, <code>nums3</code>, of length <code>n</code>. For each index <code>i</code> in the range <code>[0, n - 1]</code>, you can assign either <code>nums1[i]</code> or <code>nums2[i]</code> to <code>nums3[i]</code>.</p> <p>Your task is to maximize the length of the <strong>longest non-decreasing subarray</strong> in <code>nums3</code> by choosing its values optimally.</p> <p>Return <em>an integer representing the length of the <strong>longest non-decreasing</strong> subarray in</em> <code>nums3</code>.</p> <p><strong>Note: </strong>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [2,3,1], nums2 = [1,2,1] <strong>Output:</strong> 2 <strong>Explanation: </strong>One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2]] =&gt; [2,2,1]. The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. We can show that 2 is the maximum achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3,2,1], nums2 = [2,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] =&gt; [1,2,3,4]. The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1], nums2 = [2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums1[1]] =&gt; [1,1]. The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length == nums2.length == n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) f = g = 1 ans = 1 for i in range(1, n): ff = gg = 1 if nums1[i] >= nums1[i - 1]: ff = max(ff, f + 1) if nums1[i] >= nums2[i - 1]: ff = max(ff, g + 1) if nums2[i] >= nums1[i - 1]: gg = max(gg, f + 1) if nums2[i] >= nums2[i - 1]: gg = max(gg, g + 1) f, g = ff, gg ans = max(ans, f, g) return ans
2,771
Longest Non-decreasing Subarray From Two Arrays
Medium
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>.</p> <p>Let&#39;s define another <strong>0-indexed</strong> integer array, <code>nums3</code>, of length <code>n</code>. For each index <code>i</code> in the range <code>[0, n - 1]</code>, you can assign either <code>nums1[i]</code> or <code>nums2[i]</code> to <code>nums3[i]</code>.</p> <p>Your task is to maximize the length of the <strong>longest non-decreasing subarray</strong> in <code>nums3</code> by choosing its values optimally.</p> <p>Return <em>an integer representing the length of the <strong>longest non-decreasing</strong> subarray in</em> <code>nums3</code>.</p> <p><strong>Note: </strong>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [2,3,1], nums2 = [1,2,1] <strong>Output:</strong> 2 <strong>Explanation: </strong>One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2]] =&gt; [2,2,1]. The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. We can show that 2 is the maximum achievable length.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,3,2,1], nums2 = [2,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] =&gt; [1,2,3,4]. The entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,1], nums2 = [2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to construct nums3 is: nums3 = [nums1[0], nums1[1]] =&gt; [1,1]. The entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length == nums2.length == n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxNonDecreasingLength(nums1: number[], nums2: number[]): number { const n = nums1.length; let [f, g, ans] = [1, 1, 1]; for (let i = 1; i < n; ++i) { let [ff, gg] = [1, 1]; if (nums1[i] >= nums1[i - 1]) { ff = Math.max(ff, f + 1); } if (nums1[i] >= nums2[i - 1]) { ff = Math.max(ff, g + 1); } if (nums2[i] >= nums1[i - 1]) { gg = Math.max(gg, f + 1); } if (nums2[i] >= nums2[i - 1]) { gg = Math.max(gg, g + 1); } f = ff; g = gg; ans = Math.max(ans, f, g); } return ans; }
2,772
Apply Operations to Make All Array Elements Equal to Zero
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p> <p>You can apply the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>any</strong> subarray of size <code>k</code> from the array and <strong>decrease</strong> all its elements by <code>1</code>.</li> </ul> <p>Return <code>true</code><em> if you can make all the array elements equal to </em><code>0</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1,1,0], k = 3 <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [<strong><u>1</u></strong>,<strong><u>1</u></strong>,<strong><u>2</u></strong>,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,<strong><u>1</u></strong>,<strong><u>0</u></strong>,<strong><u>0</u></strong>,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1], k = 2 <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make all the array elements equal to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Prefix Sum
C++
class Solution { public: bool checkArray(vector<int>& nums, int k) { int n = nums.size(); vector<int> d(n + 1); int s = 0; for (int i = 0; i < n; ++i) { s += d[i]; nums[i] += s; if (nums[i] == 0) { continue; } if (nums[i] < 0 || i + k > n) { return false; } s -= nums[i]; d[i + k] += nums[i]; } return true; } };
2,772
Apply Operations to Make All Array Elements Equal to Zero
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p> <p>You can apply the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>any</strong> subarray of size <code>k</code> from the array and <strong>decrease</strong> all its elements by <code>1</code>.</li> </ul> <p>Return <code>true</code><em> if you can make all the array elements equal to </em><code>0</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1,1,0], k = 3 <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [<strong><u>1</u></strong>,<strong><u>1</u></strong>,<strong><u>2</u></strong>,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,<strong><u>1</u></strong>,<strong><u>0</u></strong>,<strong><u>0</u></strong>,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1], k = 2 <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make all the array elements equal to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Prefix Sum
Go
func checkArray(nums []int, k int) bool { n := len(nums) d := make([]int, n+1) s := 0 for i, x := range nums { s += d[i] x += s if x == 0 { continue } if x < 0 || i+k > n { return false } s -= x d[i+k] += x } return true }
2,772
Apply Operations to Make All Array Elements Equal to Zero
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p> <p>You can apply the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>any</strong> subarray of size <code>k</code> from the array and <strong>decrease</strong> all its elements by <code>1</code>.</li> </ul> <p>Return <code>true</code><em> if you can make all the array elements equal to </em><code>0</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1,1,0], k = 3 <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [<strong><u>1</u></strong>,<strong><u>1</u></strong>,<strong><u>2</u></strong>,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,<strong><u>1</u></strong>,<strong><u>0</u></strong>,<strong><u>0</u></strong>,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1], k = 2 <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make all the array elements equal to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Prefix Sum
Java
class Solution { public boolean checkArray(int[] nums, int k) { int n = nums.length; int[] d = new int[n + 1]; int s = 0; for (int i = 0; i < n; ++i) { s += d[i]; nums[i] += s; if (nums[i] == 0) { continue; } if (nums[i] < 0 || i + k > n) { return false; } s -= nums[i]; d[i + k] += nums[i]; } return true; } }
2,772
Apply Operations to Make All Array Elements Equal to Zero
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p> <p>You can apply the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>any</strong> subarray of size <code>k</code> from the array and <strong>decrease</strong> all its elements by <code>1</code>.</li> </ul> <p>Return <code>true</code><em> if you can make all the array elements equal to </em><code>0</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1,1,0], k = 3 <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [<strong><u>1</u></strong>,<strong><u>1</u></strong>,<strong><u>2</u></strong>,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,<strong><u>1</u></strong>,<strong><u>0</u></strong>,<strong><u>0</u></strong>,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1], k = 2 <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make all the array elements equal to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Prefix Sum
Python
class Solution: def checkArray(self, nums: List[int], k: int) -> bool: n = len(nums) d = [0] * (n + 1) s = 0 for i, x in enumerate(nums): s += d[i] x += s if x == 0: continue if x < 0 or i + k > n: return False s -= x d[i + k] += x return True
2,772
Apply Operations to Make All Array Elements Equal to Zero
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a positive integer <code>k</code>.</p> <p>You can apply the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>any</strong> subarray of size <code>k</code> from the array and <strong>decrease</strong> all its elements by <code>1</code>.</li> </ul> <p>Return <code>true</code><em> if you can make all the array elements equal to </em><code>0</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subarray</strong> is a contiguous non-empty part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,3,1,1,0], k = 3 <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose the subarray [2,2,3]. The resulting array will be nums = [<strong><u>1</u></strong>,<strong><u>1</u></strong>,<strong><u>2</u></strong>,1,1,0]. - Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,<strong><u>1</u></strong>,<strong><u>0</u></strong>,<strong><u>0</u></strong>,0]. - Choose the subarray [1,1,1]. The resulting array will be nums = [<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,0,0,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1], k = 2 <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make all the array elements equal to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Prefix Sum
TypeScript
function checkArray(nums: number[], k: number): boolean { const n = nums.length; const d: number[] = Array(n + 1).fill(0); let s = 0; for (let i = 0; i < n; ++i) { s += d[i]; nums[i] += s; if (nums[i] === 0) { continue; } if (nums[i] < 0 || i + k > n) { return false; } s -= nums[i]; d[i + k] += nums[i]; } return true; }
2,773
Height of Special Binary Tree
Medium
<p>You are given a <code>root</code>, which is the root of a <strong>special</strong> binary tree with <code>n</code> nodes. The nodes of the special binary tree are numbered from <code>1</code> to <code>n</code>. Suppose the tree has <code>k</code> leaves in the following order: <code>b<sub>1 </sub>&lt;<sub> </sub>b<sub>2 </sub>&lt; ... &lt; b<sub>k</sub></code>.</p> <p>The leaves of this tree have a <strong>special</strong> property! That is, for every leaf <code>b<sub>i</sub></code>, the following conditions hold:</p> <ul> <li>The right child of <code>b<sub>i</sub></code> is <code>b<sub>i + 1</sub></code> if <code>i &lt; k</code>, and <code>b<sub>1</sub></code> otherwise.</li> <li>The left child of <code>b<sub>i</sub></code> is <code>b<sub>i - 1</sub></code> if <code>i &gt; 1</code>, and <code>b<sub>k</sub></code> otherwise.</li> </ul> <p>Return<em> the height of the given tree.</em></p> <p><strong>Note:</strong> The height of a binary tree is the length of the <strong>longest path</strong> from the root to any other node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> 2 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 200px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 <strong>Explanation: </strong>The given tree is shown in the following picture. There is only one leaf, so it doesn&#39;t have any left or right child. We can see that the graph has a height of 1. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 95px; height: 122px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,null,5,6] <strong>Output:</strong> 3 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 280px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of nodes in the tree</code></li> <li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= node.val &lt;= n</code></li> <li>The input is generated such that each <code>node.val</code> is unique.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int heightOfTree(TreeNode* root) { int ans = 0; function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int d) { ans = max(ans, d++); if (root->left && root->left->right != root) { dfs(root->left, d); } if (root->right && root->right->left != root) { dfs(root->right, d); } }; dfs(root, 0); return ans; } };
2,773
Height of Special Binary Tree
Medium
<p>You are given a <code>root</code>, which is the root of a <strong>special</strong> binary tree with <code>n</code> nodes. The nodes of the special binary tree are numbered from <code>1</code> to <code>n</code>. Suppose the tree has <code>k</code> leaves in the following order: <code>b<sub>1 </sub>&lt;<sub> </sub>b<sub>2 </sub>&lt; ... &lt; b<sub>k</sub></code>.</p> <p>The leaves of this tree have a <strong>special</strong> property! That is, for every leaf <code>b<sub>i</sub></code>, the following conditions hold:</p> <ul> <li>The right child of <code>b<sub>i</sub></code> is <code>b<sub>i + 1</sub></code> if <code>i &lt; k</code>, and <code>b<sub>1</sub></code> otherwise.</li> <li>The left child of <code>b<sub>i</sub></code> is <code>b<sub>i - 1</sub></code> if <code>i &gt; 1</code>, and <code>b<sub>k</sub></code> otherwise.</li> </ul> <p>Return<em> the height of the given tree.</em></p> <p><strong>Note:</strong> The height of a binary tree is the length of the <strong>longest path</strong> from the root to any other node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> 2 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 200px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 <strong>Explanation: </strong>The given tree is shown in the following picture. There is only one leaf, so it doesn&#39;t have any left or right child. We can see that the graph has a height of 1. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 95px; height: 122px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,null,5,6] <strong>Output:</strong> 3 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 280px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of nodes in the tree</code></li> <li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= node.val &lt;= n</code></li> <li>The input is generated such that each <code>node.val</code> is unique.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func heightOfTree(root *TreeNode) (ans int) { var dfs func(*TreeNode, int) dfs = func(root *TreeNode, d int) { if ans < d { ans = d } d++ if root.Left != nil && root.Left.Right != root { dfs(root.Left, d) } if root.Right != nil && root.Right.Left != root { dfs(root.Right, d) } } dfs(root, 0) return }
2,773
Height of Special Binary Tree
Medium
<p>You are given a <code>root</code>, which is the root of a <strong>special</strong> binary tree with <code>n</code> nodes. The nodes of the special binary tree are numbered from <code>1</code> to <code>n</code>. Suppose the tree has <code>k</code> leaves in the following order: <code>b<sub>1 </sub>&lt;<sub> </sub>b<sub>2 </sub>&lt; ... &lt; b<sub>k</sub></code>.</p> <p>The leaves of this tree have a <strong>special</strong> property! That is, for every leaf <code>b<sub>i</sub></code>, the following conditions hold:</p> <ul> <li>The right child of <code>b<sub>i</sub></code> is <code>b<sub>i + 1</sub></code> if <code>i &lt; k</code>, and <code>b<sub>1</sub></code> otherwise.</li> <li>The left child of <code>b<sub>i</sub></code> is <code>b<sub>i - 1</sub></code> if <code>i &gt; 1</code>, and <code>b<sub>k</sub></code> otherwise.</li> </ul> <p>Return<em> the height of the given tree.</em></p> <p><strong>Note:</strong> The height of a binary tree is the length of the <strong>longest path</strong> from the root to any other node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> 2 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 200px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 <strong>Explanation: </strong>The given tree is shown in the following picture. There is only one leaf, so it doesn&#39;t have any left or right child. We can see that the graph has a height of 1. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 95px; height: 122px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,null,5,6] <strong>Output:</strong> 3 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 280px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of nodes in the tree</code></li> <li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= node.val &lt;= n</code></li> <li>The input is generated such that each <code>node.val</code> is unique.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int heightOfTree(TreeNode root) { dfs(root, 0); return ans; } private void dfs(TreeNode root, int d) { ans = Math.max(ans, d++); if (root.left != null && root.left.right != root) { dfs(root.left, d); } if (root.right != null && root.right.left != root) { dfs(root.right, d); } } }
2,773
Height of Special Binary Tree
Medium
<p>You are given a <code>root</code>, which is the root of a <strong>special</strong> binary tree with <code>n</code> nodes. The nodes of the special binary tree are numbered from <code>1</code> to <code>n</code>. Suppose the tree has <code>k</code> leaves in the following order: <code>b<sub>1 </sub>&lt;<sub> </sub>b<sub>2 </sub>&lt; ... &lt; b<sub>k</sub></code>.</p> <p>The leaves of this tree have a <strong>special</strong> property! That is, for every leaf <code>b<sub>i</sub></code>, the following conditions hold:</p> <ul> <li>The right child of <code>b<sub>i</sub></code> is <code>b<sub>i + 1</sub></code> if <code>i &lt; k</code>, and <code>b<sub>1</sub></code> otherwise.</li> <li>The left child of <code>b<sub>i</sub></code> is <code>b<sub>i - 1</sub></code> if <code>i &gt; 1</code>, and <code>b<sub>k</sub></code> otherwise.</li> </ul> <p>Return<em> the height of the given tree.</em></p> <p><strong>Note:</strong> The height of a binary tree is the length of the <strong>longest path</strong> from the root to any other node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> 2 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 200px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 <strong>Explanation: </strong>The given tree is shown in the following picture. There is only one leaf, so it doesn&#39;t have any left or right child. We can see that the graph has a height of 1. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 95px; height: 122px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,null,5,6] <strong>Output:</strong> 3 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 280px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of nodes in the tree</code></li> <li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= node.val &lt;= n</code></li> <li>The input is generated such that each <code>node.val</code> is unique.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def heightOfTree(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode], d: int): nonlocal ans ans = max(ans, d) if root.left and root.left.right != root: dfs(root.left, d + 1) if root.right and root.right.left != root: dfs(root.right, d + 1) ans = 0 dfs(root, 0) return ans
2,773
Height of Special Binary Tree
Medium
<p>You are given a <code>root</code>, which is the root of a <strong>special</strong> binary tree with <code>n</code> nodes. The nodes of the special binary tree are numbered from <code>1</code> to <code>n</code>. Suppose the tree has <code>k</code> leaves in the following order: <code>b<sub>1 </sub>&lt;<sub> </sub>b<sub>2 </sub>&lt; ... &lt; b<sub>k</sub></code>.</p> <p>The leaves of this tree have a <strong>special</strong> property! That is, for every leaf <code>b<sub>i</sub></code>, the following conditions hold:</p> <ul> <li>The right child of <code>b<sub>i</sub></code> is <code>b<sub>i + 1</sub></code> if <code>i &lt; k</code>, and <code>b<sub>1</sub></code> otherwise.</li> <li>The left child of <code>b<sub>i</sub></code> is <code>b<sub>i - 1</sub></code> if <code>i &gt; 1</code>, and <code>b<sub>k</sub></code> otherwise.</li> </ul> <p>Return<em> the height of the given tree.</em></p> <p><strong>Note:</strong> The height of a binary tree is the length of the <strong>longest path</strong> from the root to any other node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> 2 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 200px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,2] <strong>Output:</strong> 1 <strong>Explanation: </strong>The given tree is shown in the following picture. There is only one leaf, so it doesn&#39;t have any left or right child. We can see that the graph has a height of 1. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 95px; height: 122px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,null,5,6] <strong>Output:</strong> 3 <strong>Explanation: </strong>The given tree is shown in the following picture. Each leaf&#39;s left child is the leaf to its left (shown with the blue edges). Each leaf&#39;s right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2773.Height%20of%20Special%20Binary%20Tree/images/3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 200px; height: 280px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of nodes in the tree</code></li> <li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= node.val &lt;= n</code></li> <li>The input is generated such that each <code>node.val</code> is unique.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function heightOfTree(root: TreeNode | null): number { let ans = 0; const dfs = (root: TreeNode | null, d: number) => { ans = Math.max(ans, d++); if (root.left && root.left.right !== root) { dfs(root.left, d); } if (root.right && root.right.left !== root) { dfs(root.right, d); } }; dfs(root, 0); return ans; }
2,774
Array Upper Bound
Easy
<p>Write code that enhances all arrays such that you can call the <code>upperBound()</code>&nbsp;method on any array and it will return the last index of a given <code>target</code> number.&nbsp;<code>nums</code>&nbsp;is a sorted ascending array of numbers that may contain duplicates. If the <code>target</code> number is not found in the array, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> Last index of target value is 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,5], target = 2 <strong>Output:</strong> -1 <strong>Explanation:</strong> Because there is no digit 2 in the array, return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,6,6,6,6,7], target = 6 <strong>Output:</strong> 5 <strong>Explanation:</strong> Last index of target value is 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code><font face="monospace">-10<sup>4</sup>&nbsp;&lt;= nums[i], target &lt;= 10<sup>4</sup></font></code></li> <li><code>nums</code>&nbsp;is sorted in ascending order.</li> </ul> <p>&nbsp;</p> <strong>Follow up: </strong>Can you write an algorithm with&nbsp;O(log n)&nbsp;runtime complexity?
JavaScript
TypeScript
declare global { interface Array<T> { upperBound(target: number): number; } } Array.prototype.upperBound = function (target: number) { let left = 0; let right = this.length; while (left < right) { const mid = (left + right) >> 1; if (this[mid] > target) { right = mid; } else { left = mid + 1; } } return left > 0 && this[left - 1] == target ? left - 1 : -1; }; // [3,4,5].upperBound(5); // 2 // [1,4,5].upperBound(2); // -1 // [3,4,6,6,6,6,7].upperBound(6) // 5
2,775
Undefined to Null
Medium
<p>Given a deeply nested object or array <code>obj</code>, return the object <code>obj</code> with any <code>undefined</code> values replaced by <code>null</code>.</p> <p><code>undefined</code> values are handled differently than <code>null</code> values when objects are converted to a JSON string using <code>JSON.stringify()</code>. This function helps ensure serialized data is free of unexpected errors.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;a&quot;: undefined, &quot;b&quot;: 3} <strong>Output:</strong> {&quot;a&quot;: null, &quot;b&quot;: 3} <strong>Explanation:</strong> The value for obj.a has been changed from undefined to null </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;a&quot;: undefined, &quot;b&quot;: [&quot;a&quot;, undefined]} <strong>Output:</strong> {&quot;a&quot;: null,&quot;b&quot;: [&quot;a&quot;, null]} <strong>Explanation:</strong> The values for obj.a and obj.b[1] have been changed from undefined to null </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a valid JSON object or array</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
function undefinedToNull(obj: Record<any, any>): Record<any, any> { for (const key in obj) { if (typeof obj[key] === 'object') { obj[key] = undefinedToNull(obj[key]); } if (obj[key] === undefined) { obj[key] = null; } } return obj; } /** * undefinedToNull({"a": undefined, "b": 3}) // {"a": null, "b": 3} * undefinedToNull([undefined, undefined]) // [null, null] */
2,776
Convert Callback Based Function to Promise Based Function
Medium
<p>Write a function that accepts another function <code>fn</code> and converts the callback-based function&nbsp;into a promise-based function.&nbsp;</p> <p>The function <code>fn</code> takes a callback as its first argument, along with any additional arguments <code>args</code>&nbsp;passed as separate inputs.</p> <p>The&nbsp;<code>promisify</code>&nbsp;function returns a new function that should return a promise. The promise should resolve with the argument passed as the first parameter of the callback when the callback is invoked without error, and reject with the error when the callback is called with an error as the second argument.</p> <p>The following is an example of a function that could be passed into&nbsp;<code>promisify</code>.</p> <pre> function sum(callback, a, b) { if (a &lt; 0 || b &lt; 0) { &nbsp; const err = Error(&#39;a and b must be positive&#39;); callback(undefined, err); &nbsp; } else { callback(a + b); &nbsp; } } </pre> <p>This is the equivalent code based on promises:</p> <pre> async function sum(a, b) { if (a &lt; 0 || b &lt; 0) { throw Error(&#39;a and b must be positive&#39;); &nbsp; } else { return a + b; &nbsp; } } </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (callback, a, b, c) =&gt; { callback(a * b * c); } args = [1, 2, 3] <strong>Output:</strong> {&quot;resolved&quot;: 6} <strong>Explanation:</strong> const asyncFunc = promisify(fn); asyncFunc(1, 2, 3).then(console.log); // 6 fn is called with a callback as the first argument and args as the rest. The promise based version of fn resolves a value of 6 when called with (1, 2, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (callback, a, b, c) =&gt; { callback(a * b * c, &quot;Promise Rejected&quot;); } args = [4, 5, 6] <strong>Output:</strong> {&quot;rejected&quot;: &quot;Promise Rejected&quot;} <strong>Explanation:</strong> const asyncFunc = promisify(fn); asyncFunc(4, 5, 6).catch(console.log); // &quot;Promise Rejected&quot; fn is called with a callback as the first argument and args as the rest. As the second argument, the callback accepts an error message, so when fn is called, the promise is rejected with a error message provided in the callback. Note that it did not matter what was passed as the first argument into the callback. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= args.length &lt;= 100</code></li> <li><code>0 &lt;= args[i] &lt;= 10<sup>4</sup></code></li> </ul>
JavaScript
TypeScript
type CallbackFn = (next: (data: number, error: string) => void, ...args: number[]) => void; type Promisified = (...args: number[]) => Promise<number>; function promisify(fn: CallbackFn): Promisified { return async function (...args) { return new Promise((resolve, reject) => { fn( (data, error) => { if (error) { reject(error); } else { resolve(data); } }, ...args, ); }); }; } /** * const asyncFunc = promisify(callback => callback(42)); * asyncFunc().then(console.log); // 42 */
2,777
Date Range Generator
Medium
<p>Given a start date <code>start</code>, an end date <code>end</code>, and a positive integer&nbsp;<code>step</code>, return a generator object that yields&nbsp;dates in the range from <code>start</code> to <code>end</code>&nbsp;inclusive.</p> <p>The value of&nbsp;<code>step</code>&nbsp;indicates the number of days between consecutive yielded values.</p> <p>All yielded dates&nbsp;must be in the string format&nbsp;<code>YYYY-MM-DD</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> start = &quot;2023-04-01&quot;, end = &quot;2023-04-04&quot;, step = 1 <strong>Output:</strong> [&quot;2023-04-01&quot;,&quot;2023-04-02&quot;,&quot;2023-04-03&quot;,&quot;2023-04-04&quot;] <strong>Explanation:</strong> const g = dateRangeGenerator(start, end, step); g.next().value // &#39;2023-04-01&#39; g.next().value // &#39;2023-04-02&#39; g.next().value // &#39;2023-04-03&#39; g.next().value // &#39;2023-04-04&#39;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> start = &quot;2023-04-10&quot;, end = &quot;2023-04-20&quot;, step = 3 <strong>Output:</strong> [&quot;2023-04-10&quot;,&quot;2023-04-13&quot;,&quot;2023-04-16&quot;,&quot;2023-04-19&quot;] <strong>Explanation:</strong> const g = dateRangeGenerator(start, end, step); g.next().value // &#39;2023-04-10&#39; g.next().value // &#39;2023-04-13&#39; g.next().value // &#39;2023-04-16&#39; g.next().value // &#39;2023-04-19&#39;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> start = &quot;2023-04-10&quot;, end = &quot;2023-04-10&quot;, step = 1 <strong>Output:</strong> [&quot;2023-04-10&quot;] <strong>Explanation:</strong> const g = dateRangeGenerator(start, end, step); g.next().value // &#39;2023-04-10&#39; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>new Date(start) &lt;= new Date(end)</code></li> <li><code>start</code> and <code>end</code> dates&nbsp;are in the string format&nbsp;<code>YYYY-MM-DD</code></li> <li><code>0 &lt;= The difference in days between the start date and the end date &lt;= 1500</code></li> <li><code>1 &lt;= step &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
function* dateRangeGenerator(start: string, end: string, step: number): Generator<string> { const startDate = new Date(start); const endDate = new Date(end); let currentDate = startDate; while (currentDate <= endDate) { yield currentDate.toISOString().slice(0, 10); currentDate.setDate(currentDate.getDate() + step); } } /** * const g = dateRangeGenerator('2023-04-01', '2023-04-04', 1); * g.next().value; // '2023-04-01' * g.next().value; // '2023-04-02' * g.next().value; // '2023-04-03' * g.next().value; // '2023-04-04' * g.next().done; // true */
2,778
Sum of Squares of Special Elements
Easy
<p>You are given a <strong>1-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>An element <code>nums[i]</code> of <code>nums</code> is called <strong>special</strong> if <code>i</code> divides <code>n</code>, i.e. <code>n % i == 0</code>.</p> <p>Return <em>the <strong>sum of the squares</strong> of all <strong>special</strong> elements of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 21 <strong>Explanation:</strong> There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,1,19,18,3] <strong>Output:</strong> 63 <strong>Explanation:</strong> There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration
C++
class Solution { public: int sumOfSquares(vector<int>& nums) { int n = nums.size(); int ans = 0; for (int i = 1; i <= n; ++i) { if (n % i == 0) { ans += nums[i - 1] * nums[i - 1]; } } return ans; } };
2,778
Sum of Squares of Special Elements
Easy
<p>You are given a <strong>1-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>An element <code>nums[i]</code> of <code>nums</code> is called <strong>special</strong> if <code>i</code> divides <code>n</code>, i.e. <code>n % i == 0</code>.</p> <p>Return <em>the <strong>sum of the squares</strong> of all <strong>special</strong> elements of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 21 <strong>Explanation:</strong> There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,1,19,18,3] <strong>Output:</strong> 63 <strong>Explanation:</strong> There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration
Go
func sumOfSquares(nums []int) (ans int) { n := len(nums) for i, x := range nums { if n%(i+1) == 0 { ans += x * x } } return }
2,778
Sum of Squares of Special Elements
Easy
<p>You are given a <strong>1-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>An element <code>nums[i]</code> of <code>nums</code> is called <strong>special</strong> if <code>i</code> divides <code>n</code>, i.e. <code>n % i == 0</code>.</p> <p>Return <em>the <strong>sum of the squares</strong> of all <strong>special</strong> elements of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 21 <strong>Explanation:</strong> There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,1,19,18,3] <strong>Output:</strong> 63 <strong>Explanation:</strong> There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration
Java
class Solution { public int sumOfSquares(int[] nums) { int n = nums.length; int ans = 0; for (int i = 1; i <= n; ++i) { if (n % i == 0) { ans += nums[i - 1] * nums[i - 1]; } } return ans; } }
2,778
Sum of Squares of Special Elements
Easy
<p>You are given a <strong>1-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>An element <code>nums[i]</code> of <code>nums</code> is called <strong>special</strong> if <code>i</code> divides <code>n</code>, i.e. <code>n % i == 0</code>.</p> <p>Return <em>the <strong>sum of the squares</strong> of all <strong>special</strong> elements of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 21 <strong>Explanation:</strong> There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,1,19,18,3] <strong>Output:</strong> 63 <strong>Explanation:</strong> There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration
Python
class Solution: def sumOfSquares(self, nums: List[int]) -> int: n = len(nums) return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0)
2,778
Sum of Squares of Special Elements
Easy
<p>You are given a <strong>1-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>An element <code>nums[i]</code> of <code>nums</code> is called <strong>special</strong> if <code>i</code> divides <code>n</code>, i.e. <code>n % i == 0</code>.</p> <p>Return <em>the <strong>sum of the squares</strong> of all <strong>special</strong> elements of </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 21 <strong>Explanation:</strong> There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,1,19,18,3] <strong>Output:</strong> 63 <strong>Explanation:</strong> There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration
TypeScript
function sumOfSquares(nums: number[]): number { const n = nums.length; let ans = 0; for (let i = 0; i < n; ++i) { if (n % (i + 1) === 0) { ans += nums[i] * nums[i]; } } return ans; }
2,779
Maximum Beauty of an Array After Applying Operation
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>.</p> <p>In one operation, you can do the following:</p> <ul> <li>Choose an index <code>i</code> that <strong>hasn&#39;t been chosen before</strong> from the range <code>[0, nums.length - 1]</code>.</li> <li>Replace <code>nums[i]</code> with any integer from the range <code>[nums[i] - k, nums[i] + k]</code>.</li> </ul> <p>The <strong>beauty</strong> of the array is the length of the longest subsequence consisting of equal elements.</p> <p>Return <em>the <strong>maximum</strong> possible beauty of the array </em><code>nums</code><em> after applying the operation any number of times.</em></p> <p><strong>Note</strong> that you can apply the operation to each index <strong>only once</strong>.</p> <p>A&nbsp;<strong>subsequence</strong> of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,6,1,2], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example we don&#39;t have to apply any operations. The beauty of the array nums is 4 (whole array). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
C++
class Solution { public: int maximumBeauty(vector<int>& nums, int k) { int m = *max_element(nums.begin(), nums.end()) + k * 2 + 2; vector<int> d(m); for (int x : nums) { d[x]++; d[x + k * 2 + 1]--; } int ans = 0, s = 0; for (int x : d) { s += x; ans = max(ans, s); } return ans; } };
2,779
Maximum Beauty of an Array After Applying Operation
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>.</p> <p>In one operation, you can do the following:</p> <ul> <li>Choose an index <code>i</code> that <strong>hasn&#39;t been chosen before</strong> from the range <code>[0, nums.length - 1]</code>.</li> <li>Replace <code>nums[i]</code> with any integer from the range <code>[nums[i] - k, nums[i] + k]</code>.</li> </ul> <p>The <strong>beauty</strong> of the array is the length of the longest subsequence consisting of equal elements.</p> <p>Return <em>the <strong>maximum</strong> possible beauty of the array </em><code>nums</code><em> after applying the operation any number of times.</em></p> <p><strong>Note</strong> that you can apply the operation to each index <strong>only once</strong>.</p> <p>A&nbsp;<strong>subsequence</strong> of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,6,1,2], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example we don&#39;t have to apply any operations. The beauty of the array nums is 4 (whole array). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Go
func maximumBeauty(nums []int, k int) (ans int) { m := slices.Max(nums) m += k*2 + 2 d := make([]int, m) for _, x := range nums { d[x]++ d[x+k*2+1]-- } s := 0 for _, x := range d { s += x if ans < s { ans = s } } return }
2,779
Maximum Beauty of an Array After Applying Operation
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>.</p> <p>In one operation, you can do the following:</p> <ul> <li>Choose an index <code>i</code> that <strong>hasn&#39;t been chosen before</strong> from the range <code>[0, nums.length - 1]</code>.</li> <li>Replace <code>nums[i]</code> with any integer from the range <code>[nums[i] - k, nums[i] + k]</code>.</li> </ul> <p>The <strong>beauty</strong> of the array is the length of the longest subsequence consisting of equal elements.</p> <p>Return <em>the <strong>maximum</strong> possible beauty of the array </em><code>nums</code><em> after applying the operation any number of times.</em></p> <p><strong>Note</strong> that you can apply the operation to each index <strong>only once</strong>.</p> <p>A&nbsp;<strong>subsequence</strong> of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,6,1,2], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example we don&#39;t have to apply any operations. The beauty of the array nums is 4 (whole array). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Java
class Solution { public int maximumBeauty(int[] nums, int k) { int m = Arrays.stream(nums).max().getAsInt() + k * 2 + 2; int[] d = new int[m]; for (int x : nums) { d[x]++; d[x + k * 2 + 1]--; } int ans = 0, s = 0; for (int x : d) { s += x; ans = Math.max(ans, s); } return ans; } }
2,779
Maximum Beauty of an Array After Applying Operation
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>.</p> <p>In one operation, you can do the following:</p> <ul> <li>Choose an index <code>i</code> that <strong>hasn&#39;t been chosen before</strong> from the range <code>[0, nums.length - 1]</code>.</li> <li>Replace <code>nums[i]</code> with any integer from the range <code>[nums[i] - k, nums[i] + k]</code>.</li> </ul> <p>The <strong>beauty</strong> of the array is the length of the longest subsequence consisting of equal elements.</p> <p>Return <em>the <strong>maximum</strong> possible beauty of the array </em><code>nums</code><em> after applying the operation any number of times.</em></p> <p><strong>Note</strong> that you can apply the operation to each index <strong>only once</strong>.</p> <p>A&nbsp;<strong>subsequence</strong> of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,6,1,2], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example we don&#39;t have to apply any operations. The beauty of the array nums is 4 (whole array). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
Python
class Solution: def maximumBeauty(self, nums: List[int], k: int) -> int: m = max(nums) + k * 2 + 2 d = [0] * m for x in nums: d[x] += 1 d[x + k * 2 + 1] -= 1 return max(accumulate(d))
2,779
Maximum Beauty of an Array After Applying Operation
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>.</p> <p>In one operation, you can do the following:</p> <ul> <li>Choose an index <code>i</code> that <strong>hasn&#39;t been chosen before</strong> from the range <code>[0, nums.length - 1]</code>.</li> <li>Replace <code>nums[i]</code> with any integer from the range <code>[nums[i] - k, nums[i] + k]</code>.</li> </ul> <p>The <strong>beauty</strong> of the array is the length of the longest subsequence consisting of equal elements.</p> <p>Return <em>the <strong>maximum</strong> possible beauty of the array </em><code>nums</code><em> after applying the operation any number of times.</em></p> <p><strong>Note</strong> that you can apply the operation to each index <strong>only once</strong>.</p> <p>A&nbsp;<strong>subsequence</strong> of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,6,1,2], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we apply the following operations: - Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2]. - Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4]. After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3). It can be proven that 3 is the maximum possible length we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example we don&#39;t have to apply any operations. The beauty of the array nums is 4 (whole array). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Sorting; Sliding Window
TypeScript
function maximumBeauty(nums: number[], k: number): number { const m = Math.max(...nums) + k * 2 + 2; const d: number[] = Array(m).fill(0); for (const x of nums) { d[x]++; d[x + k * 2 + 1]--; } let ans = 0; let s = 0; for (const x of d) { s += x; ans = Math.max(ans, s); } return ans; }
2,780
Minimum Index of a Valid Split
Medium
<p>An element <code>x</code> of an integer array <code>arr</code> of length <code>m</code> is <strong>dominant</strong> if <strong>more than half</strong> the elements of <code>arr</code> have a value of <code>x</code>.</p> <p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> with one <strong>dominant</strong> element.</p> <p>You can split <code>nums</code> at an index <code>i</code> into two arrays <code>nums[0, ..., i]</code> and <code>nums[i + 1, ..., n - 1]</code>, but the split is only <strong>valid</strong> if:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code></li> <li><code>nums[0, ..., i]</code>, and <code>nums[i + 1, ..., n - 1]</code> have the same dominant element.</li> </ul> <p>Here, <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code>, both ends being inclusive. Particularly, if <code>j &lt; i</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>Return <em>the <strong>minimum</strong> index of a <strong>valid split</strong></em>. If no valid split exists, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can split the array at index 2 to obtain arrays [1,2,2] and [2]. In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 &gt; 3. In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 &gt; 1. Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. It can be shown that index 2 is the minimum index of a valid split. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,1,1,1,7,1,2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. It can be shown that index 4 is the minimum index of a valid split.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,7,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that there is no valid split. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> has exactly one dominant element.</li> </ul>
Array; Hash Table; Sorting
C++
class Solution { public: int minimumIndex(vector<int>& nums) { int x = 0, cnt = 0; unordered_map<int, int> freq; for (int v : nums) { ++freq[v]; if (freq[v] > cnt) { cnt = freq[v]; x = v; } } int cur = 0; for (int i = 1; i <= nums.size(); ++i) { if (nums[i - 1] == x) { ++cur; if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { return i - 1; } } } return -1; } };
2,780
Minimum Index of a Valid Split
Medium
<p>An element <code>x</code> of an integer array <code>arr</code> of length <code>m</code> is <strong>dominant</strong> if <strong>more than half</strong> the elements of <code>arr</code> have a value of <code>x</code>.</p> <p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> with one <strong>dominant</strong> element.</p> <p>You can split <code>nums</code> at an index <code>i</code> into two arrays <code>nums[0, ..., i]</code> and <code>nums[i + 1, ..., n - 1]</code>, but the split is only <strong>valid</strong> if:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code></li> <li><code>nums[0, ..., i]</code>, and <code>nums[i + 1, ..., n - 1]</code> have the same dominant element.</li> </ul> <p>Here, <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code>, both ends being inclusive. Particularly, if <code>j &lt; i</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>Return <em>the <strong>minimum</strong> index of a <strong>valid split</strong></em>. If no valid split exists, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can split the array at index 2 to obtain arrays [1,2,2] and [2]. In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 &gt; 3. In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 &gt; 1. Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. It can be shown that index 2 is the minimum index of a valid split. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,1,1,1,7,1,2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. It can be shown that index 4 is the minimum index of a valid split.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,7,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that there is no valid split. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> has exactly one dominant element.</li> </ul>
Array; Hash Table; Sorting
Go
func minimumIndex(nums []int) int { x, cnt := 0, 0 freq := map[int]int{} for _, v := range nums { freq[v]++ if freq[v] > cnt { x, cnt = v, freq[v] } } cur := 0 for i, v := range nums { i++ if v == x { cur++ if cur*2 > i && (cnt-cur)*2 > len(nums)-i { return i - 1 } } } return -1 }
2,780
Minimum Index of a Valid Split
Medium
<p>An element <code>x</code> of an integer array <code>arr</code> of length <code>m</code> is <strong>dominant</strong> if <strong>more than half</strong> the elements of <code>arr</code> have a value of <code>x</code>.</p> <p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> with one <strong>dominant</strong> element.</p> <p>You can split <code>nums</code> at an index <code>i</code> into two arrays <code>nums[0, ..., i]</code> and <code>nums[i + 1, ..., n - 1]</code>, but the split is only <strong>valid</strong> if:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code></li> <li><code>nums[0, ..., i]</code>, and <code>nums[i + 1, ..., n - 1]</code> have the same dominant element.</li> </ul> <p>Here, <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code>, both ends being inclusive. Particularly, if <code>j &lt; i</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>Return <em>the <strong>minimum</strong> index of a <strong>valid split</strong></em>. If no valid split exists, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can split the array at index 2 to obtain arrays [1,2,2] and [2]. In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 &gt; 3. In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 &gt; 1. Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. It can be shown that index 2 is the minimum index of a valid split. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,1,1,1,7,1,2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. It can be shown that index 4 is the minimum index of a valid split.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,7,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that there is no valid split. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> has exactly one dominant element.</li> </ul>
Array; Hash Table; Sorting
Java
class Solution { public int minimumIndex(List<Integer> nums) { int x = 0, cnt = 0; Map<Integer, Integer> freq = new HashMap<>(); for (int v : nums) { int t = freq.merge(v, 1, Integer::sum); if (cnt < t) { cnt = t; x = v; } } int cur = 0; for (int i = 1; i <= nums.size(); ++i) { if (nums.get(i - 1) == x) { ++cur; if (cur * 2 > i && (cnt - cur) * 2 > nums.size() - i) { return i - 1; } } } return -1; } }
2,780
Minimum Index of a Valid Split
Medium
<p>An element <code>x</code> of an integer array <code>arr</code> of length <code>m</code> is <strong>dominant</strong> if <strong>more than half</strong> the elements of <code>arr</code> have a value of <code>x</code>.</p> <p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> with one <strong>dominant</strong> element.</p> <p>You can split <code>nums</code> at an index <code>i</code> into two arrays <code>nums[0, ..., i]</code> and <code>nums[i + 1, ..., n - 1]</code>, but the split is only <strong>valid</strong> if:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code></li> <li><code>nums[0, ..., i]</code>, and <code>nums[i + 1, ..., n - 1]</code> have the same dominant element.</li> </ul> <p>Here, <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code>, both ends being inclusive. Particularly, if <code>j &lt; i</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>Return <em>the <strong>minimum</strong> index of a <strong>valid split</strong></em>. If no valid split exists, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can split the array at index 2 to obtain arrays [1,2,2] and [2]. In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 &gt; 3. In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 &gt; 1. Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. It can be shown that index 2 is the minimum index of a valid split. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,1,1,1,7,1,2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. It can be shown that index 4 is the minimum index of a valid split.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,7,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that there is no valid split. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> has exactly one dominant element.</li> </ul>
Array; Hash Table; Sorting
Python
class Solution: def minimumIndex(self, nums: List[int]) -> int: x, cnt = Counter(nums).most_common(1)[0] cur = 0 for i, v in enumerate(nums, 1): if v == x: cur += 1 if cur * 2 > i and (cnt - cur) * 2 > len(nums) - i: return i - 1 return -1
2,780
Minimum Index of a Valid Split
Medium
<p>An element <code>x</code> of an integer array <code>arr</code> of length <code>m</code> is <strong>dominant</strong> if <strong>more than half</strong> the elements of <code>arr</code> have a value of <code>x</code>.</p> <p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> with one <strong>dominant</strong> element.</p> <p>You can split <code>nums</code> at an index <code>i</code> into two arrays <code>nums[0, ..., i]</code> and <code>nums[i + 1, ..., n - 1]</code>, but the split is only <strong>valid</strong> if:</p> <ul> <li><code>0 &lt;= i &lt; n - 1</code></li> <li><code>nums[0, ..., i]</code>, and <code>nums[i + 1, ..., n - 1]</code> have the same dominant element.</li> </ul> <p>Here, <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code>, both ends being inclusive. Particularly, if <code>j &lt; i</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>Return <em>the <strong>minimum</strong> index of a <strong>valid split</strong></em>. If no valid split exists, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can split the array at index 2 to obtain arrays [1,2,2] and [2]. In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 &gt; 3. In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 &gt; 1. Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. It can be shown that index 2 is the minimum index of a valid split. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,1,1,1,7,1,2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1]. In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 &gt; 5. Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split. It can be shown that index 4 is the minimum index of a valid split.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,7,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that there is no valid split. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> has exactly one dominant element.</li> </ul>
Array; Hash Table; Sorting
TypeScript
function minimumIndex(nums: number[]): number { let [x, cnt] = [0, 0]; const freq: Map<number, number> = new Map(); for (const v of nums) { freq.set(v, (freq.get(v) ?? 0) + 1); if (freq.get(v)! > cnt) { [x, cnt] = [v, freq.get(v)!]; } } let cur = 0; for (let i = 1; i <= nums.length; ++i) { if (nums[i - 1] === x) { ++cur; if (cur * 2 > i && (cnt - cur) * 2 > nums.length - i) { return i - 1; } } } return -1; }
2,781
Length of the Longest Valid Substring
Hard
<p>You are given a string <code>word</code> and an array of strings <code>forbidden</code>.</p> <p>A string is called <strong>valid</strong> if none of its substrings are present in <code>forbidden</code>.</p> <p>Return <em>the length of the <strong>longest valid substring</strong> of the string </em><code>word</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string, possibly empty.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;cbaaaabc&quot;, forbidden = [&quot;aaa&quot;,&quot;cb&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;ba&quot;, &quot;aa&quot;, &quot;bc&quot;, &quot;baa&quot;, &quot;aab&quot;, &quot;ab&quot;, &quot;abc&quot; and &quot;aabc&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;aaa&quot; or &quot;cb&quot; as a substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;leetcode&quot;, forbidden = [&quot;de&quot;,&quot;le&quot;,&quot;e&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;l&quot;, &quot;t&quot;, &quot;c&quot;, &quot;o&quot;, &quot;d&quot;, &quot;tc&quot;, &quot;co&quot;, &quot;od&quot;, &quot;tco&quot;, &quot;cod&quot;, and &quot;tcod&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;de&quot;, &quot;le&quot;, or &quot;e&quot; as a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= forbidden.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= forbidden[i].length &lt;= 10</code></li> <li><code>forbidden[i]</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sliding Window
C++
class Solution { public: int longestValidSubstring(string word, vector<string>& forbidden) { unordered_set<string> s(forbidden.begin(), forbidden.end()); int ans = 0, n = word.size(); for (int i = 0, j = 0; j < n; ++j) { for (int k = j; k > max(j - 10, i - 1); --k) { if (s.count(word.substr(k, j - k + 1))) { i = k + 1; break; } } ans = max(ans, j - i + 1); } return ans; } };
2,781
Length of the Longest Valid Substring
Hard
<p>You are given a string <code>word</code> and an array of strings <code>forbidden</code>.</p> <p>A string is called <strong>valid</strong> if none of its substrings are present in <code>forbidden</code>.</p> <p>Return <em>the length of the <strong>longest valid substring</strong> of the string </em><code>word</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string, possibly empty.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;cbaaaabc&quot;, forbidden = [&quot;aaa&quot;,&quot;cb&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;ba&quot;, &quot;aa&quot;, &quot;bc&quot;, &quot;baa&quot;, &quot;aab&quot;, &quot;ab&quot;, &quot;abc&quot; and &quot;aabc&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;aaa&quot; or &quot;cb&quot; as a substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;leetcode&quot;, forbidden = [&quot;de&quot;,&quot;le&quot;,&quot;e&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;l&quot;, &quot;t&quot;, &quot;c&quot;, &quot;o&quot;, &quot;d&quot;, &quot;tc&quot;, &quot;co&quot;, &quot;od&quot;, &quot;tco&quot;, &quot;cod&quot;, and &quot;tcod&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;de&quot;, &quot;le&quot;, or &quot;e&quot; as a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= forbidden.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= forbidden[i].length &lt;= 10</code></li> <li><code>forbidden[i]</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sliding Window
Go
func longestValidSubstring(word string, forbidden []string) (ans int) { s := map[string]bool{} for _, x := range forbidden { s[x] = true } n := len(word) for i, j := 0, 0; j < n; j++ { for k := j; k > max(j-10, i-1); k-- { if s[word[k:j+1]] { i = k + 1 break } } ans = max(ans, j-i+1) } return }
2,781
Length of the Longest Valid Substring
Hard
<p>You are given a string <code>word</code> and an array of strings <code>forbidden</code>.</p> <p>A string is called <strong>valid</strong> if none of its substrings are present in <code>forbidden</code>.</p> <p>Return <em>the length of the <strong>longest valid substring</strong> of the string </em><code>word</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string, possibly empty.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;cbaaaabc&quot;, forbidden = [&quot;aaa&quot;,&quot;cb&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;ba&quot;, &quot;aa&quot;, &quot;bc&quot;, &quot;baa&quot;, &quot;aab&quot;, &quot;ab&quot;, &quot;abc&quot; and &quot;aabc&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;aaa&quot; or &quot;cb&quot; as a substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;leetcode&quot;, forbidden = [&quot;de&quot;,&quot;le&quot;,&quot;e&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;l&quot;, &quot;t&quot;, &quot;c&quot;, &quot;o&quot;, &quot;d&quot;, &quot;tc&quot;, &quot;co&quot;, &quot;od&quot;, &quot;tco&quot;, &quot;cod&quot;, and &quot;tcod&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;de&quot;, &quot;le&quot;, or &quot;e&quot; as a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= forbidden.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= forbidden[i].length &lt;= 10</code></li> <li><code>forbidden[i]</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sliding Window
Java
class Solution { public int longestValidSubstring(String word, List<String> forbidden) { var s = new HashSet<>(forbidden); int ans = 0, n = word.length(); for (int i = 0, j = 0; j < n; ++j) { for (int k = j; k > Math.max(j - 10, i - 1); --k) { if (s.contains(word.substring(k, j + 1))) { i = k + 1; break; } } ans = Math.max(ans, j - i + 1); } return ans; } }
2,781
Length of the Longest Valid Substring
Hard
<p>You are given a string <code>word</code> and an array of strings <code>forbidden</code>.</p> <p>A string is called <strong>valid</strong> if none of its substrings are present in <code>forbidden</code>.</p> <p>Return <em>the length of the <strong>longest valid substring</strong> of the string </em><code>word</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string, possibly empty.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;cbaaaabc&quot;, forbidden = [&quot;aaa&quot;,&quot;cb&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;ba&quot;, &quot;aa&quot;, &quot;bc&quot;, &quot;baa&quot;, &quot;aab&quot;, &quot;ab&quot;, &quot;abc&quot; and &quot;aabc&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;aaa&quot; or &quot;cb&quot; as a substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;leetcode&quot;, forbidden = [&quot;de&quot;,&quot;le&quot;,&quot;e&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;l&quot;, &quot;t&quot;, &quot;c&quot;, &quot;o&quot;, &quot;d&quot;, &quot;tc&quot;, &quot;co&quot;, &quot;od&quot;, &quot;tco&quot;, &quot;cod&quot;, and &quot;tcod&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;de&quot;, &quot;le&quot;, or &quot;e&quot; as a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= forbidden.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= forbidden[i].length &lt;= 10</code></li> <li><code>forbidden[i]</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sliding Window
Python
class Solution: def longestValidSubstring(self, word: str, forbidden: List[str]) -> int: s = set(forbidden) ans = i = 0 for j in range(len(word)): for k in range(j, max(j - 10, i - 1), -1): if word[k : j + 1] in s: i = k + 1 break ans = max(ans, j - i + 1) return ans
2,781
Length of the Longest Valid Substring
Hard
<p>You are given a string <code>word</code> and an array of strings <code>forbidden</code>.</p> <p>A string is called <strong>valid</strong> if none of its substrings are present in <code>forbidden</code>.</p> <p>Return <em>the length of the <strong>longest valid substring</strong> of the string </em><code>word</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string, possibly empty.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;cbaaaabc&quot;, forbidden = [&quot;aaa&quot;,&quot;cb&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;ba&quot;, &quot;aa&quot;, &quot;bc&quot;, &quot;baa&quot;, &quot;aab&quot;, &quot;ab&quot;, &quot;abc&quot; and &quot;aabc&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;aaa&quot; or &quot;cb&quot; as a substring. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;leetcode&quot;, forbidden = [&quot;de&quot;,&quot;le&quot;,&quot;e&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 11 valid substrings in word: &quot;l&quot;, &quot;t&quot;, &quot;c&quot;, &quot;o&quot;, &quot;d&quot;, &quot;tc&quot;, &quot;co&quot;, &quot;od&quot;, &quot;tco&quot;, &quot;cod&quot;, and &quot;tcod&quot;. The length of the longest valid substring is 4. It can be shown that all other substrings contain either &quot;de&quot;, &quot;le&quot;, or &quot;e&quot; as a substring. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= forbidden.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= forbidden[i].length &lt;= 10</code></li> <li><code>forbidden[i]</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; String; Sliding Window
TypeScript
function longestValidSubstring(word: string, forbidden: string[]): number { const s: Set<string> = new Set(forbidden); const n = word.length; let ans = 0; for (let i = 0, j = 0; j < n; ++j) { for (let k = j; k > Math.max(j - 10, i - 1); --k) { if (s.has(word.substring(k, j + 1))) { i = k + 1; break; } } ans = Math.max(ans, j - i + 1); } return ans; }
2,782
Number of Unique Categories
Medium
<p>You are given an integer <code>n</code> and an object <code>categoryHandler</code> of class <code>CategoryHandler</code>.</p> <p>There are <code>n&nbsp;</code>elements, numbered from <code>0</code> to <code>n - 1</code>. Each element has a category, and your task is to find the number of unique categories.</p> <p>The class <code>CategoryHandler</code> contains the following function, which may help you:</p> <ul> <li><code>boolean haveSameCategory(integer a, integer b)</code>: Returns <code>true</code> if <code>a</code> and <code>b</code> are in the same category and <code>false</code> otherwise. Also, if either <code>a</code> or <code>b</code> is not a valid number (i.e. it&#39;s greater than or equal to <code>n</code>or less than <code>0</code>), it returns <code>false</code>.</li> </ul> <p>Return <em>the number of unique categories.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6, categoryHandler = [1,1,2,2,3,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, categoryHandler = [1,2,3,4,5] <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3, categoryHandler = [1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Union Find; Counting; Interactive
C++
/** * Definition for a category handler. * class CategoryHandler { * public: * CategoryHandler(vector<int> categories); * bool haveSameCategory(int a, int b); * }; */ class Solution { public: int numberOfCategories(int n, CategoryHandler* categoryHandler) { vector<int> p(n); iota(p.begin(), p.end(), 0); function<int(int)> find = [&](int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; }; for (int a = 0; a < n; ++a) { for (int b = a + 1; b < n; ++b) { if (categoryHandler->haveSameCategory(a, b)) { p[find(a)] = find(b); } } } int ans = 0; for (int i = 0; i < n; ++i) { ans += i == p[i]; } return ans; } };
2,782
Number of Unique Categories
Medium
<p>You are given an integer <code>n</code> and an object <code>categoryHandler</code> of class <code>CategoryHandler</code>.</p> <p>There are <code>n&nbsp;</code>elements, numbered from <code>0</code> to <code>n - 1</code>. Each element has a category, and your task is to find the number of unique categories.</p> <p>The class <code>CategoryHandler</code> contains the following function, which may help you:</p> <ul> <li><code>boolean haveSameCategory(integer a, integer b)</code>: Returns <code>true</code> if <code>a</code> and <code>b</code> are in the same category and <code>false</code> otherwise. Also, if either <code>a</code> or <code>b</code> is not a valid number (i.e. it&#39;s greater than or equal to <code>n</code>or less than <code>0</code>), it returns <code>false</code>.</li> </ul> <p>Return <em>the number of unique categories.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6, categoryHandler = [1,1,2,2,3,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, categoryHandler = [1,2,3,4,5] <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3, categoryHandler = [1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Union Find; Counting; Interactive
Go
/** * Definition for a category handler. * type CategoryHandler interface { * HaveSameCategory(int, int) bool * } */ func numberOfCategories(n int, categoryHandler CategoryHandler) (ans int) { p := make([]int, n) for i := range p { p[i] = i } var find func(int) int find = func(x int) int { if p[x] != x { p[x] = find(p[x]) } return p[x] } for a := 0; a < n; a++ { for b := a + 1; b < n; b++ { if categoryHandler.HaveSameCategory(a, b) { p[find(a)] = find(b) } } } for i, x := range p { if i == x { ans++ } } return }
2,782
Number of Unique Categories
Medium
<p>You are given an integer <code>n</code> and an object <code>categoryHandler</code> of class <code>CategoryHandler</code>.</p> <p>There are <code>n&nbsp;</code>elements, numbered from <code>0</code> to <code>n - 1</code>. Each element has a category, and your task is to find the number of unique categories.</p> <p>The class <code>CategoryHandler</code> contains the following function, which may help you:</p> <ul> <li><code>boolean haveSameCategory(integer a, integer b)</code>: Returns <code>true</code> if <code>a</code> and <code>b</code> are in the same category and <code>false</code> otherwise. Also, if either <code>a</code> or <code>b</code> is not a valid number (i.e. it&#39;s greater than or equal to <code>n</code>or less than <code>0</code>), it returns <code>false</code>.</li> </ul> <p>Return <em>the number of unique categories.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6, categoryHandler = [1,1,2,2,3,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, categoryHandler = [1,2,3,4,5] <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3, categoryHandler = [1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Union Find; Counting; Interactive
Java
/** * Definition for a category handler. * class CategoryHandler { * public CategoryHandler(int[] categories); * public boolean haveSameCategory(int a, int b); * }; */ class Solution { private int[] p; public int numberOfCategories(int n, CategoryHandler categoryHandler) { p = new int[n]; for (int i = 0; i < n; ++i) { p[i] = i; } for (int a = 0; a < n; ++a) { for (int b = a + 1; b < n; ++b) { if (categoryHandler.haveSameCategory(a, b)) { p[find(a)] = find(b); } } } int ans = 0; for (int i = 0; i < n; ++i) { if (i == p[i]) { ++ans; } } return ans; } private int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } }
2,782
Number of Unique Categories
Medium
<p>You are given an integer <code>n</code> and an object <code>categoryHandler</code> of class <code>CategoryHandler</code>.</p> <p>There are <code>n&nbsp;</code>elements, numbered from <code>0</code> to <code>n - 1</code>. Each element has a category, and your task is to find the number of unique categories.</p> <p>The class <code>CategoryHandler</code> contains the following function, which may help you:</p> <ul> <li><code>boolean haveSameCategory(integer a, integer b)</code>: Returns <code>true</code> if <code>a</code> and <code>b</code> are in the same category and <code>false</code> otherwise. Also, if either <code>a</code> or <code>b</code> is not a valid number (i.e. it&#39;s greater than or equal to <code>n</code>or less than <code>0</code>), it returns <code>false</code>.</li> </ul> <p>Return <em>the number of unique categories.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 6, categoryHandler = [1,1,2,2,3,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, categoryHandler = [1,2,3,4,5] <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3, categoryHandler = [1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Union Find; Counting; Interactive
Python
# Definition for a category handler. # class CategoryHandler: # def haveSameCategory(self, a: int, b: int) -> bool: # pass class Solution: def numberOfCategories( self, n: int, categoryHandler: Optional['CategoryHandler'] ) -> int: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] p = list(range(n)) for a in range(n): for b in range(a + 1, n): if categoryHandler.haveSameCategory(a, b): p[find(a)] = find(b) return sum(i == x for i, x in enumerate(p))