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,618
Check if Object Instance of Class
Medium
<p>Write a function that checks if a given value&nbsp;is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class&#39;s methods.</p> <p>There are&nbsp;no constraints on the data types that can be passed to the function. For example, the value or the class could be&nbsp;<code>undefined</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; checkIfInstanceOf(new Date(), Date) <strong>Output:</strong> true <strong>Explanation: </strong>The object returned by the Date constructor is, by definition, an instance of Date. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); } <strong>Output:</strong> true <strong>Explanation:</strong> class Animal {}; class Dog extends Animal {}; checkIfInstanceOf(new Dog(), Animal); // true Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; checkIfInstanceOf(Date, Date) <strong>Output:</strong> false <strong>Explanation: </strong>A date constructor cannot logically be an instance of itself. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; checkIfInstanceOf(5, Number) <strong>Output:</strong> true <strong>Explanation: </strong>5 is a Number. Note that the &quot;instanceof&quot; keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example &quot;toFixed()&quot;. </pre>
JavaScript
TypeScript
function checkIfInstanceOf(obj: any, classFunction: any): boolean { if (classFunction === null || classFunction === undefined) { return false; } while (obj !== null && obj !== undefined) { const proto = Object.getPrototypeOf(obj); if (proto === classFunction.prototype) { return true; } obj = proto; } return false; } /** * checkIfInstanceOf(new Date(), Date); // true */
2,619
Array Prototype Last
Easy
<p>Write code that enhances all arrays such that you can call the&nbsp;<code>array.last()</code>&nbsp;method on any array and it will return the last element. If there are no elements in the array, it should return&nbsp;<code>-1</code>.</p> <p>You may assume the array is the output of&nbsp;<code>JSON.parse</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [null, {}, 3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Calling nums.last() should return the last element: 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [] <strong>Output:</strong> -1 <strong>Explanation:</strong> Because there are no elements, return -1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr</code> is a valid JSON array</li> <li><code>0 &lt;= arr.length &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
declare global { interface Array<T> { last(): T | -1; } } Array.prototype.last = function () { return this.length ? this.at(-1) : -1; }; /** * const arr = [1, 2, 3]; * arr.last(); // 3 */ export {};
2,620
Counter
Easy
<p>Given an integer&nbsp;<code>n</code>,&nbsp;return a <code>counter</code> function. This <code>counter</code> function initially returns&nbsp;<code>n</code>&nbsp;and then returns 1 more than the previous value every subsequent time it is called (<code>n</code>, <code>n + 1</code>, <code>n + 2</code>, etc).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 [&quot;call&quot;,&quot;call&quot;,&quot;call&quot;] <strong>Output:</strong> [10,11,12] <strong>Explanation: </strong>counter() = 10 // The first time counter() is called, it returns n. counter() = 11 // Returns 1 more than the previous time. counter() = 12 // Returns 1 more than the previous time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = -2 [&quot;call&quot;,&quot;call&quot;,&quot;call&quot;,&quot;call&quot;,&quot;call&quot;] <strong>Output:</strong> [-2,-1,0,1,2] <strong>Explanation:</strong> counter() initially returns -2. Then increases after each sebsequent call. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000<sup>&nbsp;</sup>&lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= calls.length &lt;= 1000</code></li> <li><code>calls[i] === &quot;call&quot;</code></li> </ul>
JavaScript
TypeScript
function createCounter(n: number): () => number { let i = n; return function () { return i++; }; } /** * const counter = createCounter(10) * counter() // 10 * counter() // 11 * counter() // 12 */
2,621
Sleep
Easy
<p>Given&nbsp;a positive integer <code>millis</code>, write an asynchronous function that sleeps for <code>millis</code>&nbsp;milliseconds. It can resolve any value.</p> <p><strong>Note</strong> that <em>minor</em> deviation from <code>millis</code> in the actual sleep duration is acceptable.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> millis = 100 <strong>Output:</strong> 100 <strong>Explanation:</strong> It should return a promise that resolves after 100ms. let t = Date.now(); sleep(100).then(() =&gt; { console.log(Date.now() - t); // 100 }); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> millis = 200 <strong>Output:</strong> 200 <strong>Explanation:</strong> It should return a promise that resolves after 200ms. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= millis &lt;= 1000</code></li> </ul>
JavaScript
JavaScript
/** * @param {number} millis * @return {Promise} */ async function sleep(millis) { return new Promise(r => setTimeout(r, millis)); } /** * let t = Date.now() * sleep(100).then(() => console.log(Date.now() - t)) // 100 */
2,621
Sleep
Easy
<p>Given&nbsp;a positive integer <code>millis</code>, write an asynchronous function that sleeps for <code>millis</code>&nbsp;milliseconds. It can resolve any value.</p> <p><strong>Note</strong> that <em>minor</em> deviation from <code>millis</code> in the actual sleep duration is acceptable.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> millis = 100 <strong>Output:</strong> 100 <strong>Explanation:</strong> It should return a promise that resolves after 100ms. let t = Date.now(); sleep(100).then(() =&gt; { console.log(Date.now() - t); // 100 }); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> millis = 200 <strong>Output:</strong> 200 <strong>Explanation:</strong> It should return a promise that resolves after 200ms. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= millis &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
async function sleep(millis: number): Promise<void> { return new Promise(r => setTimeout(r, millis)); } /** * let t = Date.now() * sleep(100).then(() => console.log(Date.now() - t)) // 100 */
2,622
Cache With Time Limit
Medium
<p>Write a class that allows getting and setting&nbsp;key-value pairs, however a&nbsp;<strong>time until expiration</strong>&nbsp;is associated with each key.</p> <p>The class has three public methods:</p> <p><code>set(key, value, duration)</code>:&nbsp;accepts an integer&nbsp;<code>key</code>, an&nbsp;integer&nbsp;<code>value</code>, and a <code>duration</code> in milliseconds. Once the&nbsp;<code>duration</code>&nbsp;has elapsed, the key should be inaccessible. The method should return&nbsp;<code>true</code>&nbsp;if the same&nbsp;un-expired key already exists and <code>false</code> otherwise. Both the value and duration should be overwritten if the key already exists.</p> <p><code>get(key)</code>: if an un-expired key exists, it should return the associated value. Otherwise it should return&nbsp;<code>-1</code>.</p> <p><code>count()</code>: returns the count of un-expired keys.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;TimeLimitedCache&quot;, &quot;set&quot;, &quot;get&quot;, &quot;count&quot;, &quot;get&quot;] values = [[], [1, 42, 100], [1], [], [1]] timeDelays = [0, 0, 50, 50, 150] <strong>Output:</strong> [null, false, 42, 1, -1] <strong>Explanation:</strong> At t=0, the cache is constructed. At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn&#39;t exist so false is returned. At t=50, key=1 is requested and the value of 42 is returned. At t=50, count() is called and there is one active key in the cache. At t=100, key=1 expires. At t=150, get(1) is called but -1 is returned because the cache is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;TimeLimitedCache&quot;, &quot;set&quot;, &quot;set&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;, &quot;count&quot;] values = [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []] timeDelays = [0, 0, 40, 50, 120, 200, 250] <strong>Output:</strong> [null, false, true, 50, 50, -1, 0] <strong>Explanation:</strong> At t=0, the cache is constructed. At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn&#39;t exist so false is returned. At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten. At t=50, get(1) is called which returned 50. At t=120, get(1) is called which returned 50. At t=140, key=1 expires. At t=200, get(1) is called but the cache is empty so -1 is returned. At t=250, count() returns 0 because the cache is empty. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= key, value &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= duration &lt;= 1000</code></li> <li><code>1 &lt;= actions.length &lt;= 100</code></li> <li><code>actions.length === values.length</code></li> <li><code>actions.length === timeDelays.length</code></li> <li><code>0 &lt;= timeDelays[i] &lt;= 1450</code></li> <li><code>actions[i]</code>&nbsp;is one of &quot;TimeLimitedCache&quot;, &quot;set&quot;, &quot;get&quot; and&nbsp;&quot;count&quot;</li> <li>First action is always &quot;TimeLimitedCache&quot; and must be executed immediately, with a 0-millisecond delay</li> </ul>
JavaScript
TypeScript
class TimeLimitedCache { #cache: Map<number, [value: number, expire: number]> = new Map(); set(key: number, value: number, duration: number): boolean { const isExist = this.#cache.has(key); if (!this.#isExpired(key)) { this.#cache.set(key, [value, Date.now() + duration]); } return isExist; } get(key: number): number { if (this.#isExpired(key)) return -1; const res = this.#cache.get(key)?.[0] ?? -1; return res; } count(): number { const xs = Array.from(this.#cache).filter(([key]) => !this.#isExpired(key)); return xs.length; } #isExpired = (key: number) => this.#cache.has(key) && (this.#cache.get(key)?.[1] ?? Number.NEGATIVE_INFINITY) < Date.now(); } /** * Your TimeLimitedCache object will be instantiated and called as such: * var obj = new TimeLimitedCache() * obj.set(1, 42, 1000); // false * obj.get(1) // 42 * obj.count() // 1 */
2,623
Memoize
Medium
<p>Given a function <code>fn</code>, return a&nbsp;<strong>memoized</strong>&nbsp;version of that function.</p> <p>A&nbsp;<strong>memoized&nbsp;</strong>function is a function that will never be called twice with&nbsp;the same inputs. Instead it will return&nbsp;a cached value.</p> <p>You can assume there are&nbsp;<strong>3&nbsp;</strong>possible input functions:&nbsp;<code>sum</code><strong>, </strong><code>fib</code><strong>,&nbsp;</strong>and&nbsp;<code>factorial</code><strong>.</strong></p> <ul> <li><code>sum</code><strong>&nbsp;</strong>accepts two integers&nbsp;<code>a</code> and <code>b</code> and returns <code>a + b</code>.&nbsp;Assume that if a value has already been cached for the arguments <code>(b, a)</code> where <code>a != b</code>, it cannot be used for the arguments <code>(a, b)</code>. For example, if the arguments are <code>(3, 2)</code> and <code>(2, 3)</code>, two separate calls should be made.</li> <li><code>fib</code><strong>&nbsp;</strong>accepts a&nbsp;single integer&nbsp;<code>n</code> and&nbsp;returns&nbsp;<code>1</code> if <font face="monospace"><code>n &lt;= 1</code> </font>or<font face="monospace">&nbsp;<code>fib(n - 1) + fib(n - 2)</code>&nbsp;</font>otherwise.</li> <li><code>factorial</code>&nbsp;accepts a single integer&nbsp;<code>n</code> and returns <code>1</code>&nbsp;if&nbsp;<code>n &lt;= 1</code>&nbsp;or&nbsp;<code>factorial(n - 1) * n</code>&nbsp;otherwise.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fnName = &quot;sum&quot; actions = [&quot;call&quot;,&quot;call&quot;,&quot;getCallCount&quot;,&quot;call&quot;,&quot;getCallCount&quot;] values = [[2,2],[2,2],[],[1,2],[]] <strong>Output:</strong> [4,4,1,3,2] <strong>Explanation:</strong> const sum = (a, b) =&gt; a + b; const memoizedSum = memoize(sum); memoizedSum(2, 2); // &quot;call&quot; - returns 4. sum() was called as (2, 2) was not seen before. memoizedSum(2, 2); // &quot;call&quot; - returns 4. However sum() was not called because the same inputs were seen before. // &quot;getCallCount&quot; - total call count: 1 memoizedSum(1, 2); // &quot;call&quot; - returns 3. sum() was called as (1, 2) was not seen before. // &quot;getCallCount&quot; - total call count: 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input: </strong>fnName = &quot;factorial&quot; actions = [&quot;call&quot;,&quot;call&quot;,&quot;call&quot;,&quot;getCallCount&quot;,&quot;call&quot;,&quot;getCallCount&quot;] values = [[2],[3],[2],[],[3],[]] <strong>Output:</strong> [2,6,2,2,6,2] <strong>Explanation:</strong> const factorial = (n) =&gt; (n &lt;= 1) ? 1 : (n * factorial(n - 1)); const memoFactorial = memoize(factorial); memoFactorial(2); // &quot;call&quot; - returns 2. memoFactorial(3); // &quot;call&quot; - returns 6. memoFactorial(2); // &quot;call&quot; - returns 2. However factorial was not called because 2 was seen before. // &quot;getCallCount&quot; - total call count: 2 memoFactorial(3); // &quot;call&quot; - returns 6. However factorial was not called because 3 was seen before. // &quot;getCallCount&quot; - total call count: 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input: </strong>fnName = &quot;fib&quot; actions = [&quot;call&quot;,&quot;getCallCount&quot;] values = [[5],[]] <strong>Output:</strong> [8,1] <strong>Explanation: </strong>fib(5) = 8 // &quot;call&quot; // &quot;getCallCount&quot; - total call count: 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= a, b &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= actions.length &lt;= 10<sup>5</sup></code></li> <li><code>actions.length === values.length</code></li> <li><code>actions[i]</code> is one of &quot;call&quot; and &quot;getCallCount&quot;</li> <li><code>fnName</code> is one of &quot;sum&quot;, &quot;factorial&quot; and&nbsp;&quot;fib&quot;</li> </ul>
JavaScript
TypeScript
type Fn = (...params: any) => any; function memoize(fn: Fn): Fn { const cache: Record<any, any> = {}; return function (...args) { if (args in cache) { return cache[args]; } const result = fn(...args); cache[args] = result; return result; }; } /** * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; * return a + b; * }) * memoizedFn(2, 3) // 5 * memoizedFn(2, 3) // 5 * console.log(callCount) // 1 */
2,624
Snail Traversal
Medium
<p>Write code that enhances all arrays such that you can call the <code>snail(rowsCount, colsCount)</code> method that transforms the 1D&nbsp;array into&nbsp;a 2D array organised in&nbsp;the pattern known as <strong>snail traversal order</strong>. Invalid input values should output an empty array. If&nbsp;<code>rowsCount * colsCount !== nums.length</code>,&nbsp;the input is considered invalid.</p> <p><strong>Snail traversal order</strong><em>&nbsp;</em>starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array&nbsp;<code>[19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]</code> with <code>rowsCount = 5</code> and <code>colsCount = 4</code>,&nbsp;the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array.</p> <p>&nbsp;</p> <p><img alt="Traversal Diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2624.Snail%20Traversal/images/screen-shot-2023-04-10-at-100006-pm.png" style="width: 275px; height: 343px;" /></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15] rowsCount = 5 colsCount = 4 <strong>Output:</strong> [ [19,17,16,15], &nbsp;[10,1,14,4], &nbsp;[3,2,12,20], &nbsp;[7,5,18,11], &nbsp;[9,8,6,13] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] rowsCount = 1 colsCount = 4 <strong>Output:</strong> [[1, 2, 3, 4]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3] rowsCount = 2 colsCount = 2 <strong>Output:</strong> [] <strong>Explanation:</strong> 2 multiplied by 2 is 4, and the original array [1,3] has a length of 2; therefore, the input is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 250</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= rowsCount &lt;= 250</code></li> <li><code>1 &lt;= colsCount &lt;= 250</code></li> </ul> <p>&nbsp;</p>
JavaScript
TypeScript
declare global { interface Array<T> { snail(rowsCount: number, colsCount: number): number[][]; } } Array.prototype.snail = function (rowsCount: number, colsCount: number): number[][] { if (rowsCount * colsCount !== this.length) { return []; } const ans: number[][] = Array.from({ length: rowsCount }, () => Array(colsCount)); for (let h = 0, i = 0, j = 0, k = 1; h < this.length; ++h) { ans[i][j] = this[h]; i += k; if (i === rowsCount || i === -1) { i -= k; k = -k; ++j; } } return ans; }; /** * const arr = [1,2,3,4]; * arr.snail(1,4); // [[1,2,3,4]] */
2,625
Flatten Deeply Nested Array
Medium
<p>Given a&nbsp;<strong>multi-dimensional</strong> array&nbsp;<code>arr</code>&nbsp;and a depth <code>n</code>, return&nbsp;a&nbsp;<strong>flattened</strong>&nbsp;version of that array.</p> <p>A <strong>multi-dimensional</strong>&nbsp;array is a recursive data structure that contains integers or other&nbsp;<strong>multi-dimensional</strong>&nbsp;arrays.</p> <p>A&nbsp;<strong>flattened</strong>&nbsp;array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting&nbsp;is less&nbsp;than&nbsp;<code>n</code>. The depth of the elements in the first array are considered to be&nbsp;<code>0</code>.</p> <p>Please solve it without the built-in&nbsp;<code>Array.flat</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 0 <strong>Output</strong> [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] <strong>Explanation</strong> Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 1 <strong>Output</strong> [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15] <strong>Explanation</strong> The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]] n = 2 <strong>Output</strong> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] <strong>Explanation</strong> The maximum depth of any subarray is 1. Thus, all of them are flattened.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= count of numbers in arr &lt;=&nbsp;10<sup>5</sup></code></li> <li><code>0 &lt;= count of subarrays in arr &lt;=&nbsp;10<sup>5</sup></code></li> <li><code>maxDepth &lt;= 1000</code></li> <li><code>-1000 &lt;= each number &lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= n &lt;= 1000</font></code></li> </ul>
JavaScript
TypeScript
type MultiDimensionalArray = (number | MultiDimensionalArray)[]; var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray { if (!n) { return arr; } const ans: MultiDimensionalArray = []; for (const x of arr) { if (Array.isArray(x) && n) { ans.push(...flat(x, n - 1)); } else { ans.push(x); } } return ans; };
2,626
Array Reduce Transformation
Easy
<p>Given an integer array <code>nums</code>, a reducer function <code>fn</code>, and an initial value <code>init</code>, return the final result obtained by executing the <code>fn</code> function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.</p> <p>This result is achieved through the following operations: <code>val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ...</code> until every element in the array has been processed. The ultimate value of <code>val</code> is then returned.</p> <p>If the length of the array is 0, the function should return <code>init</code>.</p> <p>Please solve it without using the built-in <code>Array.reduce</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr; } init = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> initially, the value is init=0. (0) + nums[0] = 1 (1) + nums[1] = 3 (3) + nums[2] = 6 (6) + nums[3] = 10 The final answer is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] fn = function sum(accum, curr) { return accum + curr * curr; } init = 100 <strong>Output:</strong> 130 <strong>Explanation:</strong> initially, the value is init=100. (100) + nums[0] * nums[0] = 101 (101) + nums[1] * nums[1] = 105 (105) + nums[2] * nums[2] = 114 (114) + nums[3] * nums[3] = 130 The final answer is 130. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [] fn = function sum(accum, curr) { return 0; } init = 25 <strong>Output:</strong> 25 <strong>Explanation:</strong> For empty arrays, the answer is always init. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> <li><code>0 &lt;= init &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
type Fn = (accum: number, curr: number) => number; function reduce(nums: number[], fn: Fn, init: number): number { let acc: number = init; for (const x of nums) { acc = fn(acc, x); } return acc; }
2,627
Debounce
Medium
<p>Given a function&nbsp;<code>fn</code> and a time in milliseconds&nbsp;<code>t</code>, return&nbsp;a&nbsp;<strong>debounced</strong>&nbsp;version of that function.</p> <p>A&nbsp;<strong>debounced</strong>&nbsp;function is a function whose execution is delayed by&nbsp;<code>t</code>&nbsp;milliseconds and whose&nbsp;execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.</p> <p>For example, let&#39;s say&nbsp;<code>t = 50ms</code>, and the function was called at&nbsp;<code>30ms</code>,&nbsp;<code>60ms</code>, and <code>100ms</code>.</p> <p>The first 2 function calls would be cancelled, and the 3rd function call would be executed at&nbsp;<code>150ms</code>.</p> <p>If instead&nbsp;<code>t = 35ms</code>, The 1st call would be cancelled, the 2nd would be executed at&nbsp;<code>95ms</code>, and the 3rd would be executed at&nbsp;<code>135ms</code>.</p> <p><img alt="Debounce Schematic" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2627.Debounce/images/screen-shot-2023-04-08-at-11048-pm.png" style="width: 800px; height: 242px;" /></p> <p>The above diagram&nbsp;shows how debounce will transform&nbsp;events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs.</p> <p>Please solve it without using lodash&#39;s&nbsp;<code>_.debounce()</code> function.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> t = 50 calls = [ &nbsp; {&quot;t&quot;: 50, inputs: [1]}, &nbsp; {&quot;t&quot;: 75, inputs: [2]} ] <strong>Output:</strong> [{&quot;t&quot;: 125, inputs: [2]}] <strong>Explanation:</strong> let start = Date.now(); function log(...inputs) { &nbsp; console.log([Date.now() - start, inputs ]) } const dlog = debounce(log, 50); setTimeout(() =&gt; dlog(1), 50); setTimeout(() =&gt; dlog(2), 75); The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> t = 20 calls = [ &nbsp; {&quot;t&quot;: 50, inputs: [1]}, &nbsp; {&quot;t&quot;: 100, inputs: [2]} ] <strong>Output:</strong> [{&quot;t&quot;: 70, inputs: [1]}, {&quot;t&quot;: 120, inputs: [2]}] <strong>Explanation:</strong> The 1st call is delayed until 70ms. The inputs were (1). The 2nd call is delayed until 120ms. The inputs were (2). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> t = 150 calls = [ &nbsp; {&quot;t&quot;: 50, inputs: [1, 2]}, &nbsp; {&quot;t&quot;: 300, inputs: [3, 4]}, &nbsp; {&quot;t&quot;: 300, inputs: [5, 6]} ] <strong>Output:</strong> [{&quot;t&quot;: 200, inputs: [1,2]}, {&quot;t&quot;: 450, inputs: [5, 6]}] <strong>Explanation:</strong> The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2). The 2nd call is cancelled by the 3rd call The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= t &lt;= 1000</code></li> <li><code>1 &lt;= calls.length &lt;= 10</code></li> <li><code>0 &lt;= calls[i].t &lt;= 1000</code></li> <li><code>0 &lt;= calls[i].inputs.length &lt;= 10</code></li> </ul>
JavaScript
TypeScript
type F = (...p: any[]) => any; function debounce(fn: F, t: number): F { let timeout: ReturnType<typeof setTimeout> | undefined; return function (...args) { if (timeout !== undefined) { clearTimeout(timeout); } timeout = setTimeout(() => { fn.apply(this, args); }, t); }; } /** * const log = debounce(console.log, 100); * log('Hello'); // cancelled * log('Hello'); // cancelled * log('Hello'); // Logged at t=100ms */
2,628
JSON Deep Equal
Medium
<p>Given two values&nbsp;<code>o1</code>&nbsp;and <code>o2</code>, return a boolean value indicating whether two values, <code>o1</code> and <code>o2</code>, are <strong>deeply equal</strong>.</p> <p>For two values to be <strong>deeply equal</strong>, the following conditions must be met:</p> <ul> <li> <p>If both values are primitive types,&nbsp;they are <strong>deeply equal</strong> if they pass the <code>===</code> equality check.</p> </li> <li> <p>If both values are arrays, they are <strong>deeply equal</strong> if they have the same elements in the same order, and each element is also <strong>deeply equal</strong> according to these conditions.</p> </li> <li> <p>If both values are objects, they are <strong>deeply equal</strong> if they have the same keys, and the associated values for each key are also <strong>deeply equal</strong> according to these conditions.</p> </li> </ul> <p>You may assume both values are the output of&nbsp;<code>JSON.parse</code>. In other words, they are valid JSON.</p> <p>Please solve it without using lodash&#39;s&nbsp;<code>_.isEqual()</code>&nbsp;function</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> o1 = {&quot;x&quot;:1,&quot;y&quot;:2}, o2 = {&quot;x&quot;:1,&quot;y&quot;:2} <strong>Output:</strong> true <strong>Explanation:</strong> The keys and values match exactly. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> o1 = {&quot;y&quot;:2,&quot;x&quot;:1}, o2 = {&quot;x&quot;:1,&quot;y&quot;:2} <strong>Output:</strong> true <strong>Explanation:</strong> Although the keys are in a different order, they still match exactly. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> o1 = {&quot;x&quot;:null,&quot;L&quot;:[1,2,3]}, o2 = {&quot;x&quot;:null,&quot;L&quot;:[&quot;1&quot;,&quot;2&quot;,&quot;3&quot;]} <strong>Output:</strong> false <strong>Explanation:</strong> The array of numbers is different from the array of strings. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> o1 = true, o2 = false <strong>Output:</strong> false <strong>Explanation:</strong> true !== false</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= JSON.stringify(o1).length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= JSON.stringify(o2).length &lt;= 10<sup>5</sup></code></li> <li><code>maxNestingDepth &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
function areDeeplyEqual(o1: any, o2: any): boolean { if (o1 === null || typeof o1 !== 'object') { return o1 === o2; } if (typeof o1 !== typeof o2) { return false; } if (Array.isArray(o1) !== Array.isArray(o2)) { return false; } if (Array.isArray(o1)) { if (o1.length !== o2.length) { return false; } for (let i = 0; i < o1.length; i++) { if (!areDeeplyEqual(o1[i], o2[i])) { return false; } } return true; } else { const keys1 = Object.keys(o1); const keys2 = Object.keys(o2); if (keys1.length !== keys2.length) { return false; } for (const key of keys1) { if (!areDeeplyEqual(o1[key], o2[key])) { return false; } } return true; } }
2,629
Function Composition
Easy
<p>Given an array of functions&nbsp;<code>[f<span style="font-size: 10.8333px;">1</span>, f<sub>2</sub>, f<sub>3</sub>,&nbsp;..., f<sub>n</sub>]</code>, return&nbsp;a new function&nbsp;<code>fn</code>&nbsp;that is the <strong>function&nbsp;composition</strong> of the array of functions.</p> <p>The&nbsp;<strong>function&nbsp;composition</strong>&nbsp;of&nbsp;<code>[f(x), g(x), h(x)]</code>&nbsp;is&nbsp;<code>fn(x) = f(g(h(x)))</code>.</p> <p>The&nbsp;<strong>function&nbsp;composition</strong>&nbsp;of an empty list of functions is the&nbsp;<strong>identity function</strong>&nbsp;<code>f(x) = x</code>.</p> <p>You may assume each&nbsp;function&nbsp;in the array accepts one integer as input&nbsp;and returns one integer as output.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> functions = [x =&gt; x + 1, x =&gt; x * x, x =&gt; 2 * x], x = 4 <strong>Output:</strong> 65 <strong>Explanation:</strong> Evaluating from right to left ... Starting with x = 4. 2 * (4) = 8 (8) * (8) = 64 (64) + 1 = 65 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> functions = [x =&gt; 10 * x, x =&gt; 10 * x, x =&gt; 10 * x], x = 1 <strong>Output:</strong> 1000 <strong>Explanation:</strong> Evaluating from right to left ... 10 * (1) = 10 10 * (10) = 100 10 * (100) = 1000 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> functions = [], x = 42 <strong>Output:</strong> 42 <strong>Explanation:</strong> The composition of zero functions is the identity function</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code><font face="monospace">-1000 &lt;= x &lt;= 1000</font></code></li> <li><code><font face="monospace">0 &lt;= functions.length &lt;= 1000</font></code></li> <li>all functions accept and return a single integer</li> </ul>
JavaScript
TypeScript
type F = (x: number) => number; function compose(functions: F[]): F { return function (x) { return functions.reduceRight((acc, fn) => fn(acc), x); }; } /** * const fn = compose([x => x + 1, x => 2 * x]) * fn(4) // 9 */
2,630
Memoize II
Hard
<p>Given a function <code>fn</code>,&nbsp;return&nbsp;a&nbsp;<strong>memoized</strong>&nbsp;version of that function.</p> <p>A&nbsp;<strong>memoized&nbsp;</strong>function is a function that will never be called twice with&nbsp;the same inputs. Instead it will return&nbsp;a cached value.</p> <p><code>fn</code>&nbsp;can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are&nbsp;<code>===</code> to each other.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> getInputs = () =&gt; [[2,2],[2,2],[1,2]] fn = function (a, b) { return a + b; } <strong>Output:</strong> [{&quot;val&quot;:4,&quot;calls&quot;:1},{&quot;val&quot;:4,&quot;calls&quot;:1},{&quot;val&quot;:3,&quot;calls&quot;:2}] <strong>Explanation:</strong> const inputs = getInputs(); const memoized = memoize(fn); for (const arr of inputs) { memoized(...arr); } For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn(). For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required. For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> getInputs = () =&gt; [[{},{}],[{},{}],[{},{}]] fn = function (a, b) { return ({...a, ...b}); } <strong>Output:</strong> [{&quot;val&quot;:{},&quot;calls&quot;:1},{&quot;val&quot;:{},&quot;calls&quot;:2},{&quot;val&quot;:{},&quot;calls&quot;:3}] <strong>Explanation:</strong> Merging two empty objects will always result in an empty object. It may seem like there should only be 1&nbsp;call to fn() because of cache-hits, however none of those objects are === to each other. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> getInputs = () =&gt; { const o = {}; return [[o,o],[o,o],[o,o]]; } fn = function (a, b) { return ({...a, ...b}); } <strong>Output:</strong> [{&quot;val&quot;:{},&quot;calls&quot;:1},{&quot;val&quot;:{},&quot;calls&quot;:1},{&quot;val&quot;:{},&quot;calls&quot;:1}] <strong>Explanation:</strong> Merging two empty objects will always result in an empty object. The 2nd and 3rd third function calls result in a cache-hit. This is because every object passed in is identical. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inputs.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= inputs.flat().length &lt;= 10<sup>5</sup></code></li> <li><code>inputs[i][j] != NaN</code></li> </ul>
JavaScript
TypeScript
type Fn = (...params: any) => any; function memoize(fn: Fn): Fn { const idxMap: Map<string, number> = new Map(); const cache: Map<string, any> = new Map(); const getIdx = (obj: any): number => { if (!idxMap.has(obj)) { idxMap.set(obj, idxMap.size); } return idxMap.get(obj)!; }; return function (...params: any) { const key = params.map(getIdx).join(','); if (!cache.has(key)) { cache.set(key, fn(...params)); } return cache.get(key)!; }; } /** * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; * return a + b; * }) * memoizedFn(2, 3) // 5 * memoizedFn(2, 3) // 5 * console.log(callCount) // 1 */
2,631
Group By
Medium
<p>Write code that enhances all arrays such that you can call the&nbsp;<code>array.groupBy(fn)</code>&nbsp;method on any array and it will return a <strong>grouped</strong>&nbsp;version of the array.</p> <p>A <strong>grouped</strong> array is an object where each&nbsp;key&nbsp;is&nbsp;the output of <code>fn(arr[i])</code> and each value is an array containing all items in the original array which generate that key.</p> <p>The provided callback&nbsp;<code>fn</code>&nbsp;will accept an item in the array and return a string key.</p> <p>The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.</p> <p>Please solve it without lodash&#39;s&nbsp;<code>_.groupBy</code> function.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> array = [ &nbsp; {&quot;id&quot;:&quot;1&quot;}, &nbsp; {&quot;id&quot;:&quot;1&quot;}, &nbsp; {&quot;id&quot;:&quot;2&quot;} ], fn = function (item) { &nbsp; return item.id; } <strong>Output:</strong> { &nbsp; &quot;1&quot;: [{&quot;id&quot;: &quot;1&quot;}, {&quot;id&quot;: &quot;1&quot;}], &nbsp; &nbsp; &quot;2&quot;: [{&quot;id&quot;: &quot;2&quot;}] } <strong>Explanation:</strong> Output is from array.groupBy(fn). The selector function gets the &quot;id&quot; out of each item in the array. There are two objects with an &quot;id&quot; of 1. Both of those objects are put in the first array. There is one object with an &quot;id&quot; of 2. That object is put in the second array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> array = [ &nbsp; [1, 2, 3], &nbsp; [1, 3, 5], &nbsp; [1, 5, 9] ] fn = function (list) { &nbsp; return String(list[0]); } <strong>Output:</strong> { &nbsp; &quot;1&quot;: [[1, 2, 3], [1, 3, 5], [1, 5, 9]] } <strong>Explanation:</strong> The array can be of any type. In this case, the selector function defines the key as being the first element in the array. All the arrays have 1 as their first element so they are grouped together. { &quot;1&quot;: [[1, 2, 3], [1, 3, 5], [1, 5, 9]] } </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] fn = function (n) { &nbsp; return String(n &gt; 5); } <strong>Output:</strong> { &nbsp; &quot;true&quot;: [6, 7, 8, 9, 10], &nbsp; &quot;false&quot;: [1, 2, 3, 4, 5] } <strong>Explanation:</strong> The selector function splits the array by whether each number is greater than 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= array.length &lt;= 10<sup>5</sup></code></li> <li><code>fn</code> returns a string</li> </ul>
JavaScript
TypeScript
declare global { interface Array<T> { groupBy(fn: (item: T) => string): Record<string, T[]>; } } Array.prototype.groupBy = function (fn) { return this.reduce((acc, item) => { const key = fn(item); if (acc[key]) { acc[key].push(item); } else { acc[key] = [item]; } return acc; }, {}); }; /** * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} */
2,632
Curry
Medium
<p>Given a function&nbsp;<code>fn</code>,&nbsp;return&nbsp;a&nbsp;<strong>curried</strong>&nbsp;version of that function.</p> <p>A&nbsp;<strong>curried</strong>&nbsp;function is a function that accepts fewer or an equal number of&nbsp;parameters as the original function and returns either another&nbsp;<strong>curried</strong>&nbsp;function or the same value the original function would have returned.</p> <p>In practical terms, if you called the original function like&nbsp;<code>sum(1,2,3)</code>, you would call the&nbsp;<strong>curried</strong>&nbsp;version like <code>csum(1)(2)(3)<font face="sans-serif, Arial, Verdana, Trebuchet MS">,&nbsp;</font></code><code>csum(1)(2,3)</code>,&nbsp;<code>csum(1,2)(3)</code>, or&nbsp;<code>csum(1,2,3)</code>. All these methods of calling the <strong>curried</strong> function&nbsp;should return the same value as the original.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = function sum(a, b, c) { return a + b + c; } inputs = [[1],[2],[3]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The code being executed is: const curriedSum = curry(fn); curriedSum(1)(2)(3) === 6; curriedSum(1)(2)(3) should return the same value as sum(1, 2, 3). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = function sum(a, b, c) { return a + b + c; } inputs = [[1,2],[3]] <strong>Output:</strong> 6 <strong>Explanation:</strong> curriedSum(1, 2)(3) should return the same value as sum(1, 2, 3).</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> fn = function sum(a, b, c) { return a + b + c; } inputs = [[],[],[1,2,3]] <strong>Output:</strong> 6 <strong>Explanation:</strong> You should be able to pass the parameters in any way, including all at once or none at all. curriedSum()()(1, 2, 3) should return the same value as sum(1, 2, 3). </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> fn = function life() { return 42; } inputs = [[]] <strong>Output:</strong> 42 <strong>Explanation:</strong> currying a function that accepts zero parameters should effectively do nothing. curriedLife() === 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inputs.length &lt;= 1000</code></li> <li><code>0 &lt;= inputs[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= fn.length &lt;= 1000</code></li> <li><code>inputs.flat().length == fn.length</code></li> <li>function parameters explicitly defined</li> <li>If <code>fn.length &gt; 0</code>&nbsp;then the last array in <code>inputs</code> is not empty</li> <li>If&nbsp;<code>fn.length === 0</code> then <code>inputs.length === 1</code>&nbsp;</li> </ul>
JavaScript
TypeScript
function curry(fn: Function): Function { return function curried(...args) { if (args.length >= fn.length) { return fn(...args); } return (...nextArgs) => curried(...args, ...nextArgs); }; } /** * function sum(a, b) { return a + b; } * const csum = curry(sum); * csum(1)(2) // 3 */
2,633
Convert Object to JSON String
Medium
<p>Given a value, return a valid JSON string of that value. The value can be a string, number, array, object, boolean, or null.&nbsp;The returned string should not include extra spaces. The order of keys should be the same as the order returned by&nbsp;<code>Object.keys()</code>.</p> <p>Please solve it without using the built-in <code>JSON.stringify</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> object = {&quot;y&quot;:1,&quot;x&quot;:2} <strong>Output:</strong> {&quot;y&quot;:1,&quot;x&quot;:2} <strong>Explanation:</strong> Return the JSON representation. Note that the order of keys should be the same as the order returned by Object.keys().</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> object = {&quot;a&quot;:&quot;str&quot;,&quot;b&quot;:-12,&quot;c&quot;:true,&quot;d&quot;:null} <strong>Output:</strong> {&quot;a&quot;:&quot;str&quot;,&quot;b&quot;:-12,&quot;c&quot;:true,&quot;d&quot;:null} <strong>Explanation:</strong> The primitives of JSON are strings, numbers, booleans, and null. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> object = {&quot;key&quot;:{&quot;a&quot;:1,&quot;b&quot;:[{},null,&quot;Hello&quot;]}} <strong>Output:</strong> {&quot;key&quot;:{&quot;a&quot;:1,&quot;b&quot;:[{},null,&quot;Hello&quot;]}} <strong>Explanation:</strong> Objects and arrays can include other objects and arrays. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> object = true <strong>Output:</strong> true <strong>Explanation:</strong> Primitive types are valid inputs.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>value</code> is a valid JSON value</li> <li><code>1 &lt;= JSON.stringify(object).length &lt;= 10<sup>5</sup></code></li> <li><code>maxNestingLevel &lt;= 1000</code></li> <li>all strings contain only alphanumeric characters</li> </ul>
JavaScript
TypeScript
function jsonStringify(object: any): string { if (object === null) { return 'null'; } if (typeof object === 'string') { return `"${object}"`; } if (typeof object === 'number' || typeof object === 'boolean') { return object.toString(); } if (Array.isArray(object)) { return `[${object.map(jsonStringify).join(',')}]`; } if (typeof object === 'object') { return `{${Object.entries(object) .map(([key, value]) => `${jsonStringify(key)}:${jsonStringify(value)}`) .join(',')}}`; } return ''; }
2,634
Filter Elements from Array
Easy
<p>Given an integer array <code>arr</code> and a filtering function <code>fn</code>, return a filtered array <code>filteredArr</code>.</p> <p>The <code>fn</code> function takes one or two arguments:</p> <ul> <li><code>arr[i]</code> - number&nbsp;from&nbsp;the <code>arr</code></li> <li><code>i</code>&nbsp;- index of <code>arr[i]</code></li> </ul> <p><code>filteredArr</code> should only contain the elements from the&nbsp;<code>arr</code> for which the expression <code>fn(arr[i], i)</code> evaluates to a <strong>truthy</strong> value. A&nbsp;<strong>truthy</strong>&nbsp;value is a value where&nbsp;<code>Boolean(value)</code>&nbsp;returns&nbsp;<code>true</code>.</p> <p>Please solve it without the built-in <code>Array.filter</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [0,10,20,30], fn = function greaterThan10(n) { return n &gt; 10; } <strong>Output:</strong> [20,30] <strong>Explanation:</strong> const newArray = filter(arr, fn); // [20, 30] The function filters out values that are not greater than 10</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; } <strong>Output:</strong> [1] <strong>Explanation:</strong> fn can also accept the index of each element In this case, the function removes elements not at index 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 } <strong>Output:</strong> [-2,0,1,2] <strong>Explanation:</strong> Falsey values such as 0 should be filtered out </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= arr.length &lt;= 1000</code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
JavaScript
TypeScript
function filter(arr: number[], fn: (n: number, i: number) => any): number[] { const ans: number[] = []; for (let i = 0; i < arr.length; ++i) { if (fn(arr[i], i)) { ans.push(arr[i]); } } return ans; }
2,635
Apply Transform Over Each Element in Array
Easy
<p>Given an integer array&nbsp;<code>arr</code>&nbsp;and a mapping function&nbsp;<code>fn</code>, return&nbsp;a new array with a transformation applied to each element.</p> <p>The returned array should be created such that&nbsp;<code>returnedArray[i] = fn(arr[i], i)</code>.</p> <p>Please solve it without the built-in <code>Array.map</code> method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3], fn = function plusone(n) { return n + 1; } <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> const newArray = map(arr, plusone); // [2,3,4] The function increases each value in the array by one. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3], fn = function plusI(n, i) { return n + i; } <strong>Output:</strong> [1,3,5] <strong>Explanation:</strong> The function increases each value by the index it resides in. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [10,20,30], fn = function constant() { return 42; } <strong>Output:</strong> [42,42,42] <strong>Explanation:</strong> The function always returns 42. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= arr.length &lt;= 1000</code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= arr[i] &lt;= 10<sup>9</sup></font></code></li> <li><code>fn</code> returns an integer.</li> </ul>
JavaScript
TypeScript
function map(arr: number[], fn: (n: number, i: number) => number): number[] { for (let i = 0; i < arr.length; ++i) { arr[i] = fn(arr[i], i); } return arr; }
2,636
Promise Pool
Medium
<p>Given an array&nbsp;of asynchronous functions&nbsp;<code>functions</code>&nbsp;and a <strong>pool limit</strong>&nbsp;<code>n</code>, return an asynchronous function&nbsp;<code>promisePool</code>. It should return&nbsp;a promise that resolves when all the input&nbsp;functions resolve.</p> <p><b>Pool limit</b> is defined as the maximum number promises that can be pending at once.&nbsp;<code>promisePool</code>&nbsp;should begin execution of as many functions as possible and continue executing new functions when old promises&nbsp;resolve.&nbsp;<code>promisePool</code>&nbsp;should execute <code>functions[i]</code>&nbsp;then <code>functions[i + 1]</code>&nbsp;then <code>functions[i + 2]</code>, etc. When the last promise resolves,&nbsp;<code>promisePool</code>&nbsp;should also resolve.</p> <p>For example, if&nbsp;<code>n = 1</code>, <code>promisePool</code>&nbsp;will execute one function at&nbsp;a time in&nbsp;series. However, if&nbsp;<code>n = 2</code>, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.</p> <p>You can assume all&nbsp;<code>functions</code>&nbsp;never reject. It is acceptable for&nbsp;<code>promisePool</code>&nbsp;to return a promise that resolves any value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> functions = [ &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 300)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 400)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 200)) ] n = 2 <strong>Output:</strong> [[300,400,500],500] <strong>Explanation:</strong> Three functions are passed in. They sleep for 300ms, 400ms, and 200ms respectively. They resolve at 300ms, 400ms, and 500ms respectively. The returned promise resolves at 500ms. At t=0, the first 2 functions are executed. The pool size limit of 2 is reached. At t=300, the 1st function resolves, and the 3rd function is executed. Pool size is 2. At t=400, the 2nd function resolves. There is nothing left to execute. Pool size is 1. At t=500, the 3rd function resolves. Pool size is zero so the returned promise also resolves. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input: </strong>functions = [ &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 300)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 400)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 200)) ] n = 5 <strong>Output:</strong> [[300,400,200],400] <strong>Explanation:</strong> The three input promises resolve at 300ms, 400ms, and 200ms respectively. The returned promise resolves at 400ms. At t=0, all 3 functions are executed. The pool limit of 5 is never met. At t=200, the 3rd function resolves. Pool size is 2. At t=300, the 1st function resolved. Pool size is 1. At t=400, the 2nd function resolves. Pool size is 0, so the returned promise also resolves. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> functions = [ &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 300)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 400)), &nbsp; () =&gt; new Promise(res =&gt; setTimeout(res, 200)) ] n = 1 <strong>Output:</strong> [[300,700,900],900] <strong>Explanation: </strong>The three input promises resolve at 300ms, 700ms, and 900ms respectively. The returned promise resolves at 900ms. At t=0, the 1st function is executed. Pool size is 1. At t=300, the 1st function resolves and the 2nd function is executed. Pool size is 1. At t=700, the 2nd function resolves and the 3rd function is executed. Pool size is 1. At t=900, the 3rd function resolves. Pool size is 0 so the returned promise resolves. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= functions.length &lt;= 10</code></li> <li><code><font face="monospace">1 &lt;= n &lt;= 10</font></code></li> </ul>
JavaScript
TypeScript
type F = () => Promise<any>; function promisePool(functions: F[], n: number): Promise<any> { const wrappers = functions.map(fn => async () => { await fn(); const nxt = waiting.shift(); nxt && (await nxt()); }); const running = wrappers.slice(0, n); const waiting = wrappers.slice(n); return Promise.all(running.map(fn => fn())); }
2,637
Promise Time Limit
Medium
<p>Given an&nbsp;asynchronous function&nbsp;<code>fn</code>&nbsp;and a time <code>t</code>&nbsp;in milliseconds, return&nbsp;a new&nbsp;<strong>time limited</strong>&nbsp;version of the input function. <code>fn</code> takes arguments provided to the&nbsp;<strong>time limited&nbsp;</strong>function.</p> <p>The <strong>time limited</strong> function should follow these rules:</p> <ul> <li>If the <code>fn</code> completes within the time limit of <code>t</code> milliseconds, the <strong>time limited</strong> function should&nbsp;resolve with the result.</li> <li>If the execution of the <code>fn</code> exceeds the time limit, the <strong>time limited</strong> function should reject with the string <code>&quot;Time Limit Exceeded&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = async (n) =&gt; { &nbsp; await new Promise(res =&gt; setTimeout(res, 100)); &nbsp; return n * n; } inputs = [5] t = 50 <strong>Output:</strong> {&quot;rejected&quot;:&quot;Time Limit Exceeded&quot;,&quot;time&quot;:50} <strong>Explanation:</strong> const limited = timeLimit(fn, t) const start = performance.now() let result; try { &nbsp; &nbsp;const res = await limited(...inputs) &nbsp; &nbsp;result = {&quot;resolved&quot;: res, &quot;time&quot;: Math.floor(performance.now() - start)}; } catch (err) { &nbsp; result = {&quot;rejected&quot;: err, &quot;time&quot;: Math.floor(performance.now() - start)}; } console.log(result) // Output The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = async (n) =&gt; { &nbsp; await new Promise(res =&gt; setTimeout(res, 100)); &nbsp; return n * n; } inputs = [5] t = 150 <strong>Output:</strong> {&quot;resolved&quot;:25,&quot;time&quot;:100} <strong>Explanation:</strong> The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> fn = async (a, b) =&gt; { &nbsp; await new Promise(res =&gt; setTimeout(res, 120)); &nbsp; return a + b; } inputs = [5,10] t = 150 <strong>Output:</strong> {&quot;resolved&quot;:15,&quot;time&quot;:120} <strong>Explanation:</strong> ​​​​The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> fn = async () =&gt; { &nbsp; throw &quot;Error&quot;; } inputs = [] t = 1000 <strong>Output:</strong> {&quot;rejected&quot;:&quot;Error&quot;,&quot;time&quot;:0} <strong>Explanation:</strong> The function immediately throws an error.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= inputs.length &lt;= 10</code></li> <li><code>0 &lt;= t &lt;= 1000</code></li> <li><code>fn</code> returns a promise</li> </ul>
JavaScript
TypeScript
type Fn = (...params: any[]) => Promise<any>; function timeLimit(fn: Fn, t: number): Fn { return async function (...args) { return Promise.race([ fn(...args), new Promise((_, reject) => setTimeout(() => reject('Time Limit Exceeded'), t)), ]); }; } /** * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100); * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms */
2,638
Count the Number of K-Free Subsets
Medium
<p>You are given an integer array <code>nums</code>,&nbsp;which contains <strong>distinct</strong> elements and an integer <code>k</code>.</p> <p>A subset is called a <strong>k-Free</strong> subset if it contains <strong>no</strong> two elements with an absolute difference equal to <code>k</code>. Notice that the empty set is a <strong>k-Free</strong> subset.</p> <p>Return <em>the number of <strong>k-Free</strong> subsets of </em><code>nums</code>.</p> <p>A <b>subset</b> of an array is a selection of elements (possibly none) of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,6], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,8], k = 5 <strong>Output:</strong> 12 <strong>Explanation:</strong> There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,5,9,11], k = 20 <strong>Output:</strong> 16 <strong>Explanation:</strong> All subsets are valid. Since the total count of subsets is 2<sup>4 </sup>= 16, so the answer is 16. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> </ul>
Array; Math; Dynamic Programming; Combinatorics; Sorting
C++
class Solution { public: long long countTheNumOfKFreeSubsets(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); unordered_map<int, vector<int>> g; for (int i = 0; i < nums.size(); ++i) { g[nums[i] % k].push_back(nums[i]); } long long ans = 1; for (auto& [_, arr] : g) { int m = arr.size(); long long f[m + 1]; f[0] = 1; f[1] = 2; for (int i = 2; i <= m; ++i) { if (arr[i - 1] - arr[i - 2] == k) { f[i] = f[i - 1] + f[i - 2]; } else { f[i] = f[i - 1] * 2; } } ans *= f[m]; } return ans; } };
2,638
Count the Number of K-Free Subsets
Medium
<p>You are given an integer array <code>nums</code>,&nbsp;which contains <strong>distinct</strong> elements and an integer <code>k</code>.</p> <p>A subset is called a <strong>k-Free</strong> subset if it contains <strong>no</strong> two elements with an absolute difference equal to <code>k</code>. Notice that the empty set is a <strong>k-Free</strong> subset.</p> <p>Return <em>the number of <strong>k-Free</strong> subsets of </em><code>nums</code>.</p> <p>A <b>subset</b> of an array is a selection of elements (possibly none) of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,6], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,8], k = 5 <strong>Output:</strong> 12 <strong>Explanation:</strong> There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,5,9,11], k = 20 <strong>Output:</strong> 16 <strong>Explanation:</strong> All subsets are valid. Since the total count of subsets is 2<sup>4 </sup>= 16, so the answer is 16. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> </ul>
Array; Math; Dynamic Programming; Combinatorics; Sorting
Go
func countTheNumOfKFreeSubsets(nums []int, k int) int64 { sort.Ints(nums) g := map[int][]int{} for _, x := range nums { g[x%k] = append(g[x%k], x) } ans := int64(1) for _, arr := range g { m := len(arr) f := make([]int64, m+1) f[0] = 1 f[1] = 2 for i := 2; i <= m; i++ { if arr[i-1]-arr[i-2] == k { f[i] = f[i-1] + f[i-2] } else { f[i] = f[i-1] * 2 } } ans *= f[m] } return ans }
2,638
Count the Number of K-Free Subsets
Medium
<p>You are given an integer array <code>nums</code>,&nbsp;which contains <strong>distinct</strong> elements and an integer <code>k</code>.</p> <p>A subset is called a <strong>k-Free</strong> subset if it contains <strong>no</strong> two elements with an absolute difference equal to <code>k</code>. Notice that the empty set is a <strong>k-Free</strong> subset.</p> <p>Return <em>the number of <strong>k-Free</strong> subsets of </em><code>nums</code>.</p> <p>A <b>subset</b> of an array is a selection of elements (possibly none) of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,6], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,8], k = 5 <strong>Output:</strong> 12 <strong>Explanation:</strong> There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,5,9,11], k = 20 <strong>Output:</strong> 16 <strong>Explanation:</strong> All subsets are valid. Since the total count of subsets is 2<sup>4 </sup>= 16, so the answer is 16. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> </ul>
Array; Math; Dynamic Programming; Combinatorics; Sorting
Java
class Solution { public long countTheNumOfKFreeSubsets(int[] nums, int k) { Arrays.sort(nums); Map<Integer, List<Integer>> g = new HashMap<>(); for (int i = 0; i < nums.length; ++i) { g.computeIfAbsent(nums[i] % k, x -> new ArrayList<>()).add(nums[i]); } long ans = 1; for (var arr : g.values()) { int m = arr.size(); long[] f = new long[m + 1]; f[0] = 1; f[1] = 2; for (int i = 2; i <= m; ++i) { if (arr.get(i - 1) - arr.get(i - 2) == k) { f[i] = f[i - 1] + f[i - 2]; } else { f[i] = f[i - 1] * 2; } } ans *= f[m]; } return ans; } }
2,638
Count the Number of K-Free Subsets
Medium
<p>You are given an integer array <code>nums</code>,&nbsp;which contains <strong>distinct</strong> elements and an integer <code>k</code>.</p> <p>A subset is called a <strong>k-Free</strong> subset if it contains <strong>no</strong> two elements with an absolute difference equal to <code>k</code>. Notice that the empty set is a <strong>k-Free</strong> subset.</p> <p>Return <em>the number of <strong>k-Free</strong> subsets of </em><code>nums</code>.</p> <p>A <b>subset</b> of an array is a selection of elements (possibly none) of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,6], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,8], k = 5 <strong>Output:</strong> 12 <strong>Explanation:</strong> There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,5,9,11], k = 20 <strong>Output:</strong> 16 <strong>Explanation:</strong> All subsets are valid. Since the total count of subsets is 2<sup>4 </sup>= 16, so the answer is 16. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> </ul>
Array; Math; Dynamic Programming; Combinatorics; Sorting
Python
class Solution: def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int: nums.sort() g = defaultdict(list) for x in nums: g[x % k].append(x) ans = 1 for arr in g.values(): m = len(arr) f = [0] * (m + 1) f[0] = 1 f[1] = 2 for i in range(2, m + 1): if arr[i - 1] - arr[i - 2] == k: f[i] = f[i - 1] + f[i - 2] else: f[i] = f[i - 1] * 2 ans *= f[m] return ans
2,638
Count the Number of K-Free Subsets
Medium
<p>You are given an integer array <code>nums</code>,&nbsp;which contains <strong>distinct</strong> elements and an integer <code>k</code>.</p> <p>A subset is called a <strong>k-Free</strong> subset if it contains <strong>no</strong> two elements with an absolute difference equal to <code>k</code>. Notice that the empty set is a <strong>k-Free</strong> subset.</p> <p>Return <em>the number of <strong>k-Free</strong> subsets of </em><code>nums</code>.</p> <p>A <b>subset</b> of an array is a selection of elements (possibly none) of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,6], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,8], k = 5 <strong>Output:</strong> 12 <strong>Explanation:</strong> There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,5,9,11], k = 20 <strong>Output:</strong> 16 <strong>Explanation:</strong> All subsets are valid. Since the total count of subsets is 2<sup>4 </sup>= 16, so the answer is 16. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> </ul>
Array; Math; Dynamic Programming; Combinatorics; Sorting
TypeScript
function countTheNumOfKFreeSubsets(nums: number[], k: number): number { nums.sort((a, b) => a - b); const g: Map<number, number[]> = new Map(); for (const x of nums) { const y = x % k; if (!g.has(y)) { g.set(y, []); } g.get(y)!.push(x); } let ans: number = 1; for (const [_, arr] of g) { const m = arr.length; const f: number[] = new Array(m + 1).fill(1); f[1] = 2; for (let i = 2; i <= m; ++i) { if (arr[i - 1] - arr[i - 2] === k) { f[i] = f[i - 1] + f[i - 2]; } else { f[i] = f[i - 1] * 2; } } ans *= f[m]; } return ans; }
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
C++
class Solution { public: vector<int> findColumnWidth(vector<vector<int>>& grid) { int n = grid[0].size(); vector<int> ans(n); for (auto& row : grid) { for (int j = 0; j < n; ++j) { int w = to_string(row[j]).size(); ans[j] = max(ans[j], w); } } return ans; } };
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
Go
func findColumnWidth(grid [][]int) []int { ans := make([]int, len(grid[0])) for _, row := range grid { for j, x := range row { w := len(strconv.Itoa(x)) ans[j] = max(ans[j], w) } } return ans }
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
Java
class Solution { public int[] findColumnWidth(int[][] grid) { int n = grid[0].length; int[] ans = new int[n]; for (var row : grid) { for (int j = 0; j < n; ++j) { int w = String.valueOf(row[j]).length(); ans[j] = Math.max(ans[j], w); } } return ans; } }
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
Python
class Solution: def findColumnWidth(self, grid: List[List[int]]) -> List[int]: return [max(len(str(x)) for x in col) for col in zip(*grid)]
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
Rust
impl Solution { pub fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32> { let mut ans = vec![0; grid[0].len()]; for row in grid.iter() { for (j, num) in row.iter().enumerate() { let width = num.to_string().len() as i32; ans[j] = std::cmp::max(ans[j], width); } } ans } }
2,639
Find the Width of Columns of a Grid
Easy
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. The width of a column is the maximum <strong>length </strong>of its integers.</p> <ul> <li>For example, if <code>grid = [[-10], [3], [12]]</code>, the width of the only column is <code>3</code> since <code>-10</code> is of length <code>3</code>.</li> </ul> <p>Return <em>an integer array</em> <code>ans</code> <em>of size</em> <code>n</code> <em>where</em> <code>ans[i]</code> <em>is the width of the</em> <code>i<sup>th</sup></code> <em>column</em>.</p> <p>The <strong>length</strong> of an integer <code>x</code> with <code>len</code> digits is equal to <code>len</code> if <code>x</code> is non-negative, and <code>len + 1</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1],[22],[333]] <strong>Output:</strong> [3] <strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]] <strong>Output:</strong> [3,1,2] <strong>Explanation:</strong> In the 0<sup>th</sup> column, only -15 is of length 3. In the 1<sup>st</sup> column, all integers are of length 1. In the 2<sup>nd</sup> column, both 12 and -2 are of length 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100 </code></li> <li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix
TypeScript
function findColumnWidth(grid: number[][]): number[] { const n = grid[0].length; const ans: number[] = new Array(n).fill(0); for (const row of grid) { for (let j = 0; j < n; ++j) { const w: number = String(row[j]).length; ans[j] = Math.max(ans[j], w); } } return ans; }
2,640
Find the Score of All Prefixes of an Array
Medium
<p>We define the <strong>conversion array</strong> <code>conver</code> of an array <code>arr</code> as follows:</p> <ul> <li><code>conver[i] = arr[i] + max(arr[0..i])</code> where <code>max(arr[0..i])</code> is the maximum value of <code>arr[j]</code> over <code>0 &lt;= j &lt;= i</code>.</li> </ul> <p>We also define the <strong>score</strong> of an array <code>arr</code> as the sum of the values of the conversion array of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the score of the prefix</em> <code>nums[0..i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,7,5,10] <strong>Output:</strong> [4,10,24,36,56] <strong>Explanation:</strong> For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,4,8,16] <strong>Output:</strong> [2,4,8,16,32,64] <strong>Explanation:</strong> For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 </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>
Array; Prefix Sum
C++
class Solution { public: vector<long long> findPrefixScore(vector<int>& nums) { int n = nums.size(); vector<long long> ans(n); int mx = 0; for (int i = 0; i < n; ++i) { mx = max(mx, nums[i]); ans[i] = nums[i] + mx + (i == 0 ? 0 : ans[i - 1]); } return ans; } };
2,640
Find the Score of All Prefixes of an Array
Medium
<p>We define the <strong>conversion array</strong> <code>conver</code> of an array <code>arr</code> as follows:</p> <ul> <li><code>conver[i] = arr[i] + max(arr[0..i])</code> where <code>max(arr[0..i])</code> is the maximum value of <code>arr[j]</code> over <code>0 &lt;= j &lt;= i</code>.</li> </ul> <p>We also define the <strong>score</strong> of an array <code>arr</code> as the sum of the values of the conversion array of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the score of the prefix</em> <code>nums[0..i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,7,5,10] <strong>Output:</strong> [4,10,24,36,56] <strong>Explanation:</strong> For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,4,8,16] <strong>Output:</strong> [2,4,8,16,32,64] <strong>Explanation:</strong> For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 </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>
Array; Prefix Sum
Go
func findPrefixScore(nums []int) []int64 { n := len(nums) ans := make([]int64, n) mx := 0 for i, x := range nums { mx = max(mx, x) ans[i] = int64(x + mx) if i > 0 { ans[i] += ans[i-1] } } return ans }
2,640
Find the Score of All Prefixes of an Array
Medium
<p>We define the <strong>conversion array</strong> <code>conver</code> of an array <code>arr</code> as follows:</p> <ul> <li><code>conver[i] = arr[i] + max(arr[0..i])</code> where <code>max(arr[0..i])</code> is the maximum value of <code>arr[j]</code> over <code>0 &lt;= j &lt;= i</code>.</li> </ul> <p>We also define the <strong>score</strong> of an array <code>arr</code> as the sum of the values of the conversion array of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the score of the prefix</em> <code>nums[0..i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,7,5,10] <strong>Output:</strong> [4,10,24,36,56] <strong>Explanation:</strong> For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,4,8,16] <strong>Output:</strong> [2,4,8,16,32,64] <strong>Explanation:</strong> For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 </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>
Array; Prefix Sum
Java
class Solution { public long[] findPrefixScore(int[] nums) { int n = nums.length; long[] ans = new long[n]; int mx = 0; for (int i = 0; i < n; ++i) { mx = Math.max(mx, nums[i]); ans[i] = nums[i] + mx + (i == 0 ? 0 : ans[i - 1]); } return ans; } }
2,640
Find the Score of All Prefixes of an Array
Medium
<p>We define the <strong>conversion array</strong> <code>conver</code> of an array <code>arr</code> as follows:</p> <ul> <li><code>conver[i] = arr[i] + max(arr[0..i])</code> where <code>max(arr[0..i])</code> is the maximum value of <code>arr[j]</code> over <code>0 &lt;= j &lt;= i</code>.</li> </ul> <p>We also define the <strong>score</strong> of an array <code>arr</code> as the sum of the values of the conversion array of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the score of the prefix</em> <code>nums[0..i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,7,5,10] <strong>Output:</strong> [4,10,24,36,56] <strong>Explanation:</strong> For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,4,8,16] <strong>Output:</strong> [2,4,8,16,32,64] <strong>Explanation:</strong> For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 </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>
Array; Prefix Sum
Python
class Solution: def findPrefixScore(self, nums: List[int]) -> List[int]: n = len(nums) ans = [0] * n mx = 0 for i, x in enumerate(nums): mx = max(mx, x) ans[i] = x + mx + (0 if i == 0 else ans[i - 1]) return ans
2,640
Find the Score of All Prefixes of an Array
Medium
<p>We define the <strong>conversion array</strong> <code>conver</code> of an array <code>arr</code> as follows:</p> <ul> <li><code>conver[i] = arr[i] + max(arr[0..i])</code> where <code>max(arr[0..i])</code> is the maximum value of <code>arr[j]</code> over <code>0 &lt;= j &lt;= i</code>.</li> </ul> <p>We also define the <strong>score</strong> of an array <code>arr</code> as the sum of the values of the conversion array of <code>arr</code>.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the score of the prefix</em> <code>nums[0..i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,7,5,10] <strong>Output:</strong> [4,10,24,36,56] <strong>Explanation:</strong> For the prefix [2], the conversion array is [4] hence the score is 4 For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10 For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24 For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36 For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,4,8,16] <strong>Output:</strong> [2,4,8,16,32,64] <strong>Explanation:</strong> For the prefix [1], the conversion array is [2] hence the score is 2 For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4 For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8 For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16 For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32 For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64 </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>
Array; Prefix Sum
TypeScript
function findPrefixScore(nums: number[]): number[] { const n = nums.length; const ans: number[] = new Array(n); let mx: number = 0; for (let i = 0; i < n; ++i) { mx = Math.max(mx, nums[i]); ans[i] = nums[i] + mx + (i === 0 ? 0 : ans[i - 1]); } return ans; }
2,641
Cousins in Binary Tree II
Medium
<p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins&#39; values</strong>.</p> <p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> <p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> <p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/example11.png" style="width: 571px; height: 151px;" /> <pre> <strong>Input:</strong> root = [5,4,9,1,10,null,7] <strong>Output:</strong> [0,0,0,7,7,null,11] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/diagram33.png" style="width: 481px; height: 91px;" /> <pre> <strong>Input:</strong> root = [3,1,2] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Hash Table; 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: TreeNode* replaceValueInTree(TreeNode* root) { memset(s, 0, sizeof(s)); dfs1(root, 0); root->val = 0; dfs2(root, 0); return root; } private: int s[100010]; void dfs1(TreeNode* root, int depth) { if (!root) { return; } s[depth] += root->val; dfs1(root->left, depth + 1); dfs1(root->right, depth + 1); }; void dfs2(TreeNode* root, int depth) { int l = root->left ? root->left->val : 0; int r = root->right ? root->right->val : 0; int sub = l + r; ++depth; if (root->left) { root->left->val = s[depth] - sub; dfs2(root->left, depth); } if (root->right) { root->right->val = s[depth] - sub; dfs2(root->right, depth); } }; };
2,641
Cousins in Binary Tree II
Medium
<p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins&#39; values</strong>.</p> <p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> <p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> <p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/example11.png" style="width: 571px; height: 151px;" /> <pre> <strong>Input:</strong> root = [5,4,9,1,10,null,7] <strong>Output:</strong> [0,0,0,7,7,null,11] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/diagram33.png" style="width: 481px; height: 91px;" /> <pre> <strong>Input:</strong> root = [3,1,2] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Hash Table; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func replaceValueInTree(root *TreeNode) *TreeNode { s := []int{} var dfs1 func(*TreeNode, int) dfs1 = func(root *TreeNode, depth int) { if root == nil { return } if len(s) <= depth { s = append(s, 0) } s[depth] += root.Val dfs1(root.Left, depth+1) dfs1(root.Right, depth+1) } var dfs2 func(*TreeNode, int) dfs2 = func(root *TreeNode, depth int) { l, r := 0, 0 if root.Left != nil { l = root.Left.Val } if root.Right != nil { r = root.Right.Val } sub := l + r depth++ if root.Left != nil { root.Left.Val = s[depth] - sub dfs2(root.Left, depth) } if root.Right != nil { root.Right.Val = s[depth] - sub dfs2(root.Right, depth) } } dfs1(root, 0) root.Val = 0 dfs2(root, 0) return root }
2,641
Cousins in Binary Tree II
Medium
<p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins&#39; values</strong>.</p> <p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> <p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> <p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/example11.png" style="width: 571px; height: 151px;" /> <pre> <strong>Input:</strong> root = [5,4,9,1,10,null,7] <strong>Output:</strong> [0,0,0,7,7,null,11] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/diagram33.png" style="width: 481px; height: 91px;" /> <pre> <strong>Input:</strong> root = [3,1,2] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Hash Table; 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 List<Integer> s = new ArrayList<>(); public TreeNode replaceValueInTree(TreeNode root) { dfs1(root, 0); root.val = 0; dfs2(root, 0); return root; } private void dfs1(TreeNode root, int depth) { if (root == null) { return; } if (s.size() <= depth) { s.add(0); } s.set(depth, s.get(depth) + root.val); dfs1(root.left, depth + 1); dfs1(root.right, depth + 1); } private void dfs2(TreeNode root, int depth) { int l = root.left == null ? 0 : root.left.val; int r = root.right == null ? 0 : root.right.val; int sub = l + r; ++depth; if (root.left != null) { root.left.val = s.get(depth) - sub; dfs2(root.left, depth); } if (root.right != null) { root.right.val = s.get(depth) - sub; dfs2(root.right, depth); } } }
2,641
Cousins in Binary Tree II
Medium
<p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins&#39; values</strong>.</p> <p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> <p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> <p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/example11.png" style="width: 571px; height: 151px;" /> <pre> <strong>Input:</strong> root = [5,4,9,1,10,null,7] <strong>Output:</strong> [0,0,0,7,7,null,11] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/diagram33.png" style="width: 481px; height: 91px;" /> <pre> <strong>Input:</strong> root = [3,1,2] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Hash Table; 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 replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def dfs1(root: Optional[TreeNode], depth: int): if root is None: return if len(s) <= depth: s.append(0) s[depth] += root.val dfs1(root.left, depth + 1) dfs1(root.right, depth + 1) def dfs2(root: Optional[TreeNode], depth: int): sub = (root.left.val if root.left else 0) + ( root.right.val if root.right else 0 ) depth += 1 if root.left: root.left.val = s[depth] - sub dfs2(root.left, depth) if root.right: root.right.val = s[depth] - sub dfs2(root.right, depth) s = [] dfs1(root, 0) root.val = 0 dfs2(root, 0) return root
2,641
Cousins in Binary Tree II
Medium
<p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins&#39; values</strong>.</p> <p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> <p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> <p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/example11.png" style="width: 571px; height: 151px;" /> <pre> <strong>Input:</strong> root = [5,4,9,1,10,null,7] <strong>Output:</strong> [0,0,0,7,7,null,11] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 5 does not have any cousins so its sum is 0. - Node with value 4 does not have any cousins so its sum is 0. - Node with value 9 does not have any cousins so its sum is 0. - Node with value 1 has a cousin with value 7 so its sum is 7. - Node with value 10 has a cousin with value 7 so its sum is 7. - Node with value 7 has cousins with values 1 and 10 so its sum is 11. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2641.Cousins%20in%20Binary%20Tree%20II/images/diagram33.png" style="width: 481px; height: 91px;" /> <pre> <strong>Input:</strong> root = [3,1,2] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. - Node with value 3 does not have any cousins so its sum is 0. - Node with value 1 does not have any cousins so its sum is 0. - Node with value 2 does not have any cousins so its sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Hash Table; 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 replaceValueInTree(root: TreeNode | null): TreeNode | null { const s: number[] = []; const dfs1 = (root: TreeNode | null, depth: number) => { if (!root) { return; } if (s.length <= depth) { s.push(0); } s[depth] += root.val; dfs1(root.left, depth + 1); dfs1(root.right, depth + 1); }; const dfs2 = (root: TreeNode | null, depth: number) => { const sub = (root.left?.val || 0) + (root.right?.val || 0); ++depth; if (root.left) { root.left.val = s[depth] - sub; dfs2(root.left, depth); } if (root.right) { root.right.val = s[depth] - sub; dfs2(root.right, depth); } }; dfs1(root, 0); root.val = 0; dfs2(root, 0); return root; }
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
C++
class Graph { public: Graph(int n, vector<vector<int>>& edges) { this->n = n; g = vector<vector<int>>(n, vector<int>(n, inf)); for (auto& e : edges) { int f = e[0], t = e[1], c = e[2]; g[f][t] = c; } } void addEdge(vector<int> edge) { int f = edge[0], t = edge[1], c = edge[2]; g[f][t] = c; } int shortestPath(int node1, int node2) { vector<bool> vis(n); vector<int> dist(n, inf); dist[node1] = 0; for (int i = 0; i < n; ++i) { int t = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[t] > dist[j])) { t = j; } } vis[t] = true; for (int j = 0; j < n; ++j) { dist[j] = min(dist[j], dist[t] + g[t][j]); } } return dist[node2] >= inf ? -1 : dist[node2]; } private: vector<vector<int>> g; int n; const int inf = 1 << 29; }; /** * Your Graph object will be instantiated and called as such: * Graph* obj = new Graph(n, edges); * obj->addEdge(edge); * int param_2 = obj->shortestPath(node1,node2); */
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
C#
public class Graph { private int n; private int[,] g; private readonly int inf = 1 << 29; public Graph(int n, int[][] edges) { this.n = n; g = new int[n, n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { g[i, j] = inf; } } foreach (var e in edges) { int f = e[0], t = e[1], c = e[2]; g[f, t] = c; } } public void AddEdge(int[] edge) { int f = edge[0], t = edge[1], c = edge[2]; g[f, t] = c; } public int ShortestPath(int node1, int node2) { int[] dist = new int[n]; bool[] vis = new bool[n]; Array.Fill(dist, inf); dist[node1] = 0; for (int i = 0; i < n; ++i) { int t = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[t] > dist[j])) { t = j; } } vis[t] = true; for (int j = 0; j < n; ++j) { dist[j] = Math.Min(dist[j], dist[t] + g[t, j]); } } return dist[node2] >= inf ? -1 : dist[node2]; } } /** * Your Graph object will be instantiated and called as such: * Graph obj = new Graph(n, edges); * obj.AddEdge(edge); * int param_2 = obj.ShortestPath(node1,node2); */
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
Go
const inf = 1 << 29 type Graph struct { g [][]int } func Constructor(n int, edges [][]int) Graph { g := make([][]int, n) for i := range g { g[i] = make([]int, n) for j := range g[i] { g[i][j] = inf } } for _, e := range edges { f, t, c := e[0], e[1], e[2] g[f][t] = c } return Graph{g} } func (this *Graph) AddEdge(edge []int) { f, t, c := edge[0], edge[1], edge[2] this.g[f][t] = c } func (this *Graph) ShortestPath(node1 int, node2 int) int { n := len(this.g) dist := make([]int, n) for i := range dist { dist[i] = inf } vis := make([]bool, n) dist[node1] = 0 for i := 0; i < n; i++ { t := -1 for j := 0; j < n; j++ { if !vis[j] && (t == -1 || dist[t] > dist[j]) { t = j } } vis[t] = true for j := 0; j < n; j++ { dist[j] = min(dist[j], dist[t]+this.g[t][j]) } } if dist[node2] >= inf { return -1 } return dist[node2] } /** * Your Graph object will be instantiated and called as such: * obj := Constructor(n, edges); * obj.AddEdge(edge); * param_2 := obj.ShortestPath(node1,node2); */
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
Java
class Graph { private int n; private int[][] g; private final int inf = 1 << 29; public Graph(int n, int[][] edges) { this.n = n; g = new int[n][n]; for (var f : g) { Arrays.fill(f, inf); } for (int[] e : edges) { int f = e[0], t = e[1], c = e[2]; g[f][t] = c; } } public void addEdge(int[] edge) { int f = edge[0], t = edge[1], c = edge[2]; g[f][t] = c; } public int shortestPath(int node1, int node2) { int[] dist = new int[n]; boolean[] vis = new boolean[n]; Arrays.fill(dist, inf); dist[node1] = 0; for (int i = 0; i < n; ++i) { int t = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[t] > dist[j])) { t = j; } } vis[t] = true; for (int j = 0; j < n; ++j) { dist[j] = Math.min(dist[j], dist[t] + g[t][j]); } } return dist[node2] >= inf ? -1 : dist[node2]; } } /** * Your Graph object will be instantiated and called as such: * Graph obj = new Graph(n, edges); * obj.addEdge(edge); * int param_2 = obj.shortestPath(node1,node2); */
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
Python
class Graph: def __init__(self, n: int, edges: List[List[int]]): self.n = n self.g = [[inf] * n for _ in range(n)] for f, t, c in edges: self.g[f][t] = c def addEdge(self, edge: List[int]) -> None: f, t, c = edge self.g[f][t] = c def shortestPath(self, node1: int, node2: int) -> int: dist = [inf] * self.n dist[node1] = 0 vis = [False] * self.n for _ in range(self.n): t = -1 for j in range(self.n): if not vis[j] and (t == -1 or dist[t] > dist[j]): t = j vis[t] = True for j in range(self.n): dist[j] = min(dist[j], dist[t] + self.g[t][j]) return -1 if dist[node2] == inf else dist[node2] # Your Graph object will be instantiated and called as such: # obj = Graph(n, edges) # obj.addEdge(edge) # param_2 = obj.shortestPath(node1,node2)
2,642
Design Graph With Shortest Path Calculator
Hard
<p>There is a <strong>directed weighted</strong> graph that consists of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>. The edges of the graph are initially represented by the given array <code>edges</code> where <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> meaning that there is an edge from <code>from<sub>i</sub></code> to <code>to<sub>i</sub></code> with the cost <code>edgeCost<sub>i</sub></code>.</p> <p>Implement the <code>Graph</code> class:</p> <ul> <li><code>Graph(int n, int[][] edges)</code> initializes the object with <code>n</code> nodes and the given edges.</li> <li><code>addEdge(int[] edge)</code> adds an edge to the list of edges where <code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li> <li><code>int shortestPath(int node1, int node2)</code> returns the <strong>minimum</strong> cost of a path from <code>node1</code> to <code>node2</code>. If no path exists, return <code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2642.Design%20Graph%20With%20Shortest%20Path%20Calculator/images/graph3drawio-2.png" style="width: 621px; height: 191px;" /> <pre> <strong>Input</strong> [&quot;Graph&quot;, &quot;shortestPath&quot;, &quot;shortestPath&quot;, &quot;addEdge&quot;, &quot;shortestPath&quot;] [[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] <strong>Output</strong> [null, 6, -1, null, 6] <strong>Explanation</strong> Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -&gt; 0 -&gt; 1 -&gt; 2 with a total cost of 3 + 2 + 1 = 6. g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -&gt; 1 -&gt; 3 with a total cost of 2 + 4 = 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li> <li><code>edges[i].length == edge.length == 3</code></li> <li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li> <li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li> <li>There are no repeated edges and no self-loops in the graph at any point.</li> <li>At most <code>100</code> calls will be made for <code>addEdge</code>.</li> <li>At most <code>100</code> calls will be made for <code>shortestPath</code>.</li> </ul>
Graph; Design; Shortest Path; Heap (Priority Queue)
TypeScript
class Graph { private g: number[][] = []; constructor(n: number, edges: number[][]) { this.g = Array.from({ length: n }, () => Array(n).fill(Infinity)); for (const [f, t, c] of edges) { this.g[f][t] = c; } } addEdge(edge: number[]): void { const [f, t, c] = edge; this.g[f][t] = c; } shortestPath(node1: number, node2: number): number { const n = this.g.length; const dist: number[] = Array(n).fill(Infinity); dist[node1] = 0; const vis: boolean[] = Array(n).fill(false); for (let i = 0; i < n; ++i) { let t = -1; for (let j = 0; j < n; ++j) { if (!vis[j] && (t === -1 || dist[j] < dist[t])) { t = j; } } vis[t] = true; for (let j = 0; j < n; ++j) { dist[j] = Math.min(dist[j], dist[t] + this.g[t][j]); } } return dist[node2] >= Infinity ? -1 : dist[node2]; } } /** * Your Graph object will be instantiated and called as such: * var obj = new Graph(n, edges) * obj.addEdge(edge) * var param_2 = obj.shortestPath(node1,node2) */
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
C++
class Solution { public: vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) { vector<int> ans(2); for (int i = 0; i < mat.size(); ++i) { int cnt = accumulate(mat[i].begin(), mat[i].end(), 0); if (ans[1] < cnt) { ans = {i, cnt}; } } return ans; } };
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
C#
public class Solution { public int[] RowAndMaximumOnes(int[][] mat) { int[] ans = new int[2]; for (int i = 0; i < mat.Length; i++) { int cnt = mat[i].Sum(); if (ans[1] < cnt) { ans = new int[] { i, cnt }; } } return ans; } }
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
Go
func rowAndMaximumOnes(mat [][]int) []int { ans := []int{0, 0} for i, row := range mat { cnt := 0 for _, x := range row { cnt += x } if ans[1] < cnt { ans = []int{i, cnt} } } return ans }
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
Java
class Solution { public int[] rowAndMaximumOnes(int[][] mat) { int[] ans = new int[2]; for (int i = 0; i < mat.length; ++i) { int cnt = 0; for (int x : mat[i]) { cnt += x; } if (ans[1] < cnt) { ans[0] = i; ans[1] = cnt; } } return ans; } }
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
Python
class Solution: def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]: ans = [0, 0] for i, row in enumerate(mat): cnt = sum(row) if ans[1] < cnt: ans = [i, cnt] return ans
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
Rust
impl Solution { pub fn row_and_maximum_ones(mat: Vec<Vec<i32>>) -> Vec<i32> { let mut ans = vec![0, 0]; for (i, row) in mat.iter().enumerate() { let cnt = row.iter().sum(); if ans[1] < cnt { ans = vec![i as i32, cnt]; } } ans } }
2,643
Row With Maximum Ones
Easy
<p>Given a <code>m x n</code> binary matrix <code>mat</code>, find the <strong>0-indexed</strong> position of the row that contains the <strong>maximum</strong> count of <strong>ones,</strong> and the number of ones in that row.</p> <p>In case there are multiple rows that have the maximum count of ones, the row with the <strong>smallest row number</strong> should be selected.</p> <p>Return<em> an array containing the index of the row, and the number of ones in it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mat = [[0,1],[1,0]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> Both rows have the same number of 1&#39;s. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0,0],[0,1,1]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[0,0],[1,1],[0,0]] <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code>&nbsp;</li> <li><code>n == mat[i].length</code>&nbsp;</li> <li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li> <li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Matrix
TypeScript
function rowAndMaximumOnes(mat: number[][]): number[] { const ans: number[] = [0, 0]; for (let i = 0; i < mat.length; i++) { const cnt = mat[i].reduce((sum, num) => sum + num, 0); if (ans[1] < cnt) { ans[0] = i; ans[1] = cnt; } } return ans; }
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
C++
class Solution { public: int maxDivScore(vector<int>& nums, vector<int>& divisors) { int ans = divisors[0]; int mx = 0; for (int div : divisors) { int cnt = 0; for (int x : nums) { cnt += x % div == 0; } if (mx < cnt) { mx = cnt; ans = div; } else if (mx == cnt) { ans = min(ans, div); } } return ans; } };
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Go
func maxDivScore(nums []int, divisors []int) int { ans, mx := divisors[0], 0 for _, div := range divisors { cnt := 0 for _, x := range nums { if x%div == 0 { cnt++ } } if mx < cnt { ans, mx = div, cnt } else if mx == cnt && ans > div { ans = div } } return ans }
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Java
class Solution { public int maxDivScore(int[] nums, int[] divisors) { int ans = divisors[0]; int mx = 0; for (int div : divisors) { int cnt = 0; for (int x : nums) { if (x % div == 0) { ++cnt; } } if (mx < cnt) { mx = cnt; ans = div; } else if (mx == cnt) { ans = Math.min(ans, div); } } return ans; } }
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Python
class Solution: def maxDivScore(self, nums: List[int], divisors: List[int]) -> int: ans, mx = divisors[0], 0 for div in divisors: cnt = sum(x % div == 0 for x in nums) if mx < cnt: mx, ans = cnt, div elif mx == cnt and ans > div: ans = div return ans
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Rust
impl Solution { pub fn max_div_score(nums: Vec<i32>, divisors: Vec<i32>) -> i32 { let mut ans = divisors[0]; let mut mx = 0; for &div in &divisors { let mut cnt = 0; for &n in &nums { if n % div == 0 { cnt += 1; } } if cnt > mx || (cnt >= mx && div < ans) { mx = cnt; ans = div; } } ans } }
2,644
Find the Maximum Divisibility Score
Easy
<p>You are given two integer arrays <code>nums</code> and <code>divisors</code>.</p> <p>The <strong>divisibility score</strong> of <code>divisors[i]</code> is the number of indices <code>j</code> such that <code>nums[j]</code> is divisible by <code>divisors[i]</code>.</p> <p>Return the integer <code>divisors[i]</code> with the <strong>maximum</strong> divisibility score. If multiple integers have the maximum score, return the smallest one.</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,9,15,50], divisors = [5,3,7,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[2]</code> and <code>nums[3]</code> are divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 2 since <code>nums[1]</code> and <code>nums[2]</code> are divisible by 3.</p> <p>The divisibility score of <code>divisors[2]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 7.</p> <p>The divisibility score of <code>divisors[3]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 2.</p> <p>As <code>divisors[0]</code>,&nbsp;<code>divisors[1]</code>, and <code>divisors[3]</code> have the same divisibility score, we return the smaller one which is <code>divisors[3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,7,9,3,9], divisors = [5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 0 since none of numbers in <code>nums</code> is divisible by 5.</p> <p>The divisibility score of <code>divisors[1]</code> is 1 since only <code>nums[0]</code> is divisible by 2.</p> <p>The divisibility score of <code>divisors[2]</code> is 3 since <code>nums[2]</code>, <code>nums[3]</code> and <code>nums[4]</code> are divisible by 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [20,14,21,10], divisors = [10,16,20]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The divisibility score of <code>divisors[0]</code> is 2 since <code>nums[0]</code> and <code>nums[3]</code> are divisible by 10.</p> <p>The divisibility score of <code>divisors[1]</code> is 0 since none of the numbers in <code>nums</code> is divisible by 16.</p> <p>The divisibility score of <code>divisors[2]</code> is 1 since <code>nums[0]</code> is divisible by 20.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length, divisors.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], divisors[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
TypeScript
function maxDivScore(nums: number[], divisors: number[]): number { let ans: number = divisors[0]; let mx: number = 0; for (const div of divisors) { const cnt = nums.reduce((a, b) => a + (b % div == 0 ? 1 : 0), 0); if (mx < cnt) { mx = cnt; ans = div; } else if (mx === cnt && ans > div) { ans = div; } } return ans; }
2,645
Minimum Additions to Make Valid String
Medium
<p>Given a string <code>word</code> to which you can insert letters &quot;a&quot;, &quot;b&quot; or &quot;c&quot; anywhere and any number of times, return <em>the minimum number of letters that must be inserted so that <code>word</code> becomes <strong>valid</strong>.</em></p> <p>A string is called <strong>valid </strong>if it can be formed by concatenating the string &quot;abc&quot; several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;b&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Insert the letter &quot;a&quot; right before &quot;b&quot;, and the letter &quot;c&quot; right next to &quot;b&quot; to obtain the valid string &quot;<strong>a</strong>b<strong>c</strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Insert letters &quot;b&quot; and &quot;c&quot; next to each &quot;a&quot; to obtain the valid string &quot;a<strong>bc</strong>a<strong>bc</strong>a<strong>bc</strong>&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abc&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> word is already valid. No modifications are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50</code></li> <li><code>word</code> consists of letters &quot;a&quot;, &quot;b&quot;&nbsp;and &quot;c&quot; only.&nbsp;</li> </ul>
Stack; Greedy; String; Dynamic Programming
C++
class Solution { public: int addMinimum(string word) { string s = "abc"; int ans = 0, n = word.size(); for (int i = 0, j = 0; j < n; i = (i + 1) % 3) { if (word[j] != s[i]) { ++ans; } else { ++j; } } if (word[n - 1] != 'c') { ans += word[n - 1] == 'b' ? 1 : 2; } return ans; } };
2,645
Minimum Additions to Make Valid String
Medium
<p>Given a string <code>word</code> to which you can insert letters &quot;a&quot;, &quot;b&quot; or &quot;c&quot; anywhere and any number of times, return <em>the minimum number of letters that must be inserted so that <code>word</code> becomes <strong>valid</strong>.</em></p> <p>A string is called <strong>valid </strong>if it can be formed by concatenating the string &quot;abc&quot; several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;b&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Insert the letter &quot;a&quot; right before &quot;b&quot;, and the letter &quot;c&quot; right next to &quot;b&quot; to obtain the valid string &quot;<strong>a</strong>b<strong>c</strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Insert letters &quot;b&quot; and &quot;c&quot; next to each &quot;a&quot; to obtain the valid string &quot;a<strong>bc</strong>a<strong>bc</strong>a<strong>bc</strong>&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abc&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> word is already valid. No modifications are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50</code></li> <li><code>word</code> consists of letters &quot;a&quot;, &quot;b&quot;&nbsp;and &quot;c&quot; only.&nbsp;</li> </ul>
Stack; Greedy; String; Dynamic Programming
Go
func addMinimum(word string) (ans int) { s := "abc" n := len(word) for i, j := 0, 0; j < n; i = (i + 1) % 3 { if word[j] != s[i] { ans++ } else { j++ } } if word[n-1] == 'b' { ans++ } else if word[n-1] == 'a' { ans += 2 } return }
2,645
Minimum Additions to Make Valid String
Medium
<p>Given a string <code>word</code> to which you can insert letters &quot;a&quot;, &quot;b&quot; or &quot;c&quot; anywhere and any number of times, return <em>the minimum number of letters that must be inserted so that <code>word</code> becomes <strong>valid</strong>.</em></p> <p>A string is called <strong>valid </strong>if it can be formed by concatenating the string &quot;abc&quot; several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;b&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Insert the letter &quot;a&quot; right before &quot;b&quot;, and the letter &quot;c&quot; right next to &quot;b&quot; to obtain the valid string &quot;<strong>a</strong>b<strong>c</strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Insert letters &quot;b&quot; and &quot;c&quot; next to each &quot;a&quot; to obtain the valid string &quot;a<strong>bc</strong>a<strong>bc</strong>a<strong>bc</strong>&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abc&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> word is already valid. No modifications are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50</code></li> <li><code>word</code> consists of letters &quot;a&quot;, &quot;b&quot;&nbsp;and &quot;c&quot; only.&nbsp;</li> </ul>
Stack; Greedy; String; Dynamic Programming
Java
class Solution { public int addMinimum(String word) { String s = "abc"; int ans = 0, n = word.length(); for (int i = 0, j = 0; j < n; i = (i + 1) % 3) { if (word.charAt(j) != s.charAt(i)) { ++ans; } else { ++j; } } if (word.charAt(n - 1) != 'c') { ans += word.charAt(n - 1) == 'b' ? 1 : 2; } return ans; } }
2,645
Minimum Additions to Make Valid String
Medium
<p>Given a string <code>word</code> to which you can insert letters &quot;a&quot;, &quot;b&quot; or &quot;c&quot; anywhere and any number of times, return <em>the minimum number of letters that must be inserted so that <code>word</code> becomes <strong>valid</strong>.</em></p> <p>A string is called <strong>valid </strong>if it can be formed by concatenating the string &quot;abc&quot; several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;b&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Insert the letter &quot;a&quot; right before &quot;b&quot;, and the letter &quot;c&quot; right next to &quot;b&quot; to obtain the valid string &quot;<strong>a</strong>b<strong>c</strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Insert letters &quot;b&quot; and &quot;c&quot; next to each &quot;a&quot; to obtain the valid string &quot;a<strong>bc</strong>a<strong>bc</strong>a<strong>bc</strong>&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abc&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> word is already valid. No modifications are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50</code></li> <li><code>word</code> consists of letters &quot;a&quot;, &quot;b&quot;&nbsp;and &quot;c&quot; only.&nbsp;</li> </ul>
Stack; Greedy; String; Dynamic Programming
Python
class Solution: def addMinimum(self, word: str) -> int: s = 'abc' ans, n = 0, len(word) i = j = 0 while j < n: if word[j] != s[i]: ans += 1 else: j += 1 i = (i + 1) % 3 if word[-1] != 'c': ans += 1 if word[-1] == 'b' else 2 return ans
2,645
Minimum Additions to Make Valid String
Medium
<p>Given a string <code>word</code> to which you can insert letters &quot;a&quot;, &quot;b&quot; or &quot;c&quot; anywhere and any number of times, return <em>the minimum number of letters that must be inserted so that <code>word</code> becomes <strong>valid</strong>.</em></p> <p>A string is called <strong>valid </strong>if it can be formed by concatenating the string &quot;abc&quot; several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;b&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Insert the letter &quot;a&quot; right before &quot;b&quot;, and the letter &quot;c&quot; right next to &quot;b&quot; to obtain the valid string &quot;<strong>a</strong>b<strong>c</strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaa&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> Insert letters &quot;b&quot; and &quot;c&quot; next to each &quot;a&quot; to obtain the valid string &quot;a<strong>bc</strong>a<strong>bc</strong>a<strong>bc</strong>&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abc&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> word is already valid. No modifications are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50</code></li> <li><code>word</code> consists of letters &quot;a&quot;, &quot;b&quot;&nbsp;and &quot;c&quot; only.&nbsp;</li> </ul>
Stack; Greedy; String; Dynamic Programming
TypeScript
function addMinimum(word: string): number { const s: string = 'abc'; let ans: number = 0; const n: number = word.length; for (let i = 0, j = 0; j < n; i = (i + 1) % 3) { if (word[j] !== s[i]) { ++ans; } else { ++j; } } if (word[n - 1] === 'b') { ++ans; } else if (word[n - 1] === 'a') { ans += 2; } return ans; }
2,646
Minimize the Total Price of the Trips
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p> <p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p> <p>Additionally, you are given a 2D integer array <code>trips</code>, where <code>trips[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> indicates that you start the <code>i<sup>th</sup></code> trip from the node <code>start<sub>i</sub></code> and travel to the node <code>end<sub>i</sub></code> by any path you like.</p> <p>Before performing your first trip, you can choose some <strong>non-adjacent</strong> nodes and halve the prices.</p> <p>Return <em>the minimum total price sum to perform all the given trips</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram2.png" style="width: 541px; height: 181px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1<sup>st</sup> trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2<sup>nd</sup> trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3<sup>rd</sup> trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram3.png" style="width: 456px; height: 111px;" /> <pre> <strong>Input:</strong> n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1<sup>st</sup> trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>edges.length == n - 1</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>edges</code> represents a valid tree.</li> <li><code>price.length == n</code></li> <li><code>price[i]</code> is an even integer.</li> <li><code>1 &lt;= price[i] &lt;= 1000</code></li> <li><code>1 &lt;= trips.length &lt;= 100</code></li> <li><code>0 &lt;= start<sub>i</sub>, end<sub>i</sub>&nbsp;&lt;= n - 1</code></li> </ul>
Tree; Depth-First Search; Graph; Array; Dynamic Programming
C++
class Solution { public: int minimumTotalPrice(int n, vector<vector<int>>& edges, vector<int>& price, vector<vector<int>>& trips) { vector<vector<int>> g(n); vector<int> cnt(n); for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } function<bool(int, int, int)> dfs = [&](int i, int fa, int k) -> bool { ++cnt[i]; if (i == k) { return true; } bool ok = false; for (int j : g[i]) { if (j != fa) { ok = dfs(j, i, k); if (ok) { break; } } } if (!ok) { --cnt[i]; } return ok; }; function<pair<int, int>(int, int)> dfs2 = [&](int i, int fa) -> pair<int, int> { int a = cnt[i] * price[i]; int b = a >> 1; for (int j : g[i]) { if (j != fa) { auto [x, y] = dfs2(j, i); a += min(x, y); b += x; } } return {a, b}; }; for (auto& t : trips) { int start = t[0], end = t[1]; dfs(start, -1, end); } auto [a, b] = dfs2(0, -1); return min(a, b); } };
2,646
Minimize the Total Price of the Trips
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p> <p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p> <p>Additionally, you are given a 2D integer array <code>trips</code>, where <code>trips[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> indicates that you start the <code>i<sup>th</sup></code> trip from the node <code>start<sub>i</sub></code> and travel to the node <code>end<sub>i</sub></code> by any path you like.</p> <p>Before performing your first trip, you can choose some <strong>non-adjacent</strong> nodes and halve the prices.</p> <p>Return <em>the minimum total price sum to perform all the given trips</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram2.png" style="width: 541px; height: 181px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1<sup>st</sup> trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2<sup>nd</sup> trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3<sup>rd</sup> trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram3.png" style="width: 456px; height: 111px;" /> <pre> <strong>Input:</strong> n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1<sup>st</sup> trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>edges.length == n - 1</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>edges</code> represents a valid tree.</li> <li><code>price.length == n</code></li> <li><code>price[i]</code> is an even integer.</li> <li><code>1 &lt;= price[i] &lt;= 1000</code></li> <li><code>1 &lt;= trips.length &lt;= 100</code></li> <li><code>0 &lt;= start<sub>i</sub>, end<sub>i</sub>&nbsp;&lt;= n - 1</code></li> </ul>
Tree; Depth-First Search; Graph; Array; Dynamic Programming
Go
func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int { g := make([][]int, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } cnt := make([]int, n) var dfs func(int, int, int) bool dfs = func(i, fa, k int) bool { cnt[i]++ if i == k { return true } ok := false for _, j := range g[i] { if j != fa { ok = dfs(j, i, k) if ok { break } } } if !ok { cnt[i]-- } return ok } for _, t := range trips { start, end := t[0], t[1] dfs(start, -1, end) } var dfs2 func(int, int) (int, int) dfs2 = func(i, fa int) (int, int) { a := price[i] * cnt[i] b := a >> 1 for _, j := range g[i] { if j != fa { x, y := dfs2(j, i) a += min(x, y) b += x } } return a, b } a, b := dfs2(0, -1) return min(a, b) }
2,646
Minimize the Total Price of the Trips
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p> <p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p> <p>Additionally, you are given a 2D integer array <code>trips</code>, where <code>trips[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> indicates that you start the <code>i<sup>th</sup></code> trip from the node <code>start<sub>i</sub></code> and travel to the node <code>end<sub>i</sub></code> by any path you like.</p> <p>Before performing your first trip, you can choose some <strong>non-adjacent</strong> nodes and halve the prices.</p> <p>Return <em>the minimum total price sum to perform all the given trips</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram2.png" style="width: 541px; height: 181px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1<sup>st</sup> trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2<sup>nd</sup> trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3<sup>rd</sup> trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram3.png" style="width: 456px; height: 111px;" /> <pre> <strong>Input:</strong> n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1<sup>st</sup> trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>edges.length == n - 1</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>edges</code> represents a valid tree.</li> <li><code>price.length == n</code></li> <li><code>price[i]</code> is an even integer.</li> <li><code>1 &lt;= price[i] &lt;= 1000</code></li> <li><code>1 &lt;= trips.length &lt;= 100</code></li> <li><code>0 &lt;= start<sub>i</sub>, end<sub>i</sub>&nbsp;&lt;= n - 1</code></li> </ul>
Tree; Depth-First Search; Graph; Array; Dynamic Programming
Java
class Solution { private List<Integer>[] g; private int[] price; private int[] cnt; public int minimumTotalPrice(int n, int[][] edges, int[] price, int[][] trips) { this.price = price; cnt = new int[n]; g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (var e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } for (var t : trips) { int start = t[0], end = t[1]; dfs(start, -1, end); } int[] ans = dfs2(0, -1); return Math.min(ans[0], ans[1]); } private boolean dfs(int i, int fa, int k) { ++cnt[i]; if (i == k) { return true; } boolean ok = false; for (int j : g[i]) { if (j != fa) { ok = dfs(j, i, k); if (ok) { break; } } } if (!ok) { --cnt[i]; } return ok; } private int[] dfs2(int i, int fa) { int a = cnt[i] * price[i]; int b = a >> 1; for (int j : g[i]) { if (j != fa) { var t = dfs2(j, i); a += Math.min(t[0], t[1]); b += t[0]; } } return new int[] {a, b}; } }
2,646
Minimize the Total Price of the Trips
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p> <p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p> <p>Additionally, you are given a 2D integer array <code>trips</code>, where <code>trips[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> indicates that you start the <code>i<sup>th</sup></code> trip from the node <code>start<sub>i</sub></code> and travel to the node <code>end<sub>i</sub></code> by any path you like.</p> <p>Before performing your first trip, you can choose some <strong>non-adjacent</strong> nodes and halve the prices.</p> <p>Return <em>the minimum total price sum to perform all the given trips</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram2.png" style="width: 541px; height: 181px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1<sup>st</sup> trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2<sup>nd</sup> trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3<sup>rd</sup> trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram3.png" style="width: 456px; height: 111px;" /> <pre> <strong>Input:</strong> n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1<sup>st</sup> trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>edges.length == n - 1</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>edges</code> represents a valid tree.</li> <li><code>price.length == n</code></li> <li><code>price[i]</code> is an even integer.</li> <li><code>1 &lt;= price[i] &lt;= 1000</code></li> <li><code>1 &lt;= trips.length &lt;= 100</code></li> <li><code>0 &lt;= start<sub>i</sub>, end<sub>i</sub>&nbsp;&lt;= n - 1</code></li> </ul>
Tree; Depth-First Search; Graph; Array; Dynamic Programming
Python
class Solution: def minimumTotalPrice( self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]] ) -> int: def dfs(i: int, fa: int, k: int) -> bool: cnt[i] += 1 if i == k: return True ok = any(j != fa and dfs(j, i, k) for j in g[i]) if not ok: cnt[i] -= 1 return ok def dfs2(i: int, fa: int) -> (int, int): a = cnt[i] * price[i] b = a // 2 for j in g[i]: if j != fa: x, y = dfs2(j, i) a += min(x, y) b += x return a, b g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) cnt = Counter() for start, end in trips: dfs(start, -1, end) return min(dfs2(0, -1))
2,646
Minimize the Total Price of the Trips
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p> <p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p> <p>Additionally, you are given a 2D integer array <code>trips</code>, where <code>trips[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> indicates that you start the <code>i<sup>th</sup></code> trip from the node <code>start<sub>i</sub></code> and travel to the node <code>end<sub>i</sub></code> by any path you like.</p> <p>Before performing your first trip, you can choose some <strong>non-adjacent</strong> nodes and halve the prices.</p> <p>Return <em>the minimum total price sum to perform all the given trips</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram2.png" style="width: 541px; height: 181px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half. For the 1<sup>st</sup> trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6. For the 2<sup>nd</sup> trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7. For the 3<sup>rd</sup> trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10. The total price sum of all trips is 6 + 7 + 10 = 23. It can be proven, that 23 is the minimum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2646.Minimize%20the%20Total%20Price%20of%20the%20Trips/images/diagram3.png" style="width: 456px; height: 111px;" /> <pre> <strong>Input:</strong> n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half. For the 1<sup>st</sup> trip, we choose path [0]. The price sum of that path is 1. The total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>edges.length == n - 1</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>edges</code> represents a valid tree.</li> <li><code>price.length == n</code></li> <li><code>price[i]</code> is an even integer.</li> <li><code>1 &lt;= price[i] &lt;= 1000</code></li> <li><code>1 &lt;= trips.length &lt;= 100</code></li> <li><code>0 &lt;= start<sub>i</sub>, end<sub>i</sub>&nbsp;&lt;= n - 1</code></li> </ul>
Tree; Depth-First Search; Graph; Array; Dynamic Programming
TypeScript
function minimumTotalPrice( n: number, edges: number[][], price: number[], trips: number[][], ): number { const g: number[][] = Array.from({ length: n }, () => []); for (const [a, b] of edges) { g[a].push(b); g[b].push(a); } const cnt: number[] = new Array(n).fill(0); const dfs = (i: number, fa: number, k: number): boolean => { ++cnt[i]; if (i === k) { return true; } let ok = false; for (const j of g[i]) { if (j !== fa) { ok = dfs(j, i, k); if (ok) { break; } } } if (!ok) { --cnt[i]; } return ok; }; for (const [start, end] of trips) { dfs(start, -1, end); } const dfs2 = (i: number, fa: number): number[] => { let a: number = price[i] * cnt[i]; let b: number = a >> 1; for (const j of g[i]) { if (j !== fa) { const [x, y] = dfs2(j, i); a += Math.min(x, y); b += x; } } return [a, b]; }; const [a, b] = dfs2(0, -1); return Math.min(a, b); }
2,647
Color the Triangle Red
Hard
<p>You are given an integer <code>n</code>. Consider an equilateral triangle of side length <code>n</code>, broken up into <code>n<sup>2</sup></code> unit equilateral triangles. The triangle has <code>n</code> <strong>1-indexed</strong> rows where the <code>i<sup>th</sup></code> row has <code>2i - 1</code> unit equilateral triangles.</p> <p>The triangles in the <code>i<sup>th</sup></code> row are also <strong>1-indexed</strong> with coordinates from <code>(i, 1)</code> to <code>(i, 2i - 1)</code>. The following image shows a triangle of side length <code>4</code> with the indexing of its triangle.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/triangle4.jpg" style="width: 402px; height: 242px;" /> <p>Two triangles are <strong>neighbors</strong> if they <strong>share a side</strong>. For example:</p> <ul> <li>Triangles <code>(1,1)</code> and <code>(2,2)</code> are neighbors</li> <li>Triangles <code>(3,2)</code> and <code>(3,3)</code> are neighbors.</li> <li>Triangles <code>(2,2)</code> and <code>(3,3)</code> are not neighbors because they do not share any side.</li> </ul> <p>Initially, all the unit triangles are <strong>white</strong>. You want to choose <code>k</code> triangles and color them <strong>red</strong>. We will then run the following algorithm:</p> <ol> <li>Choose a white triangle that has <strong>at least two</strong> red neighbors. <ul> <li>If there is no such triangle, stop the algorithm.</li> </ul> </li> <li>Color that triangle <strong>red</strong>.</li> <li>Go to step 1.</li> </ol> <p>Choose the minimum <code>k</code> possible and set <code>k</code> triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.</p> <p>Return <em>a 2D list of the coordinates of the triangles that you will color red initially</em>. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example1.jpg" style="width: 500px; height: 263px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,1],[2,1],[2,3],[3,1],[3,5]] <strong>Explanation:</strong> Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. - Choose (3,2) that has two red neighbors and color it red. - Choose (3,4) that has three red neighbors and color it red. - Choose (3,3) that has three red neighbors and color it red. It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example2.jpg" style="width: 300px; height: 101px;" /> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [[1,1],[2,1],[2,3]] <strong>Explanation:</strong> Initially, we choose the shown 3 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. It can be shown that choosing any 2 triangles and running the algorithm will not make all triangles red. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Math
C++
class Solution { public: vector<vector<int>> colorRed(int n) { vector<vector<int>> ans; ans.push_back({1, 1}); for (int i = n, k = 0; i > 1; --i, k = (k + 1) % 4) { if (k == 0) { for (int j = 1; j < i << 1; j += 2) { ans.push_back({i, j}); } } else if (k == 1) { ans.push_back({i, 2}); } else if (k == 2) { for (int j = 3; j < i << 1; j += 2) { ans.push_back({i, j}); } } else { ans.push_back({i, 1}); } } return ans; } };
2,647
Color the Triangle Red
Hard
<p>You are given an integer <code>n</code>. Consider an equilateral triangle of side length <code>n</code>, broken up into <code>n<sup>2</sup></code> unit equilateral triangles. The triangle has <code>n</code> <strong>1-indexed</strong> rows where the <code>i<sup>th</sup></code> row has <code>2i - 1</code> unit equilateral triangles.</p> <p>The triangles in the <code>i<sup>th</sup></code> row are also <strong>1-indexed</strong> with coordinates from <code>(i, 1)</code> to <code>(i, 2i - 1)</code>. The following image shows a triangle of side length <code>4</code> with the indexing of its triangle.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/triangle4.jpg" style="width: 402px; height: 242px;" /> <p>Two triangles are <strong>neighbors</strong> if they <strong>share a side</strong>. For example:</p> <ul> <li>Triangles <code>(1,1)</code> and <code>(2,2)</code> are neighbors</li> <li>Triangles <code>(3,2)</code> and <code>(3,3)</code> are neighbors.</li> <li>Triangles <code>(2,2)</code> and <code>(3,3)</code> are not neighbors because they do not share any side.</li> </ul> <p>Initially, all the unit triangles are <strong>white</strong>. You want to choose <code>k</code> triangles and color them <strong>red</strong>. We will then run the following algorithm:</p> <ol> <li>Choose a white triangle that has <strong>at least two</strong> red neighbors. <ul> <li>If there is no such triangle, stop the algorithm.</li> </ul> </li> <li>Color that triangle <strong>red</strong>.</li> <li>Go to step 1.</li> </ol> <p>Choose the minimum <code>k</code> possible and set <code>k</code> triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.</p> <p>Return <em>a 2D list of the coordinates of the triangles that you will color red initially</em>. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example1.jpg" style="width: 500px; height: 263px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,1],[2,1],[2,3],[3,1],[3,5]] <strong>Explanation:</strong> Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. - Choose (3,2) that has two red neighbors and color it red. - Choose (3,4) that has three red neighbors and color it red. - Choose (3,3) that has three red neighbors and color it red. It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example2.jpg" style="width: 300px; height: 101px;" /> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [[1,1],[2,1],[2,3]] <strong>Explanation:</strong> Initially, we choose the shown 3 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. It can be shown that choosing any 2 triangles and running the algorithm will not make all triangles red. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Math
Go
func colorRed(n int) (ans [][]int) { ans = append(ans, []int{1, 1}) for i, k := n, 0; i > 1; i, k = i-1, (k+1)%4 { if k == 0 { for j := 1; j < i<<1; j += 2 { ans = append(ans, []int{i, j}) } } else if k == 1 { ans = append(ans, []int{i, 2}) } else if k == 2 { for j := 3; j < i<<1; j += 2 { ans = append(ans, []int{i, j}) } } else { ans = append(ans, []int{i, 1}) } } return }
2,647
Color the Triangle Red
Hard
<p>You are given an integer <code>n</code>. Consider an equilateral triangle of side length <code>n</code>, broken up into <code>n<sup>2</sup></code> unit equilateral triangles. The triangle has <code>n</code> <strong>1-indexed</strong> rows where the <code>i<sup>th</sup></code> row has <code>2i - 1</code> unit equilateral triangles.</p> <p>The triangles in the <code>i<sup>th</sup></code> row are also <strong>1-indexed</strong> with coordinates from <code>(i, 1)</code> to <code>(i, 2i - 1)</code>. The following image shows a triangle of side length <code>4</code> with the indexing of its triangle.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/triangle4.jpg" style="width: 402px; height: 242px;" /> <p>Two triangles are <strong>neighbors</strong> if they <strong>share a side</strong>. For example:</p> <ul> <li>Triangles <code>(1,1)</code> and <code>(2,2)</code> are neighbors</li> <li>Triangles <code>(3,2)</code> and <code>(3,3)</code> are neighbors.</li> <li>Triangles <code>(2,2)</code> and <code>(3,3)</code> are not neighbors because they do not share any side.</li> </ul> <p>Initially, all the unit triangles are <strong>white</strong>. You want to choose <code>k</code> triangles and color them <strong>red</strong>. We will then run the following algorithm:</p> <ol> <li>Choose a white triangle that has <strong>at least two</strong> red neighbors. <ul> <li>If there is no such triangle, stop the algorithm.</li> </ul> </li> <li>Color that triangle <strong>red</strong>.</li> <li>Go to step 1.</li> </ol> <p>Choose the minimum <code>k</code> possible and set <code>k</code> triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.</p> <p>Return <em>a 2D list of the coordinates of the triangles that you will color red initially</em>. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example1.jpg" style="width: 500px; height: 263px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,1],[2,1],[2,3],[3,1],[3,5]] <strong>Explanation:</strong> Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. - Choose (3,2) that has two red neighbors and color it red. - Choose (3,4) that has three red neighbors and color it red. - Choose (3,3) that has three red neighbors and color it red. It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example2.jpg" style="width: 300px; height: 101px;" /> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [[1,1],[2,1],[2,3]] <strong>Explanation:</strong> Initially, we choose the shown 3 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. It can be shown that choosing any 2 triangles and running the algorithm will not make all triangles red. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Math
Java
class Solution { public int[][] colorRed(int n) { List<int[]> ans = new ArrayList<>(); ans.add(new int[] {1, 1}); for (int i = n, k = 0; i > 1; --i, k = (k + 1) % 4) { if (k == 0) { for (int j = 1; j < i << 1; j += 2) { ans.add(new int[] {i, j}); } } else if (k == 1) { ans.add(new int[] {i, 2}); } else if (k == 2) { for (int j = 3; j < i << 1; j += 2) { ans.add(new int[] {i, j}); } } else { ans.add(new int[] {i, 1}); } } return ans.toArray(new int[0][]); } }
2,647
Color the Triangle Red
Hard
<p>You are given an integer <code>n</code>. Consider an equilateral triangle of side length <code>n</code>, broken up into <code>n<sup>2</sup></code> unit equilateral triangles. The triangle has <code>n</code> <strong>1-indexed</strong> rows where the <code>i<sup>th</sup></code> row has <code>2i - 1</code> unit equilateral triangles.</p> <p>The triangles in the <code>i<sup>th</sup></code> row are also <strong>1-indexed</strong> with coordinates from <code>(i, 1)</code> to <code>(i, 2i - 1)</code>. The following image shows a triangle of side length <code>4</code> with the indexing of its triangle.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/triangle4.jpg" style="width: 402px; height: 242px;" /> <p>Two triangles are <strong>neighbors</strong> if they <strong>share a side</strong>. For example:</p> <ul> <li>Triangles <code>(1,1)</code> and <code>(2,2)</code> are neighbors</li> <li>Triangles <code>(3,2)</code> and <code>(3,3)</code> are neighbors.</li> <li>Triangles <code>(2,2)</code> and <code>(3,3)</code> are not neighbors because they do not share any side.</li> </ul> <p>Initially, all the unit triangles are <strong>white</strong>. You want to choose <code>k</code> triangles and color them <strong>red</strong>. We will then run the following algorithm:</p> <ol> <li>Choose a white triangle that has <strong>at least two</strong> red neighbors. <ul> <li>If there is no such triangle, stop the algorithm.</li> </ul> </li> <li>Color that triangle <strong>red</strong>.</li> <li>Go to step 1.</li> </ol> <p>Choose the minimum <code>k</code> possible and set <code>k</code> triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.</p> <p>Return <em>a 2D list of the coordinates of the triangles that you will color red initially</em>. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example1.jpg" style="width: 500px; height: 263px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,1],[2,1],[2,3],[3,1],[3,5]] <strong>Explanation:</strong> Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. - Choose (3,2) that has two red neighbors and color it red. - Choose (3,4) that has three red neighbors and color it red. - Choose (3,3) that has three red neighbors and color it red. It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example2.jpg" style="width: 300px; height: 101px;" /> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [[1,1],[2,1],[2,3]] <strong>Explanation:</strong> Initially, we choose the shown 3 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. It can be shown that choosing any 2 triangles and running the algorithm will not make all triangles red. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Math
Python
class Solution: def colorRed(self, n: int) -> List[List[int]]: ans = [[1, 1]] k = 0 for i in range(n, 1, -1): if k == 0: for j in range(1, i << 1, 2): ans.append([i, j]) elif k == 1: ans.append([i, 2]) elif k == 2: for j in range(3, i << 1, 2): ans.append([i, j]) else: ans.append([i, 1]) k = (k + 1) % 4 return ans
2,647
Color the Triangle Red
Hard
<p>You are given an integer <code>n</code>. Consider an equilateral triangle of side length <code>n</code>, broken up into <code>n<sup>2</sup></code> unit equilateral triangles. The triangle has <code>n</code> <strong>1-indexed</strong> rows where the <code>i<sup>th</sup></code> row has <code>2i - 1</code> unit equilateral triangles.</p> <p>The triangles in the <code>i<sup>th</sup></code> row are also <strong>1-indexed</strong> with coordinates from <code>(i, 1)</code> to <code>(i, 2i - 1)</code>. The following image shows a triangle of side length <code>4</code> with the indexing of its triangle.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/triangle4.jpg" style="width: 402px; height: 242px;" /> <p>Two triangles are <strong>neighbors</strong> if they <strong>share a side</strong>. For example:</p> <ul> <li>Triangles <code>(1,1)</code> and <code>(2,2)</code> are neighbors</li> <li>Triangles <code>(3,2)</code> and <code>(3,3)</code> are neighbors.</li> <li>Triangles <code>(2,2)</code> and <code>(3,3)</code> are not neighbors because they do not share any side.</li> </ul> <p>Initially, all the unit triangles are <strong>white</strong>. You want to choose <code>k</code> triangles and color them <strong>red</strong>. We will then run the following algorithm:</p> <ol> <li>Choose a white triangle that has <strong>at least two</strong> red neighbors. <ul> <li>If there is no such triangle, stop the algorithm.</li> </ul> </li> <li>Color that triangle <strong>red</strong>.</li> <li>Go to step 1.</li> </ol> <p>Choose the minimum <code>k</code> possible and set <code>k</code> triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.</p> <p>Return <em>a 2D list of the coordinates of the triangles that you will color red initially</em>. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example1.jpg" style="width: 500px; height: 263px;" /> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> [[1,1],[2,1],[2,3],[3,1],[3,5]] <strong>Explanation:</strong> Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. - Choose (3,2) that has two red neighbors and color it red. - Choose (3,4) that has three red neighbors and color it red. - Choose (3,3) that has three red neighbors and color it red. It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2647.Color%20the%20Triangle%20Red/images/example2.jpg" style="width: 300px; height: 101px;" /> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> [[1,1],[2,1],[2,3]] <strong>Explanation:</strong> Initially, we choose the shown 3 triangles to be red. Then, we run the algorithm: - Choose (2,2) that has three red neighbors and color it red. It can be shown that choosing any 2 triangles and running the algorithm will not make all triangles red. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Math
TypeScript
function colorRed(n: number): number[][] { const ans: number[][] = [[1, 1]]; for (let i = n, k = 0; i > 1; --i, k = (k + 1) % 4) { if (k === 0) { for (let j = 1; j < i << 1; j += 2) { ans.push([i, j]); } } else if (k === 1) { ans.push([i, 2]); } else if (k === 2) { for (let j = 3; j < i << 1; j += 2) { ans.push([i, j]); } } else { ans.push([i, 1]); } } return ans; }
2,648
Generate Fibonacci Sequence
Easy
<p>Write a generator function that returns a generator object which yields the&nbsp;<strong>fibonacci sequence</strong>.</p> <p>The&nbsp;<strong>fibonacci sequence</strong>&nbsp;is defined by the relation <code>X<sub>n</sub>&nbsp;= X<sub>n-1</sub>&nbsp;+ X<sub>n-2</sub></code>.</p> <p>The first few numbers&nbsp;of the series are <code>0, 1, 1, 2, 3, 5, 8, 13</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> callCount = 5 <strong>Output:</strong> [0,1,1,2,3] <strong>Explanation:</strong> const gen = fibGenerator(); gen.next().value; // 0 gen.next().value; // 1 gen.next().value; // 1 gen.next().value; // 2 gen.next().value; // 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> callCount = 0 <strong>Output:</strong> [] <strong>Explanation:</strong> gen.next() is never called so nothing is outputted </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= callCount &lt;= 50</code></li> </ul>
JavaScript
TypeScript
function* fibGenerator(): Generator<number, any, number> { let a = 0; let b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } /** * const gen = fibGenerator(); * gen.next().value; // 0 * gen.next().value; // 1 */
2,649
Nested Array Generator
Medium
<p>Given a&nbsp;<strong>multi-dimensional array</strong> of integers, return&nbsp;a generator object which&nbsp;yields integers in the same order as&nbsp;<strong>inorder traversal</strong>.</p> <p>A&nbsp;<strong>multi-dimensional array</strong>&nbsp;is a recursive data structure that contains both integers and other&nbsp;<strong>multi-dimensional arrays</strong>.</p> <p><strong>inorder traversal</strong>&nbsp;iterates over&nbsp;each array from left to right, yielding any integers it encounters or applying&nbsp;<strong>inorder traversal</strong>&nbsp;to any arrays it encounters.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [[[6]],[1,3],[]] <strong>Output:</strong> [6,1,3] <strong>Explanation:</strong> const generator = inorderTraversal(arr); generator.next().value; // 6 generator.next().value; // 1 generator.next().value; // 3 generator.next().done; // true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [] <strong>Output:</strong> [] <strong>Explanation:</strong> There are no integers so the generator doesn&#39;t yield anything. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= arr.flat().length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= arr.flat()[i]&nbsp;&lt;= 10<sup>5</sup></code></li> <li><code>maxNestingDepth &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Can you solve this without creating a new flattened version of the array?</strong>
JavaScript
TypeScript
type MultidimensionalArray = (MultidimensionalArray | number)[]; function* inorderTraversal(arr: MultidimensionalArray): Generator<number, void, unknown> { for (const e of arr) { if (Array.isArray(e)) { yield* inorderTraversal(e); } else { yield e; } } } /** * const gen = inorderTraversal([1, [2, 3]]); * gen.next().value; // 1 * gen.next().value; // 2 * gen.next().value; // 3 */
2,650
Design Cancellable Function
Hard
<p>Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function&nbsp;<code>cancellable</code> that accepts a generator object and returns an array of two values: a <strong>cancel function</strong> and a <strong>promise</strong>.</p> <p>You may assume the generator function will only&nbsp;yield promises. It is your function&#39;s responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that&nbsp;error back to the generator.</p> <p>If the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string&nbsp;<code>&quot;Cancelled&quot;</code>&nbsp;(Not an <code>Error</code>&nbsp;object). If the error was caught, the returned&nbsp;promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.</p> <p>When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.</p> <p>An example of how your code would be used:</p> <pre> function* tasks() { const val = yield new Promise(resolve =&gt; resolve(2 + 2)); yield new Promise(resolve =&gt; setTimeout(resolve, 100)); return val + 1; // calculation shouldn&#39;t be done. } const [cancel, promise] = cancellable(tasks()); setTimeout(cancel, 50); promise.catch(console.log); // logs &quot;Cancelled&quot; at t=50ms </pre> <p>If&nbsp;instead&nbsp;<code>cancel()</code> was not called or was called after <code>t=100ms</code>, the promise would&nbsp;have resolved&nbsp;<code>5</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; return 42; } cancelledAt = 100 <strong>Output:</strong> {&quot;resolved&quot;: 42} <strong>Explanation:</strong> const generator = generatorFunction(); const [cancel, promise] = cancellable(generator); setTimeout(cancel, 100); promise.then(console.log); // resolves 42 at t=0ms The generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; const msg = yield new Promise(res =&gt; res(&quot;Hello&quot;)); &nbsp; throw `Error: ${msg}`; } cancelledAt = null <strong>Output:</strong> {&quot;rejected&quot;: &quot;Error: Hello&quot;} <strong>Explanation:</strong> A promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; yield new Promise(res =&gt; setTimeout(res, 200)); &nbsp; return &quot;Success&quot;; } cancelledAt = 100 <strong>Output:</strong> {&quot;rejected&quot;: &quot;Cancelled&quot;} <strong>Explanation:</strong> While the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; let result = 0; &nbsp; yield new Promise(res =&gt; setTimeout(res, 100)); &nbsp; result += yield new Promise(res =&gt; res(1)); &nbsp; yield new Promise(res =&gt; setTimeout(res, 100)); &nbsp; result += yield new Promise(res =&gt; res(1)); &nbsp; return result; } cancelledAt = null <strong>Output:</strong> {&quot;resolved&quot;: 2} <strong>Explanation:</strong> 4 promises are yielded. Two of those promises have their values added to the result. After 200ms, the generator finishes with a value of 2, and that value is resolved by the returned promise. </pre> <p><strong class="example">Example 5:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; let result = 0; &nbsp; try { &nbsp; yield new Promise(res =&gt; setTimeout(res, 100)); &nbsp; result += yield new Promise(res =&gt; res(1)); &nbsp; yield new Promise(res =&gt; setTimeout(res, 100)); &nbsp; result += yield new Promise(res =&gt; res(1)); &nbsp; } catch(e) { &nbsp; return result; &nbsp; } &nbsp; return result; } cancelledAt = 150 <strong>Output:</strong> {&quot;resolved&quot;: 1} <strong>Explanation:</strong> The first two yielded promises resolve and cause the result to increment. However, at t=150ms, the generator is cancelled. The error sent to the generator is caught and the result is returned and finally resolved by the returned promise. </pre> <p><strong class="example">Example 6:</strong></p> <pre> <strong>Input:</strong> generatorFunction = function*() { &nbsp; try { &nbsp; yield new Promise((resolve, reject) =&gt; reject(&quot;Promise Rejected&quot;)); &nbsp; } catch(e) { &nbsp; let a = yield new Promise(resolve =&gt; resolve(2)); let b = yield new Promise(resolve =&gt; resolve(2)); &nbsp; return a + b; &nbsp; }; } cancelledAt = null <strong>Output:</strong> {&quot;resolved&quot;: 4} <strong>Explanation:</strong> The first yielded promise immediately rejects. This error is caught. Because the generator hasn&#39;t been cancelled, execution continues as usual. It ends up resolving 2 + 2 = 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>cancelledAt == null or 0 &lt;= cancelledAt &lt;= 1000</code></li> <li><code>generatorFunction</code> returns a generator object</li> </ul>
JavaScript
TypeScript
function cancellable<T>(generator: Generator<Promise<any>, T, unknown>): [() => void, Promise<T>] { let cancel: () => void = () => {}; const cancelPromise = new Promise((resolve, reject) => { cancel = () => reject('Cancelled'); }); cancelPromise.catch(() => {}); const promise = (async () => { let next = generator.next(); while (!next.done) { try { next = generator.next(await Promise.race([next.value, cancelPromise])); } catch (e) { next = generator.throw(e); } } return next.value; })(); return [cancel, promise]; } /** * function* tasks() { * const val = yield new Promise(resolve => resolve(2 + 2)); * yield new Promise(resolve => setTimeout(resolve, 100)); * return val + 1; * } * const [cancel, promise] = cancellable(tasks()); * setTimeout(cancel, 50); * promise.catch(console.log); // logs "Cancelled" at t=50ms */
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
C++
class Solution { public: int findDelayedArrivalTime(int arrivalTime, int delayedTime) { return (arrivalTime + delayedTime) % 24; } };
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
Go
func findDelayedArrivalTime(arrivalTime int, delayedTime int) int { return (arrivalTime + delayedTime) % 24 }
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
Java
class Solution { public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { return (arrivalTime + delayedTime) % 24; } }
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
Python
class Solution: def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int: return (arrivalTime + delayedTime) % 24
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
Rust
impl Solution { pub fn find_delayed_arrival_time(arrival_time: i32, delayed_time: i32) -> i32 { (arrival_time + delayed_time) % 24 } }
2,651
Calculate Delayed Arrival Time
Easy
<p>You are given a positive integer <code>arrivalTime</code> denoting the arrival time of a train in hours, and another positive integer <code>delayedTime</code> denoting the amount of delay in hours.</p> <p>Return <em>the time when the train will arrive at the station.</em></p> <p>Note that the time in this problem is in 24-hours format.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 15, delayedTime = 5 <strong>Output:</strong> 20 <strong>Explanation:</strong> Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arrivalTime = 13, delayedTime = 11 <strong>Output:</strong> 0 <strong>Explanation:</strong> Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arrivaltime &lt;&nbsp;24</code></li> <li><code>1 &lt;= delayedTime &lt;= 24</code></li> </ul>
Math
TypeScript
function findDelayedArrivalTime(arrivalTime: number, delayedTime: number): number { return (arrivalTime + delayedTime) % 24; }
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
C++
class Solution { public: int sumOfMultiples(int n) { int ans = 0; for (int x = 1; x <= n; ++x) { if (x % 3 == 0 || x % 5 == 0 || x % 7 == 0) { ans += x; } } return ans; } };
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
Go
func sumOfMultiples(n int) (ans int) { for x := 1; x <= n; x++ { if x%3 == 0 || x%5 == 0 || x%7 == 0 { ans += x } } return }
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
Java
class Solution { public int sumOfMultiples(int n) { int ans = 0; for (int x = 1; x <= n; ++x) { if (x % 3 == 0 || x % 5 == 0 || x % 7 == 0) { ans += x; } } return ans; } }
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
Python
class Solution: def sumOfMultiples(self, n: int) -> int: return sum(x for x in range(1, n + 1) if x % 3 == 0 or x % 5 == 0 or x % 7 == 0)
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
Rust
impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { let mut ans = 0; for x in 1..=n { if x % 3 == 0 || x % 5 == 0 || x % 7 == 0 { ans += x; } } ans } }
2,652
Sum Multiples
Easy
<p>Given a positive integer <code>n</code>, find the sum of all integers in the range <code>[1, n]</code> <strong>inclusive</strong> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code>.</p> <p>Return <em>an integer denoting the sum of all numbers in the given range satisfying&nbsp;the constraint.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 21 <strong>Explanation:</strong> Numbers in the range <code>[1, 7]</code> that are divisible by <code>3</code>, <code>5,</code> or <code>7 </code>are <code>3, 5, 6, 7</code>. The sum of these numbers is <code>21</code>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 40 <strong>Explanation:</strong> Numbers in the range <code>[1, 10] that are</code> divisible by <code>3</code>, <code>5,</code> or <code>7</code> are <code>3, 5, 6, 7, 9, 10</code>. The sum of these numbers is 40. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 30 <strong>Explanation:</strong> Numbers in the range <code>[1, 9]</code> that are divisible by <code>3</code>, <code>5</code>, or <code>7</code> are <code>3, 5, 6, 7, 9</code>. The sum of these numbers is <code>30</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li> </ul>
Math
TypeScript
function sumOfMultiples(n: number): number { let ans = 0; for (let x = 1; x <= n; ++x) { if (x % 3 === 0 || x % 5 === 0 || x % 7 === 0) { ans += x; } } return ans; }
2,653
Sliding Subarray Beauty
Medium
<p>Given an integer array <code>nums</code> containing <code>n</code> integers, find the <strong>beauty</strong> of each subarray of size <code>k</code>.</p> <p>The <strong>beauty</strong> of a subarray is the <code>x<sup>th</sup></code><strong> smallest integer </strong>in the subarray if it is <strong>negative</strong>, or <code>0</code> if there are fewer than <code>x</code> negative integers.</p> <p>Return <em>an integer array containing </em><code>n - k + 1</code> <em>integers, which denote the </em><strong>beauty</strong><em> of the subarrays <strong>in order</strong> from the first index in the array.</em></p> <ul> <li> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2 <strong>Output:</strong> [-1,-2,-2] <strong>Explanation:</strong> There are 3 subarrays with size k = 3. The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp; The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp; The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2 <strong>Output:</strong> [-1,-2,-3,-4] <strong>Explanation:</strong> There are 4 subarrays with size k = 2. For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1. For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2. For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3. For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1 <strong>Output:</strong> [-3,0,-3,-3,-3] <strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong> For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[1, 2]</code>, there is no negative integer so the beauty is 0. For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length&nbsp;</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= x &lt;= k&nbsp;</code></li> <li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li> </ul>
Array; Hash Table; Sliding Window
C++
class Solution { public: vector<int> getSubarrayBeauty(vector<int>& nums, int k, int x) { int n = nums.size(); int cnt[101]{}; for (int i = 0; i < k; ++i) { ++cnt[nums[i] + 50]; } vector<int> ans(n - k + 1); auto f = [&](int x) { int s = 0; for (int i = 0; i < 50; ++i) { s += cnt[i]; if (s >= x) { return i - 50; } } return 0; }; ans[0] = f(x); for (int i = k, j = 1; i < n; ++i) { ++cnt[nums[i] + 50]; --cnt[nums[i - k] + 50]; ans[j++] = f(x); } return ans; } };
2,653
Sliding Subarray Beauty
Medium
<p>Given an integer array <code>nums</code> containing <code>n</code> integers, find the <strong>beauty</strong> of each subarray of size <code>k</code>.</p> <p>The <strong>beauty</strong> of a subarray is the <code>x<sup>th</sup></code><strong> smallest integer </strong>in the subarray if it is <strong>negative</strong>, or <code>0</code> if there are fewer than <code>x</code> negative integers.</p> <p>Return <em>an integer array containing </em><code>n - k + 1</code> <em>integers, which denote the </em><strong>beauty</strong><em> of the subarrays <strong>in order</strong> from the first index in the array.</em></p> <ul> <li> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2 <strong>Output:</strong> [-1,-2,-2] <strong>Explanation:</strong> There are 3 subarrays with size k = 3. The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp; The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp; The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2 <strong>Output:</strong> [-1,-2,-3,-4] <strong>Explanation:</strong> There are 4 subarrays with size k = 2. For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1. For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2. For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3. For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1 <strong>Output:</strong> [-3,0,-3,-3,-3] <strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong> For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[1, 2]</code>, there is no negative integer so the beauty is 0. For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length&nbsp;</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= x &lt;= k&nbsp;</code></li> <li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li> </ul>
Array; Hash Table; Sliding Window
Go
func getSubarrayBeauty(nums []int, k int, x int) []int { n := len(nums) cnt := [101]int{} for _, x := range nums[:k] { cnt[x+50]++ } ans := make([]int, n-k+1) f := func(x int) int { s := 0 for i := 0; i < 50; i++ { s += cnt[i] if s >= x { return i - 50 } } return 0 } ans[0] = f(x) for i, j := k, 1; i < n; i, j = i+1, j+1 { cnt[nums[i]+50]++ cnt[nums[i-k]+50]-- ans[j] = f(x) } return ans }
2,653
Sliding Subarray Beauty
Medium
<p>Given an integer array <code>nums</code> containing <code>n</code> integers, find the <strong>beauty</strong> of each subarray of size <code>k</code>.</p> <p>The <strong>beauty</strong> of a subarray is the <code>x<sup>th</sup></code><strong> smallest integer </strong>in the subarray if it is <strong>negative</strong>, or <code>0</code> if there are fewer than <code>x</code> negative integers.</p> <p>Return <em>an integer array containing </em><code>n - k + 1</code> <em>integers, which denote the </em><strong>beauty</strong><em> of the subarrays <strong>in order</strong> from the first index in the array.</em></p> <ul> <li> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2 <strong>Output:</strong> [-1,-2,-2] <strong>Explanation:</strong> There are 3 subarrays with size k = 3. The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp; The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp; The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2 <strong>Output:</strong> [-1,-2,-3,-4] <strong>Explanation:</strong> There are 4 subarrays with size k = 2. For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1. For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2. For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3. For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1 <strong>Output:</strong> [-3,0,-3,-3,-3] <strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong> For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[1, 2]</code>, there is no negative integer so the beauty is 0. For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length&nbsp;</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= x &lt;= k&nbsp;</code></li> <li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li> </ul>
Array; Hash Table; Sliding Window
Java
class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { int n = nums.length; int[] cnt = new int[101]; for (int i = 0; i < k; ++i) { ++cnt[nums[i] + 50]; } int[] ans = new int[n - k + 1]; ans[0] = f(cnt, x); for (int i = k, j = 1; i < n; ++i) { ++cnt[nums[i] + 50]; --cnt[nums[i - k] + 50]; ans[j++] = f(cnt, x); } return ans; } private int f(int[] cnt, int x) { int s = 0; for (int i = 0; i < 50; ++i) { s += cnt[i]; if (s >= x) { return i - 50; } } return 0; } }
2,653
Sliding Subarray Beauty
Medium
<p>Given an integer array <code>nums</code> containing <code>n</code> integers, find the <strong>beauty</strong> of each subarray of size <code>k</code>.</p> <p>The <strong>beauty</strong> of a subarray is the <code>x<sup>th</sup></code><strong> smallest integer </strong>in the subarray if it is <strong>negative</strong>, or <code>0</code> if there are fewer than <code>x</code> negative integers.</p> <p>Return <em>an integer array containing </em><code>n - k + 1</code> <em>integers, which denote the </em><strong>beauty</strong><em> of the subarrays <strong>in order</strong> from the first index in the array.</em></p> <ul> <li> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2 <strong>Output:</strong> [-1,-2,-2] <strong>Explanation:</strong> There are 3 subarrays with size k = 3. The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp; The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp; The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2 <strong>Output:</strong> [-1,-2,-3,-4] <strong>Explanation:</strong> There are 4 subarrays with size k = 2. For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1. For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2. For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3. For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1 <strong>Output:</strong> [-3,0,-3,-3,-3] <strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong> For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[1, 2]</code>, there is no negative integer so the beauty is 0. For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length&nbsp;</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= x &lt;= k&nbsp;</code></li> <li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li> </ul>
Array; Hash Table; Sliding Window
Python
class Solution: def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: def f(x: int) -> int: s = 0 for i in range(50): s += cnt[i] if s >= x: return i - 50 return 0 cnt = [0] * 101 for v in nums[:k]: cnt[v + 50] += 1 ans = [f(x)] for i in range(k, len(nums)): cnt[nums[i] + 50] += 1 cnt[nums[i - k] + 50] -= 1 ans.append(f(x)) return ans
2,653
Sliding Subarray Beauty
Medium
<p>Given an integer array <code>nums</code> containing <code>n</code> integers, find the <strong>beauty</strong> of each subarray of size <code>k</code>.</p> <p>The <strong>beauty</strong> of a subarray is the <code>x<sup>th</sup></code><strong> smallest integer </strong>in the subarray if it is <strong>negative</strong>, or <code>0</code> if there are fewer than <code>x</code> negative integers.</p> <p>Return <em>an integer array containing </em><code>n - k + 1</code> <em>integers, which denote the </em><strong>beauty</strong><em> of the subarrays <strong>in order</strong> from the first index in the array.</em></p> <ul> <li> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2 <strong>Output:</strong> [-1,-2,-2] <strong>Explanation:</strong> There are 3 subarrays with size k = 3. The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp; The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp; The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2 <strong>Output:</strong> [-1,-2,-3,-4] <strong>Explanation:</strong> There are 4 subarrays with size k = 2. For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1. For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2. For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3. For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1 <strong>Output:</strong> [-3,0,-3,-3,-3] <strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong> For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[1, 2]</code>, there is no negative integer so the beauty is 0. For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3. For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length&nbsp;</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= x &lt;= k&nbsp;</code></li> <li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li> </ul>
Array; Hash Table; Sliding Window
TypeScript
function getSubarrayBeauty(nums: number[], k: number, x: number): number[] { const n = nums.length; const cnt: number[] = new Array(101).fill(0); for (let i = 0; i < k; ++i) { ++cnt[nums[i] + 50]; } const ans: number[] = new Array(n - k + 1); const f = (x: number): number => { let s = 0; for (let i = 0; i < 50; ++i) { s += cnt[i]; if (s >= x) { return i - 50; } } return 0; }; ans[0] = f(x); for (let i = k, j = 1; i < n; ++i, ++j) { cnt[nums[i] + 50]++; cnt[nums[i - k] + 50]--; ans[j] = f(x); } return ans; }
2,654
Minimum Number of Operations to Make All Array Elements Equal to 1
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;array <code>nums</code> consisiting of <strong>positive</strong> integers. You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Select an index <code>i</code> such that <code>0 &lt;= i &lt; n - 1</code> and replace either of&nbsp;<code>nums[i]</code> or <code>nums[i+1]</code> with their gcd value.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>1</code>. If it is impossible, return <code>-1</code>.</p> <p>The gcd of two integers is the greatest common divisor of the two integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,10,6,14] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make all the elements equal to 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Number Theory
C++
class Solution { public: int minOperations(vector<int>& nums) { int n = nums.size(); int cnt = 0; for (int x : nums) { if (x == 1) { ++cnt; } } if (cnt) { return n - cnt; } int mi = n + 1; for (int i = 0; i < n; ++i) { int g = 0; for (int j = i; j < n; ++j) { g = gcd(g, nums[j]); if (g == 1) { mi = min(mi, j - i + 1); } } } return mi > n ? -1 : n - 1 + mi - 1; } };
2,654
Minimum Number of Operations to Make All Array Elements Equal to 1
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;array <code>nums</code> consisiting of <strong>positive</strong> integers. You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Select an index <code>i</code> such that <code>0 &lt;= i &lt; n - 1</code> and replace either of&nbsp;<code>nums[i]</code> or <code>nums[i+1]</code> with their gcd value.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>1</code>. If it is impossible, return <code>-1</code>.</p> <p>The gcd of two integers is the greatest common divisor of the two integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,10,6,14] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make all the elements equal to 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Number Theory
Go
func minOperations(nums []int) int { n := len(nums) cnt := 0 for _, x := range nums { if x == 1 { cnt++ } } if cnt > 0 { return n - cnt } mi := n + 1 for i := 0; i < n; i++ { g := 0 for j := i; j < n; j++ { g = gcd(g, nums[j]) if g == 1 { mi = min(mi, j-i+1) } } } if mi > n { return -1 } return n - 1 + mi - 1 } func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) }
2,654
Minimum Number of Operations to Make All Array Elements Equal to 1
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;array <code>nums</code> consisiting of <strong>positive</strong> integers. You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Select an index <code>i</code> such that <code>0 &lt;= i &lt; n - 1</code> and replace either of&nbsp;<code>nums[i]</code> or <code>nums[i+1]</code> with their gcd value.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>1</code>. If it is impossible, return <code>-1</code>.</p> <p>The gcd of two integers is the greatest common divisor of the two integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,10,6,14] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make all the elements equal to 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Number Theory
Java
class Solution { public int minOperations(int[] nums) { int n = nums.length; int cnt = 0; for (int x : nums) { if (x == 1) { ++cnt; } } if (cnt > 0) { return n - cnt; } int mi = n + 1; for (int i = 0; i < n; ++i) { int g = 0; for (int j = i; j < n; ++j) { g = gcd(g, nums[j]); if (g == 1) { mi = Math.min(mi, j - i + 1); } } } return mi > n ? -1 : n - 1 + mi - 1; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
2,654
Minimum Number of Operations to Make All Array Elements Equal to 1
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;array <code>nums</code> consisiting of <strong>positive</strong> integers. You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Select an index <code>i</code> such that <code>0 &lt;= i &lt; n - 1</code> and replace either of&nbsp;<code>nums[i]</code> or <code>nums[i+1]</code> with their gcd value.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>1</code>. If it is impossible, return <code>-1</code>.</p> <p>The gcd of two integers is the greatest common divisor of the two integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,10,6,14] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make all the elements equal to 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Number Theory
Python
class Solution: def minOperations(self, nums: List[int]) -> int: n = len(nums) cnt = nums.count(1) if cnt: return n - cnt mi = n + 1 for i in range(n): g = 0 for j in range(i, n): g = gcd(g, nums[j]) if g == 1: mi = min(mi, j - i + 1) return -1 if mi > n else n - 1 + mi - 1