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,563
Count the Number of Fair Pairs
Medium
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p> <p>A pair <code>(i, j)</code> is <b>fair </b>if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code>, and</li> <li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is a single fair pair: (2,3). </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>nums.length == n</code></li> <li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Go
func countFairPairs(nums []int, lower int, upper int) (ans int64) { sort.Ints(nums) for i, x := range nums { j := sort.Search(len(nums), func(h int) bool { return h > i && nums[h] >= lower-x }) k := sort.Search(len(nums), func(h int) bool { return h > i && nums[h] >= upper-x+1 }) ans += int64(k - j) } return }
2,563
Count the Number of Fair Pairs
Medium
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p> <p>A pair <code>(i, j)</code> is <b>fair </b>if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code>, and</li> <li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is a single fair pair: (2,3). </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>nums.length == n</code></li> <li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Java
class Solution { public long countFairPairs(int[] nums, int lower, int upper) { Arrays.sort(nums); long ans = 0; int n = nums.length; for (int i = 0; i < n; ++i) { int j = search(nums, lower - nums[i], i + 1); int k = search(nums, upper - nums[i] + 1, i + 1); ans += k - j; } return ans; } private int search(int[] nums, int x, int left) { int right = nums.length; while (left < right) { int mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } }
2,563
Count the Number of Fair Pairs
Medium
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p> <p>A pair <code>(i, j)</code> is <b>fair </b>if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code>, and</li> <li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is a single fair pair: (2,3). </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>nums.length == n</code></li> <li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Python
class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: nums.sort() ans = 0 for i, x in enumerate(nums): j = bisect_left(nums, lower - x, lo=i + 1) k = bisect_left(nums, upper - x + 1, lo=i + 1) ans += k - j return ans
2,563
Count the Number of Fair Pairs
Medium
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p> <p>A pair <code>(i, j)</code> is <b>fair </b>if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code>, and</li> <li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is a single fair pair: (2,3). </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>nums.length == n</code></li> <li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
TypeScript
function countFairPairs(nums: number[], lower: number, upper: number): number { const search = (x: number, l: number): number => { let r = nums.length; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; nums.sort((a, b) => a - b); let ans = 0; for (let i = 0; i < nums.length; ++i) { const j = search(lower - nums[i], i + 1); const k = search(upper - nums[i] + 1, i + 1); ans += k - j; } return ans; }
2,564
Substring XOR Queries
Medium
<p>You are given a <strong>binary string</strong> <code>s</code>, and a <strong>2D</strong> integer array <code>queries</code> where <code>queries[i] = [first<sub>i</sub>, second<sub>i</sub>]</code>.</p> <p>For the <code>i<sup>th</sup></code> query, find the <strong>shortest substring</strong> of <code>s</code> whose <strong>decimal value</strong>, <code>val</code>, yields <code>second<sub>i</sub></code> when <strong>bitwise XORed</strong> with <code>first<sub>i</sub></code>. In other words, <code>val ^ first<sub>i</sub> == second<sub>i</sub></code>.</p> <p>The answer to the <code>i<sup>th</sup></code> query is the endpoints (<strong>0-indexed</strong>) of the substring <code>[left<sub>i</sub>, right<sub>i</sub>]</code> or <code>[-1, -1]</code> if no such substring exists. If there are multiple answers, choose the one with the <strong>minimum</strong> <code>left<sub>i</sub></code>.</p> <p><em>Return an array</em> <code>ans</code> <em>where</em> <code>ans[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</em></p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;101101&quot;, queries = [[0,5],[1,2]] <strong>Output:</strong> [[0,2],[2,3]] <strong>Explanation:</strong> For the first query the substring in range <code>[0,2]</code> is <strong>&quot;101&quot;</strong> which has a decimal value of <strong><code>5</code></strong>, and <strong><code>5 ^ 0 = 5</code></strong>, hence the answer to the first query is <code>[0,2]</code>. In the second query, the substring in range <code>[2,3]</code> is <strong>&quot;11&quot;,</strong> and has a decimal value of <strong>3</strong>, and <strong>3<code> ^ 1 = 2</code></strong>.&nbsp;So, <code>[2,3]</code> is returned for the second query. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot;, queries = [[12,8]] <strong>Output:</strong> [[-1,-1]] <strong>Explanation:</strong> In this example there is no substring that answers the query, hence <code>[-1,-1] is returned</code>. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;1&quot;, queries = [[4,5]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> For this example, the substring in range <code>[0,0]</code> has a decimal value of <strong><code>1</code></strong>, and <strong><code>1 ^ 4 = 5</code></strong>. So, the answer is <code>[0,0]</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= first<sub>i</sub>, second<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; String
C++
class Solution { public: vector<vector<int>> substringXorQueries(string s, vector<vector<int>>& queries) { unordered_map<int, vector<int>> d; int n = s.size(); for (int i = 0; i < n; ++i) { int x = 0; for (int j = 0; j < 32 && i + j < n; ++j) { x = x << 1 | (s[i + j] - '0'); if (!d.count(x)) { d[x] = {i, i + j}; } if (x == 0) { break; } } } vector<vector<int>> ans; for (auto& q : queries) { int first = q[0], second = q[1]; int val = first ^ second; if (d.count(val)) { ans.emplace_back(d[val]); } else { ans.push_back({-1, -1}); } } return ans; } };
2,564
Substring XOR Queries
Medium
<p>You are given a <strong>binary string</strong> <code>s</code>, and a <strong>2D</strong> integer array <code>queries</code> where <code>queries[i] = [first<sub>i</sub>, second<sub>i</sub>]</code>.</p> <p>For the <code>i<sup>th</sup></code> query, find the <strong>shortest substring</strong> of <code>s</code> whose <strong>decimal value</strong>, <code>val</code>, yields <code>second<sub>i</sub></code> when <strong>bitwise XORed</strong> with <code>first<sub>i</sub></code>. In other words, <code>val ^ first<sub>i</sub> == second<sub>i</sub></code>.</p> <p>The answer to the <code>i<sup>th</sup></code> query is the endpoints (<strong>0-indexed</strong>) of the substring <code>[left<sub>i</sub>, right<sub>i</sub>]</code> or <code>[-1, -1]</code> if no such substring exists. If there are multiple answers, choose the one with the <strong>minimum</strong> <code>left<sub>i</sub></code>.</p> <p><em>Return an array</em> <code>ans</code> <em>where</em> <code>ans[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</em></p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;101101&quot;, queries = [[0,5],[1,2]] <strong>Output:</strong> [[0,2],[2,3]] <strong>Explanation:</strong> For the first query the substring in range <code>[0,2]</code> is <strong>&quot;101&quot;</strong> which has a decimal value of <strong><code>5</code></strong>, and <strong><code>5 ^ 0 = 5</code></strong>, hence the answer to the first query is <code>[0,2]</code>. In the second query, the substring in range <code>[2,3]</code> is <strong>&quot;11&quot;,</strong> and has a decimal value of <strong>3</strong>, and <strong>3<code> ^ 1 = 2</code></strong>.&nbsp;So, <code>[2,3]</code> is returned for the second query. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot;, queries = [[12,8]] <strong>Output:</strong> [[-1,-1]] <strong>Explanation:</strong> In this example there is no substring that answers the query, hence <code>[-1,-1] is returned</code>. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;1&quot;, queries = [[4,5]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> For this example, the substring in range <code>[0,0]</code> has a decimal value of <strong><code>1</code></strong>, and <strong><code>1 ^ 4 = 5</code></strong>. So, the answer is <code>[0,0]</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= first<sub>i</sub>, second<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; String
Go
func substringXorQueries(s string, queries [][]int) (ans [][]int) { d := map[int][]int{} for i := range s { x := 0 for j := 0; j < 32 && i+j < len(s); j++ { x = x<<1 | int(s[i+j]-'0') if _, ok := d[x]; !ok { d[x] = []int{i, i + j} } if x == 0 { break } } } for _, q := range queries { first, second := q[0], q[1] val := first ^ second if v, ok := d[val]; ok { ans = append(ans, v) } else { ans = append(ans, []int{-1, -1}) } } return }
2,564
Substring XOR Queries
Medium
<p>You are given a <strong>binary string</strong> <code>s</code>, and a <strong>2D</strong> integer array <code>queries</code> where <code>queries[i] = [first<sub>i</sub>, second<sub>i</sub>]</code>.</p> <p>For the <code>i<sup>th</sup></code> query, find the <strong>shortest substring</strong> of <code>s</code> whose <strong>decimal value</strong>, <code>val</code>, yields <code>second<sub>i</sub></code> when <strong>bitwise XORed</strong> with <code>first<sub>i</sub></code>. In other words, <code>val ^ first<sub>i</sub> == second<sub>i</sub></code>.</p> <p>The answer to the <code>i<sup>th</sup></code> query is the endpoints (<strong>0-indexed</strong>) of the substring <code>[left<sub>i</sub>, right<sub>i</sub>]</code> or <code>[-1, -1]</code> if no such substring exists. If there are multiple answers, choose the one with the <strong>minimum</strong> <code>left<sub>i</sub></code>.</p> <p><em>Return an array</em> <code>ans</code> <em>where</em> <code>ans[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</em></p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;101101&quot;, queries = [[0,5],[1,2]] <strong>Output:</strong> [[0,2],[2,3]] <strong>Explanation:</strong> For the first query the substring in range <code>[0,2]</code> is <strong>&quot;101&quot;</strong> which has a decimal value of <strong><code>5</code></strong>, and <strong><code>5 ^ 0 = 5</code></strong>, hence the answer to the first query is <code>[0,2]</code>. In the second query, the substring in range <code>[2,3]</code> is <strong>&quot;11&quot;,</strong> and has a decimal value of <strong>3</strong>, and <strong>3<code> ^ 1 = 2</code></strong>.&nbsp;So, <code>[2,3]</code> is returned for the second query. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot;, queries = [[12,8]] <strong>Output:</strong> [[-1,-1]] <strong>Explanation:</strong> In this example there is no substring that answers the query, hence <code>[-1,-1] is returned</code>. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;1&quot;, queries = [[4,5]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> For this example, the substring in range <code>[0,0]</code> has a decimal value of <strong><code>1</code></strong>, and <strong><code>1 ^ 4 = 5</code></strong>. So, the answer is <code>[0,0]</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= first<sub>i</sub>, second<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; String
Java
class Solution { public int[][] substringXorQueries(String s, int[][] queries) { Map<Integer, int[]> d = new HashMap<>(); int n = s.length(); for (int i = 0; i < n; ++i) { int x = 0; for (int j = 0; j < 32 && i + j < n; ++j) { x = x << 1 | (s.charAt(i + j) - '0'); d.putIfAbsent(x, new int[] {i, i + j}); if (x == 0) { break; } } } int m = queries.length; int[][] ans = new int[m][2]; for (int i = 0; i < m; ++i) { int first = queries[i][0], second = queries[i][1]; int val = first ^ second; ans[i] = d.getOrDefault(val, new int[] {-1, -1}); } return ans; } }
2,564
Substring XOR Queries
Medium
<p>You are given a <strong>binary string</strong> <code>s</code>, and a <strong>2D</strong> integer array <code>queries</code> where <code>queries[i] = [first<sub>i</sub>, second<sub>i</sub>]</code>.</p> <p>For the <code>i<sup>th</sup></code> query, find the <strong>shortest substring</strong> of <code>s</code> whose <strong>decimal value</strong>, <code>val</code>, yields <code>second<sub>i</sub></code> when <strong>bitwise XORed</strong> with <code>first<sub>i</sub></code>. In other words, <code>val ^ first<sub>i</sub> == second<sub>i</sub></code>.</p> <p>The answer to the <code>i<sup>th</sup></code> query is the endpoints (<strong>0-indexed</strong>) of the substring <code>[left<sub>i</sub>, right<sub>i</sub>]</code> or <code>[-1, -1]</code> if no such substring exists. If there are multiple answers, choose the one with the <strong>minimum</strong> <code>left<sub>i</sub></code>.</p> <p><em>Return an array</em> <code>ans</code> <em>where</em> <code>ans[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</em></p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;101101&quot;, queries = [[0,5],[1,2]] <strong>Output:</strong> [[0,2],[2,3]] <strong>Explanation:</strong> For the first query the substring in range <code>[0,2]</code> is <strong>&quot;101&quot;</strong> which has a decimal value of <strong><code>5</code></strong>, and <strong><code>5 ^ 0 = 5</code></strong>, hence the answer to the first query is <code>[0,2]</code>. In the second query, the substring in range <code>[2,3]</code> is <strong>&quot;11&quot;,</strong> and has a decimal value of <strong>3</strong>, and <strong>3<code> ^ 1 = 2</code></strong>.&nbsp;So, <code>[2,3]</code> is returned for the second query. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot;, queries = [[12,8]] <strong>Output:</strong> [[-1,-1]] <strong>Explanation:</strong> In this example there is no substring that answers the query, hence <code>[-1,-1] is returned</code>. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;1&quot;, queries = [[4,5]] <strong>Output:</strong> [[0,0]] <strong>Explanation:</strong> For this example, the substring in range <code>[0,0]</code> has a decimal value of <strong><code>1</code></strong>, and <strong><code>1 ^ 4 = 5</code></strong>. So, the answer is <code>[0,0]</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= first<sub>i</sub>, second<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Hash Table; String
Python
class Solution: def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: d = {} n = len(s) for i in range(n): x = 0 for j in range(32): if i + j >= n: break x = x << 1 | int(s[i + j]) if x not in d: d[x] = [i, i + j] if x == 0: break return [d.get(first ^ second, [-1, -1]) for first, second in queries]
2,565
Subsequence With the Minimum Score
Hard
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>You are allowed to remove any number of characters from the string <code>t</code>.</p> <p>The score of the string is <code>0</code> if no characters are removed from the string <code>t</code>, otherwise:</p> <ul> <li>Let <code>left</code> be the minimum index among all removed characters.</li> <li>Let <code>right</code> be the maximum index among all removed characters.</li> </ul> <p>Then the score of the string is <code>right - left + 1</code>.</p> <p>Return <em>the minimum possible score to make </em><code>t</code><em>&nbsp;a subsequence of </em><code>s</code><em>.</em></p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abacaba&quot;, t = &quot;bzaa&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we remove the character &quot;z&quot; at index 1 (0-indexed). The string t becomes &quot;baa&quot; which is a subsequence of the string &quot;abacaba&quot; and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cde&quot;, t = &quot;xyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we remove characters &quot;x&quot;, &quot;y&quot; and &quot;z&quot; at indices 0, 1, and 2 (0-indexed). The string t becomes &quot;&quot; which is a subsequence of the string &quot;cde&quot; and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English letters.</li> </ul>
Two Pointers; String; Binary Search
C++
class Solution { public: int minimumScore(string s, string t) { int m = s.size(), n = t.size(); vector<int> f(n, 1e6); vector<int> g(n, -1); for (int i = 0, j = 0; i < m && j < n; ++i) { if (s[i] == t[j]) { f[j] = i; ++j; } } for (int i = m - 1, j = n - 1; i >= 0 && j >= 0; --i) { if (s[i] == t[j]) { g[j] = i; --j; } } auto check = [&](int len) { for (int k = 0; k < n; ++k) { int i = k - 1, j = k + len; int l = i >= 0 ? f[i] : -1; int r = j < n ? g[j] : m + 1; if (l < r) { return true; } } return false; }; int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
2,565
Subsequence With the Minimum Score
Hard
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>You are allowed to remove any number of characters from the string <code>t</code>.</p> <p>The score of the string is <code>0</code> if no characters are removed from the string <code>t</code>, otherwise:</p> <ul> <li>Let <code>left</code> be the minimum index among all removed characters.</li> <li>Let <code>right</code> be the maximum index among all removed characters.</li> </ul> <p>Then the score of the string is <code>right - left + 1</code>.</p> <p>Return <em>the minimum possible score to make </em><code>t</code><em>&nbsp;a subsequence of </em><code>s</code><em>.</em></p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abacaba&quot;, t = &quot;bzaa&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we remove the character &quot;z&quot; at index 1 (0-indexed). The string t becomes &quot;baa&quot; which is a subsequence of the string &quot;abacaba&quot; and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cde&quot;, t = &quot;xyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we remove characters &quot;x&quot;, &quot;y&quot; and &quot;z&quot; at indices 0, 1, and 2 (0-indexed). The string t becomes &quot;&quot; which is a subsequence of the string &quot;cde&quot; and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English letters.</li> </ul>
Two Pointers; String; Binary Search
Go
func minimumScore(s string, t string) int { m, n := len(s), len(t) f := make([]int, n) g := make([]int, n) for i := range f { f[i] = 1 << 30 g[i] = -1 } for i, j := 0, 0; i < m && j < n; i++ { if s[i] == t[j] { f[j] = i j++ } } for i, j := m-1, n-1; i >= 0 && j >= 0; i-- { if s[i] == t[j] { g[j] = i j-- } } return sort.Search(n+1, func(x int) bool { for k := 0; k < n; k++ { i, j := k-1, k+x l, r := -1, m+1 if i >= 0 { l = f[i] } if j < n { r = g[j] } if l < r { return true } } return false }) }
2,565
Subsequence With the Minimum Score
Hard
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>You are allowed to remove any number of characters from the string <code>t</code>.</p> <p>The score of the string is <code>0</code> if no characters are removed from the string <code>t</code>, otherwise:</p> <ul> <li>Let <code>left</code> be the minimum index among all removed characters.</li> <li>Let <code>right</code> be the maximum index among all removed characters.</li> </ul> <p>Then the score of the string is <code>right - left + 1</code>.</p> <p>Return <em>the minimum possible score to make </em><code>t</code><em>&nbsp;a subsequence of </em><code>s</code><em>.</em></p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abacaba&quot;, t = &quot;bzaa&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we remove the character &quot;z&quot; at index 1 (0-indexed). The string t becomes &quot;baa&quot; which is a subsequence of the string &quot;abacaba&quot; and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cde&quot;, t = &quot;xyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we remove characters &quot;x&quot;, &quot;y&quot; and &quot;z&quot; at indices 0, 1, and 2 (0-indexed). The string t becomes &quot;&quot; which is a subsequence of the string &quot;cde&quot; and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English letters.</li> </ul>
Two Pointers; String; Binary Search
Java
class Solution { private int m; private int n; private int[] f; private int[] g; public int minimumScore(String s, String t) { m = s.length(); n = t.length(); f = new int[n]; g = new int[n]; for (int i = 0; i < n; ++i) { f[i] = 1 << 30; g[i] = -1; } for (int i = 0, j = 0; i < m && j < n; ++i) { if (s.charAt(i) == t.charAt(j)) { f[j] = i; ++j; } } for (int i = m - 1, j = n - 1; i >= 0 && j >= 0; --i) { if (s.charAt(i) == t.charAt(j)) { g[j] = i; --j; } } int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(int len) { for (int k = 0; k < n; ++k) { int i = k - 1, j = k + len; int l = i >= 0 ? f[i] : -1; int r = j < n ? g[j] : m + 1; if (l < r) { return true; } } return false; } }
2,565
Subsequence With the Minimum Score
Hard
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>You are allowed to remove any number of characters from the string <code>t</code>.</p> <p>The score of the string is <code>0</code> if no characters are removed from the string <code>t</code>, otherwise:</p> <ul> <li>Let <code>left</code> be the minimum index among all removed characters.</li> <li>Let <code>right</code> be the maximum index among all removed characters.</li> </ul> <p>Then the score of the string is <code>right - left + 1</code>.</p> <p>Return <em>the minimum possible score to make </em><code>t</code><em>&nbsp;a subsequence of </em><code>s</code><em>.</em></p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abacaba&quot;, t = &quot;bzaa&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, we remove the character &quot;z&quot; at index 1 (0-indexed). The string t becomes &quot;baa&quot; which is a subsequence of the string &quot;abacaba&quot; and the score is 1 - 1 + 1 = 1. It can be proven that 1 is the minimum score that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cde&quot;, t = &quot;xyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, we remove characters &quot;x&quot;, &quot;y&quot; and &quot;z&quot; at indices 0, 1, and 2 (0-indexed). The string t becomes &quot;&quot; which is a subsequence of the string &quot;cde&quot; and the score is 2 - 0 + 1 = 3. It can be proven that 3 is the minimum score that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English letters.</li> </ul>
Two Pointers; String; Binary Search
Python
class Solution: def minimumScore(self, s: str, t: str) -> int: def check(x): for k in range(n): i, j = k - 1, k + x l = f[i] if i >= 0 else -1 r = g[j] if j < n else m + 1 if l < r: return True return False m, n = len(s), len(t) f = [inf] * n g = [-1] * n i, j = 0, 0 while i < m and j < n: if s[i] == t[j]: f[j] = i j += 1 i += 1 i, j = m - 1, n - 1 while i >= 0 and j >= 0: if s[i] == t[j]: g[j] = i j -= 1 i -= 1 return bisect_left(range(n + 1), True, key=check)
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
C
int minMaxDifference(int num) { char s[12]; sprintf(s, "%d", num); int mi; { char tmp[12]; char t = s[0]; for (int i = 0; s[i]; i++) { tmp[i] = (s[i] == t) ? '0' : s[i]; } tmp[strlen(s)] = '\0'; mi = atoi(tmp); } for (int i = 0; s[i]; i++) { char c = s[i]; if (c != '9') { char tmp[12]; for (int j = 0; s[j]; j++) { tmp[j] = (s[j] == c) ? '9' : s[j]; } tmp[strlen(s)] = '\0'; return atoi(tmp) - mi; } } return num - mi; }
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
C++
class Solution { public: int minMaxDifference(int num) { string s = to_string(num); string t = s; char first = s[0]; for (char& c : s) { if (c == first) { c = '0'; } } int mi = stoi(s); for (int i = 0; i < t.size(); ++i) { if (t[i] != '9') { char second = t[i]; for (int j = i; j < t.size(); ++j) { if (t[j] == second) { t[j] = '9'; } } return stoi(t) - mi; } } return num - mi; } };
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
Go
func minMaxDifference(num int) int { s := []byte(strconv.Itoa(num)) first := s[0] for i := range s { if s[i] == first { s[i] = '0' } } mi, _ := strconv.Atoi(string(s)) t := []byte(strconv.Itoa(num)) for i := range t { if t[i] != '9' { second := t[i] for j := i; j < len(t); j++ { if t[j] == second { t[j] = '9' } } mx, _ := strconv.Atoi(string(t)) return mx - mi } } return num - mi }
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
Java
class Solution { public int minMaxDifference(int num) { String s = String.valueOf(num); int mi = Integer.parseInt(s.replace(s.charAt(0), '0')); for (char c : s.toCharArray()) { if (c != '9') { return Integer.parseInt(s.replace(c, '9')) - mi; } } return num - mi; } }
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
JavaScript
/** * @param {number} num * @return {number} */ var minMaxDifference = function (num) { const s = num.toString(); const mi = +s.replaceAll(s[0], '0'); for (const c of s) { if (c !== '9') { const mx = +s.replaceAll(c, '9'); return mx - mi; } } return num - mi; };
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
Python
class Solution: def minMaxDifference(self, num: int) -> int: s = str(num) mi = int(s.replace(s[0], '0')) for c in s: if c != '9': return int(s.replace(c, '9')) - mi return num - mi
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
Rust
impl Solution { pub fn min_max_difference(num: i32) -> i32 { let s = num.to_string(); let mi = s .replace(s.chars().next().unwrap(), "0") .parse::<i32>() .unwrap(); for c in s.chars() { if c != '9' { let mx = s.replace(c, "9").parse::<i32>().unwrap(); return mx - mi; } } num - mi } }
2,566
Maximum Difference by Remapping a Digit
Easy
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p> <p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li> <li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li> <li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li> <li>The resulting number after remapping can contain leading zeroes.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> num = 11891 <strong>Output:</strong> 99009 <strong>Explanation:</strong> To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> num = 90 <strong>Output:</strong> 99 <strong>Explanation:</strong> The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li> </ul>
Greedy; Math
TypeScript
function minMaxDifference(num: number): number { const s = num.toString(); const mi = +s.replaceAll(s[0], '0'); for (const c of s) { if (c !== '9') { const mx = +s.replaceAll(c, '9'); return mx - mi; } } return num - mi; }
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
C
#define min(a, b) (((a) < (b)) ? (a) : (b)) int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; } int minimizeSum(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), cmp); return min(nums[numsSize - 1] - nums[2], min(nums[numsSize - 2] - nums[1], nums[numsSize - 3] - nums[0])); }
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int minimizeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); return min({nums[n - 1] - nums[2], nums[n - 2] - nums[1], nums[n - 3] - nums[0]}); } };
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func minimizeSum(nums []int) int { sort.Ints(nums) n := len(nums) return min(nums[n-1]-nums[2], min(nums[n-2]-nums[1], nums[n-3]-nums[0])) }
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int minimizeSum(int[] nums) { Arrays.sort(nums); int n = nums.length; int a = nums[n - 1] - nums[2]; int b = nums[n - 2] - nums[1]; int c = nums[n - 3] - nums[0]; return Math.min(a, Math.min(b, c)); } }
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minimizeSum(self, nums: List[int]) -> int: nums.sort() return min(nums[-1] - nums[2], nums[-2] - nums[1], nums[-3] - nums[0])
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Rust
impl Solution { pub fn minimize_sum(mut nums: Vec<i32>) -> i32 { nums.sort(); let n = nums.len(); (nums[n - 1] - nums[2]) .min(nums[n - 2] - nums[1]) .min(nums[n - 3] - nums[0]) } }
2,567
Minimum Score by Changing Two Elements
Medium
<p>You are given an integer array <code>nums</code>.</p> <ul> <li>The <strong>low</strong> score of <code>nums</code> is the <strong>minimum</strong> absolute difference between any two integers.</li> <li>The <strong>high</strong> score of <code>nums</code> is the <strong>maximum</strong> absolute difference between any two integers.</li> <li>The <strong>score</strong> of <code>nums</code> is the sum of the <strong>high</strong> and <strong>low</strong> scores.</li> </ul> <p>Return the <strong>minimum score</strong> after <strong>changing two elements</strong> of <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,7,8,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[0]</code> and <code>nums[1]</code> to be 6 so that <code>nums</code> becomes [6,6,7,8,5].</li> <li>The low score is the minimum absolute difference: |6 - 6| = 0.</li> <li>The high score is the maximum absolute difference: |8 - 5| = 3.</li> <li>The sum of high and low score is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Change <code>nums[1]</code> and <code>nums[2]</code> to 1 so that <code>nums</code> becomes [1,1,1].</li> <li>The sum of maximum absolute difference and minimum absolute difference is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minimizeSum(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; return Math.min(nums[n - 3] - nums[0], nums[n - 2] - nums[1], nums[n - 1] - nums[2]); }
2,568
Minimum Impossible OR
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;integer array <code>nums</code>.</p> <p>We say that an integer x is <strong>expressible</strong> from <code>nums</code> if there exist some integers <code>0 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt; ... &lt; index<sub>k</sub> &lt; nums.length</code> for which <code>nums[index<sub>1</sub>] | nums[index<sub>2</sub>] | ... | nums[index<sub>k</sub>] = x</code>. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of <code>nums</code>.</p> <p>Return <em>the minimum <strong>positive non-zero integer</strong>&nbsp;that is not </em><em>expressible from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,3,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can show that 1 is the smallest number that is not expressible. </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>
Bit Manipulation; Brainteaser; Array
C++
class Solution { public: int minImpossibleOR(vector<int>& nums) { unordered_set<int> s(nums.begin(), nums.end()); for (int i = 0;; ++i) { if (!s.count(1 << i)) { return 1 << i; } } } };
2,568
Minimum Impossible OR
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;integer array <code>nums</code>.</p> <p>We say that an integer x is <strong>expressible</strong> from <code>nums</code> if there exist some integers <code>0 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt; ... &lt; index<sub>k</sub> &lt; nums.length</code> for which <code>nums[index<sub>1</sub>] | nums[index<sub>2</sub>] | ... | nums[index<sub>k</sub>] = x</code>. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of <code>nums</code>.</p> <p>Return <em>the minimum <strong>positive non-zero integer</strong>&nbsp;that is not </em><em>expressible from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,3,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can show that 1 is the smallest number that is not expressible. </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>
Bit Manipulation; Brainteaser; Array
Go
func minImpossibleOR(nums []int) int { s := map[int]bool{} for _, x := range nums { s[x] = true } for i := 0; ; i++ { if !s[1<<i] { return 1 << i } } }
2,568
Minimum Impossible OR
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;integer array <code>nums</code>.</p> <p>We say that an integer x is <strong>expressible</strong> from <code>nums</code> if there exist some integers <code>0 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt; ... &lt; index<sub>k</sub> &lt; nums.length</code> for which <code>nums[index<sub>1</sub>] | nums[index<sub>2</sub>] | ... | nums[index<sub>k</sub>] = x</code>. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of <code>nums</code>.</p> <p>Return <em>the minimum <strong>positive non-zero integer</strong>&nbsp;that is not </em><em>expressible from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,3,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can show that 1 is the smallest number that is not expressible. </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>
Bit Manipulation; Brainteaser; Array
Java
class Solution { public int minImpossibleOR(int[] nums) { Set<Integer> s = new HashSet<>(); for (int x : nums) { s.add(x); } for (int i = 0;; ++i) { if (!s.contains(1 << i)) { return 1 << i; } } } }
2,568
Minimum Impossible OR
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;integer array <code>nums</code>.</p> <p>We say that an integer x is <strong>expressible</strong> from <code>nums</code> if there exist some integers <code>0 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt; ... &lt; index<sub>k</sub> &lt; nums.length</code> for which <code>nums[index<sub>1</sub>] | nums[index<sub>2</sub>] | ... | nums[index<sub>k</sub>] = x</code>. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of <code>nums</code>.</p> <p>Return <em>the minimum <strong>positive non-zero integer</strong>&nbsp;that is not </em><em>expressible from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,3,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can show that 1 is the smallest number that is not expressible. </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>
Bit Manipulation; Brainteaser; Array
Python
class Solution: def minImpossibleOR(self, nums: List[int]) -> int: s = set(nums) return next(1 << i for i in range(32) if 1 << i not in s)
2,568
Minimum Impossible OR
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;integer array <code>nums</code>.</p> <p>We say that an integer x is <strong>expressible</strong> from <code>nums</code> if there exist some integers <code>0 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt; ... &lt; index<sub>k</sub> &lt; nums.length</code> for which <code>nums[index<sub>1</sub>] | nums[index<sub>2</sub>] | ... | nums[index<sub>k</sub>] = x</code>. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of <code>nums</code>.</p> <p>Return <em>the minimum <strong>positive non-zero integer</strong>&nbsp;that is not </em><em>expressible from </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,3,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can show that 1 is the smallest number that is not expressible. </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>
Bit Manipulation; Brainteaser; Array
TypeScript
function minImpossibleOR(nums: number[]): number { const s: Set<number> = new Set(); for (const x of nums) { s.add(x); } for (let i = 0; ; ++i) { if (!s.has(1 << i)) { return 1 << i; } } }
2,569
Handling Sum Queries After Update
Hard
<p>You are given two <strong>0-indexed</strong> arrays <code>nums1</code> and <code>nums2</code> and a 2D array <code>queries</code> of queries. There are three types of queries:</p> <ol> <li>For a query of type 1, <code>queries[i]&nbsp;= [1, l, r]</code>. Flip the values from <code>0</code> to <code>1</code> and from <code>1</code> to <code>0</code> in <code>nums1</code>&nbsp;from index <code>l</code> to index <code>r</code>. Both <code>l</code> and <code>r</code> are <strong>0-indexed</strong>.</li> <li>For a query of type 2, <code>queries[i]&nbsp;= [2, p, 0]</code>. For every index <code>0 &lt;= i &lt; n</code>, set&nbsp;<code>nums2[i] =&nbsp;nums2[i]&nbsp;+ nums1[i]&nbsp;* p</code>.</li> <li>For a query of type 3, <code>queries[i]&nbsp;= [3, 0, 0]</code>. Find the sum of the elements in <code>nums2</code>.</li> </ol> <p>Return <em>an array containing all the answers to the third type&nbsp;queries.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] <strong>Output:</strong> [3] <strong>Explanation:</strong> After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] <strong>Output:</strong> [5] <strong>Explanation:</strong> After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length,nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length = nums2.length</code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">queries[i].length = 3</font></code></li> <li><code><font face="monospace">0 &lt;= l &lt;= r &lt;= nums1.length - 1</font></code></li> <li><code><font face="monospace">0 &lt;= p &lt;= 10<sup>6</sup></font></code></li> <li><code>0 &lt;= nums1[i] &lt;= 1</code></li> <li><code>0 &lt;= nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array
C++
class Node { public: int l = 0, r = 0; int s = 0, lazy = 0; }; class SegmentTree { public: SegmentTree(vector<int>& nums) { this->nums = nums; int n = nums.size(); tr.resize(n << 2); for (int i = 0; i < tr.size(); ++i) { tr[i] = new Node(); } build(1, 1, n); } void modify(int u, int l, int r) { if (tr[u]->l >= l && tr[u]->r <= r) { tr[u]->lazy ^= 1; tr[u]->s = tr[u]->r - tr[u]->l + 1 - tr[u]->s; return; } pushdown(u); int mid = (tr[u]->l + tr[u]->r) >> 1; if (l <= mid) { modify(u << 1, l, r); } if (r > mid) { modify(u << 1 | 1, l, r); } pushup(u); } int query(int u, int l, int r) { if (tr[u]->l >= l && tr[u]->r <= r) { return tr[u]->s; } pushdown(u); int mid = (tr[u]->l + tr[u]->r) >> 1; int res = 0; if (l <= mid) { res += query(u << 1, l, r); } if (r > mid) { res += query(u << 1 | 1, l, r); } return res; } private: vector<Node*> tr; vector<int> nums; void build(int u, int l, int r) { tr[u]->l = l; tr[u]->r = r; if (l == r) { tr[u]->s = nums[l - 1]; return; } int mid = (l + r) >> 1; build(u << 1, l, mid); build(u << 1 | 1, mid + 1, r); pushup(u); } void pushup(int u) { tr[u]->s = tr[u << 1]->s + tr[u << 1 | 1]->s; } void pushdown(int u) { if (tr[u]->lazy) { int mid = (tr[u]->l + tr[u]->r) >> 1; tr[u << 1]->s = mid - tr[u]->l + 1 - tr[u << 1]->s; tr[u << 1]->lazy ^= 1; tr[u << 1 | 1]->s = tr[u]->r - mid - tr[u << 1 | 1]->s; tr[u << 1 | 1]->lazy ^= 1; tr[u]->lazy ^= 1; } } }; class Solution { public: vector<long long> handleQuery(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) { SegmentTree* tree = new SegmentTree(nums1); long long s = 0; for (int& x : nums2) { s += x; } vector<long long> ans; for (auto& q : queries) { if (q[0] == 1) { tree->modify(1, q[1] + 1, q[2] + 1); } else if (q[0] == 2) { s += 1LL * q[1] * tree->query(1, 1, nums1.size()); } else { ans.push_back(s); } } return ans; } };
2,569
Handling Sum Queries After Update
Hard
<p>You are given two <strong>0-indexed</strong> arrays <code>nums1</code> and <code>nums2</code> and a 2D array <code>queries</code> of queries. There are three types of queries:</p> <ol> <li>For a query of type 1, <code>queries[i]&nbsp;= [1, l, r]</code>. Flip the values from <code>0</code> to <code>1</code> and from <code>1</code> to <code>0</code> in <code>nums1</code>&nbsp;from index <code>l</code> to index <code>r</code>. Both <code>l</code> and <code>r</code> are <strong>0-indexed</strong>.</li> <li>For a query of type 2, <code>queries[i]&nbsp;= [2, p, 0]</code>. For every index <code>0 &lt;= i &lt; n</code>, set&nbsp;<code>nums2[i] =&nbsp;nums2[i]&nbsp;+ nums1[i]&nbsp;* p</code>.</li> <li>For a query of type 3, <code>queries[i]&nbsp;= [3, 0, 0]</code>. Find the sum of the elements in <code>nums2</code>.</li> </ol> <p>Return <em>an array containing all the answers to the third type&nbsp;queries.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] <strong>Output:</strong> [3] <strong>Explanation:</strong> After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] <strong>Output:</strong> [5] <strong>Explanation:</strong> After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length,nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length = nums2.length</code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">queries[i].length = 3</font></code></li> <li><code><font face="monospace">0 &lt;= l &lt;= r &lt;= nums1.length - 1</font></code></li> <li><code><font face="monospace">0 &lt;= p &lt;= 10<sup>6</sup></font></code></li> <li><code>0 &lt;= nums1[i] &lt;= 1</code></li> <li><code>0 &lt;= nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array
Go
type node struct { l, r, s, lazy int } type segmentTree struct { nums []int tr []*node } func newSegmentTree(nums []int) *segmentTree { n := len(nums) tr := make([]*node, n<<2) for i := range tr { tr[i] = &node{} } t := &segmentTree{nums, tr} t.build(1, 1, n) return t } func (t *segmentTree) build(u, l, r int) { t.tr[u].l, t.tr[u].r = l, r if l == r { t.tr[u].s = t.nums[l-1] return } mid := (l + r) >> 1 t.build(u<<1, l, mid) t.build(u<<1|1, mid+1, r) t.pushup(u) } func (t *segmentTree) modify(u, l, r int) { if t.tr[u].l >= l && t.tr[u].r <= r { t.tr[u].lazy ^= 1 t.tr[u].s = t.tr[u].r - t.tr[u].l + 1 - t.tr[u].s return } t.pushdown(u) mid := (t.tr[u].l + t.tr[u].r) >> 1 if l <= mid { t.modify(u<<1, l, r) } if r > mid { t.modify(u<<1|1, l, r) } t.pushup(u) } func (t *segmentTree) query(u, l, r int) int { if t.tr[u].l >= l && t.tr[u].r <= r { return t.tr[u].s } t.pushdown(u) mid := (t.tr[u].l + t.tr[u].r) >> 1 res := 0 if l <= mid { res += t.query(u<<1, l, r) } if r > mid { res += t.query(u<<1|1, l, r) } return res } func (t *segmentTree) pushup(u int) { t.tr[u].s = t.tr[u<<1].s + t.tr[u<<1|1].s } func (t *segmentTree) pushdown(u int) { if t.tr[u].lazy == 1 { mid := (t.tr[u].l + t.tr[u].r) >> 1 t.tr[u<<1].s = mid - t.tr[u].l + 1 - t.tr[u<<1].s t.tr[u<<1].lazy ^= 1 t.tr[u<<1|1].s = t.tr[u].r - mid - t.tr[u<<1|1].s t.tr[u<<1|1].lazy ^= 1 t.tr[u].lazy ^= 1 } } func handleQuery(nums1 []int, nums2 []int, queries [][]int) (ans []int64) { tree := newSegmentTree(nums1) var s int64 for _, x := range nums2 { s += int64(x) } for _, q := range queries { if q[0] == 1 { tree.modify(1, q[1]+1, q[2]+1) } else if q[0] == 2 { s += int64(q[1] * tree.query(1, 1, len(nums1))) } else { ans = append(ans, s) } } return }
2,569
Handling Sum Queries After Update
Hard
<p>You are given two <strong>0-indexed</strong> arrays <code>nums1</code> and <code>nums2</code> and a 2D array <code>queries</code> of queries. There are three types of queries:</p> <ol> <li>For a query of type 1, <code>queries[i]&nbsp;= [1, l, r]</code>. Flip the values from <code>0</code> to <code>1</code> and from <code>1</code> to <code>0</code> in <code>nums1</code>&nbsp;from index <code>l</code> to index <code>r</code>. Both <code>l</code> and <code>r</code> are <strong>0-indexed</strong>.</li> <li>For a query of type 2, <code>queries[i]&nbsp;= [2, p, 0]</code>. For every index <code>0 &lt;= i &lt; n</code>, set&nbsp;<code>nums2[i] =&nbsp;nums2[i]&nbsp;+ nums1[i]&nbsp;* p</code>.</li> <li>For a query of type 3, <code>queries[i]&nbsp;= [3, 0, 0]</code>. Find the sum of the elements in <code>nums2</code>.</li> </ol> <p>Return <em>an array containing all the answers to the third type&nbsp;queries.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] <strong>Output:</strong> [3] <strong>Explanation:</strong> After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] <strong>Output:</strong> [5] <strong>Explanation:</strong> After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length,nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length = nums2.length</code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">queries[i].length = 3</font></code></li> <li><code><font face="monospace">0 &lt;= l &lt;= r &lt;= nums1.length - 1</font></code></li> <li><code><font face="monospace">0 &lt;= p &lt;= 10<sup>6</sup></font></code></li> <li><code>0 &lt;= nums1[i] &lt;= 1</code></li> <li><code>0 &lt;= nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array
Java
class Node { int l, r; int s, lazy; } class SegmentTree { private Node[] tr; private int[] nums; public SegmentTree(int[] nums) { int n = nums.length; this.nums = nums; tr = new Node[n << 2]; for (int i = 0; i < tr.length; ++i) { tr[i] = new Node(); } build(1, 1, n); } private void build(int u, int l, int r) { tr[u].l = l; tr[u].r = r; if (l == r) { tr[u].s = nums[l - 1]; return; } int mid = (l + r) >> 1; build(u << 1, l, mid); build(u << 1 | 1, mid + 1, r); pushup(u); } public void modify(int u, int l, int r) { if (tr[u].l >= l && tr[u].r <= r) { tr[u].lazy ^= 1; tr[u].s = tr[u].r - tr[u].l + 1 - tr[u].s; return; } pushdown(u); int mid = (tr[u].l + tr[u].r) >> 1; if (l <= mid) { modify(u << 1, l, r); } if (r > mid) { modify(u << 1 | 1, l, r); } pushup(u); } public int query(int u, int l, int r) { if (tr[u].l >= l && tr[u].r <= r) { return tr[u].s; } pushdown(u); int mid = (tr[u].l + tr[u].r) >> 1; int res = 0; if (l <= mid) { res += query(u << 1, l, r); } if (r > mid) { res += query(u << 1 | 1, l, r); } return res; } private void pushup(int u) { tr[u].s = tr[u << 1].s + tr[u << 1 | 1].s; } private void pushdown(int u) { if (tr[u].lazy == 1) { int mid = (tr[u].l + tr[u].r) >> 1; tr[u << 1].s = mid - tr[u].l + 1 - tr[u << 1].s; tr[u << 1].lazy ^= 1; tr[u << 1 | 1].s = tr[u].r - mid - tr[u << 1 | 1].s; tr[u << 1 | 1].lazy ^= 1; tr[u].lazy ^= 1; } } } class Solution { public long[] handleQuery(int[] nums1, int[] nums2, int[][] queries) { SegmentTree tree = new SegmentTree(nums1); long s = 0; for (int x : nums2) { s += x; } int m = 0; for (var q : queries) { if (q[0] == 3) { ++m; } } long[] ans = new long[m]; int i = 0; for (var q : queries) { if (q[0] == 1) { tree.modify(1, q[1] + 1, q[2] + 1); } else if (q[0] == 2) { s += 1L * q[1] * tree.query(1, 1, nums2.length); } else { ans[i++] = s; } } return ans; } }
2,569
Handling Sum Queries After Update
Hard
<p>You are given two <strong>0-indexed</strong> arrays <code>nums1</code> and <code>nums2</code> and a 2D array <code>queries</code> of queries. There are three types of queries:</p> <ol> <li>For a query of type 1, <code>queries[i]&nbsp;= [1, l, r]</code>. Flip the values from <code>0</code> to <code>1</code> and from <code>1</code> to <code>0</code> in <code>nums1</code>&nbsp;from index <code>l</code> to index <code>r</code>. Both <code>l</code> and <code>r</code> are <strong>0-indexed</strong>.</li> <li>For a query of type 2, <code>queries[i]&nbsp;= [2, p, 0]</code>. For every index <code>0 &lt;= i &lt; n</code>, set&nbsp;<code>nums2[i] =&nbsp;nums2[i]&nbsp;+ nums1[i]&nbsp;* p</code>.</li> <li>For a query of type 3, <code>queries[i]&nbsp;= [3, 0, 0]</code>. Find the sum of the elements in <code>nums2</code>.</li> </ol> <p>Return <em>an array containing all the answers to the third type&nbsp;queries.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]] <strong>Output:</strong> [3] <strong>Explanation:</strong> After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]] <strong>Output:</strong> [5] <strong>Explanation:</strong> After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length,nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length = nums2.length</code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">queries[i].length = 3</font></code></li> <li><code><font face="monospace">0 &lt;= l &lt;= r &lt;= nums1.length - 1</font></code></li> <li><code><font face="monospace">0 &lt;= p &lt;= 10<sup>6</sup></font></code></li> <li><code>0 &lt;= nums1[i] &lt;= 1</code></li> <li><code>0 &lt;= nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array
Python
class Node: def __init__(self): self.l = self.r = 0 self.s = self.lazy = 0 class SegmentTree: def __init__(self, nums): self.nums = nums n = len(nums) self.tr = [Node() for _ in range(n << 2)] self.build(1, 1, n) def build(self, u, l, r): self.tr[u].l, self.tr[u].r = l, r if l == r: self.tr[u].s = self.nums[l - 1] return mid = (l + r) >> 1 self.build(u << 1, l, mid) self.build(u << 1 | 1, mid + 1, r) self.pushup(u) def modify(self, u, l, r): if self.tr[u].l >= l and self.tr[u].r <= r: self.tr[u].lazy ^= 1 self.tr[u].s = self.tr[u].r - self.tr[u].l + 1 - self.tr[u].s return self.pushdown(u) mid = (self.tr[u].l + self.tr[u].r) >> 1 if l <= mid: self.modify(u << 1, l, r) if r > mid: self.modify(u << 1 | 1, l, r) self.pushup(u) def query(self, u, l, r): if self.tr[u].l >= l and self.tr[u].r <= r: return self.tr[u].s self.pushdown(u) mid = (self.tr[u].l + self.tr[u].r) >> 1 res = 0 if l <= mid: res += self.query(u << 1, l, r) if r > mid: res += self.query(u << 1 | 1, l, r) return res def pushup(self, u): self.tr[u].s = self.tr[u << 1].s + self.tr[u << 1 | 1].s def pushdown(self, u): if self.tr[u].lazy: mid = (self.tr[u].l + self.tr[u].r) >> 1 self.tr[u << 1].s = mid - self.tr[u].l + 1 - self.tr[u << 1].s self.tr[u << 1].lazy ^= 1 self.tr[u << 1 | 1].s = self.tr[u].r - mid - self.tr[u << 1 | 1].s self.tr[u << 1 | 1].lazy ^= 1 self.tr[u].lazy ^= 1 class Solution: def handleQuery( self, nums1: List[int], nums2: List[int], queries: List[List[int]] ) -> List[int]: tree = SegmentTree(nums1) s = sum(nums2) ans = [] for op, a, b in queries: if op == 1: tree.modify(1, a + 1, b + 1) elif op == 2: s += a * tree.query(1, 1, len(nums1)) else: ans.append(s) return ans
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
C++
class Solution { public: vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) { int cnt[1001]{}; for (auto& x : nums1) { cnt[x[0]] += x[1]; } for (auto& x : nums2) { cnt[x[0]] += x[1]; } vector<vector<int>> ans; for (int i = 0; i < 1001; ++i) { if (cnt[i]) { ans.push_back({i, cnt[i]}); } } return ans; } };
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
Go
func mergeArrays(nums1 [][]int, nums2 [][]int) (ans [][]int) { cnt := [1001]int{} for _, x := range nums1 { cnt[x[0]] += x[1] } for _, x := range nums2 { cnt[x[0]] += x[1] } for i, x := range cnt { if x > 0 { ans = append(ans, []int{i, x}) } } return }
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
Java
class Solution { public int[][] mergeArrays(int[][] nums1, int[][] nums2) { int[] cnt = new int[1001]; for (var x : nums1) { cnt[x[0]] += x[1]; } for (var x : nums2) { cnt[x[0]] += x[1]; } int n = 0; for (int i = 0; i < 1001; ++i) { if (cnt[i] > 0) { ++n; } } int[][] ans = new int[n][2]; for (int i = 0, j = 0; i < 1001; ++i) { if (cnt[i] > 0) { ans[j++] = new int[] {i, cnt[i]}; } } return ans; } }
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
Python
class Solution: def mergeArrays( self, nums1: List[List[int]], nums2: List[List[int]] ) -> List[List[int]]: cnt = Counter() for i, v in nums1 + nums2: cnt[i] += v return sorted(cnt.items())
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
Rust
impl Solution { pub fn merge_arrays(nums1: Vec<Vec<i32>>, nums2: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut cnt = vec![0; 1001]; for x in &nums1 { cnt[x[0] as usize] += x[1]; } for x in &nums2 { cnt[x[0] as usize] += x[1]; } let mut ans = vec![]; for i in 0..cnt.len() { if cnt[i] > 0 { ans.push(vec![i as i32, cnt[i] as i32]); } } ans } }
2,570
Merge Two 2D Arrays by Summing Values
Easy
<p>You are given two <strong>2D</strong> integer arrays <code>nums1</code> and <code>nums2.</code></p> <ul> <li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> <li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id <code>id<sub>i</sub></code> has a value equal to <code>val<sub>i</sub></code>.</li> </ul> <p>Each array contains <strong>unique</strong> ids and is sorted in <strong>ascending</strong> order by id.</p> <p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p> <ul> <li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li> <li>Each id should be included <strong>only once</strong> and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays, then assume its value in that array to be <code>0</code>.</li> </ul> <p>Return <em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]] <strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]] <strong>Explanation:</strong> The resulting array contains the following: - id = 1, the value of this id is 2 + 4 = 6. - id = 2, the value of this id is 3. - id = 3, the value of this id is 2. - id = 4, the value of this id is 5 + 1 = 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]] <strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]] <strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li> <li><code>nums1[i].length == nums2[j].length == 2</code></li> <li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li> <li>Both arrays contain unique ids.</li> <li>Both arrays are in&nbsp;strictly ascending order by id.</li> </ul>
Array; Hash Table; Two Pointers
TypeScript
function mergeArrays(nums1: number[][], nums2: number[][]): number[][] { const n = 1001; const cnt = new Array(n).fill(0); for (const [a, b] of nums1) { cnt[a] += b; } for (const [a, b] of nums2) { cnt[a] += b; } const ans: number[][] = []; for (let i = 0; i < n; ++i) { if (cnt[i] > 0) { ans.push([i, cnt[i]]); } } return ans; }
2,571
Minimum Operations to Reduce an Integer to 0
Medium
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> <ul> <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> <p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code>&nbsp;where <code>i &gt;= 0</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 39 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>0</sup> = 1 to n, so now n = 40. - Subtract 2<sup>3</sup> = 8 from n, so now n = 32. - Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 54 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>1</sup> = 2 to n, so now n = 56. - Add 2<sup>3</sup> = 8 to n, so now n = 64. - Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Bit Manipulation; Dynamic Programming
C++
class Solution { public: int minOperations(int n) { int ans = 0, cnt = 0; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ++cnt; } else if (cnt > 0) { ++ans; cnt = cnt == 1 ? 0 : 1; } } ans += cnt == 1 ? 1 : 0; ans += cnt > 1 ? 2 : 0; return ans; } };
2,571
Minimum Operations to Reduce an Integer to 0
Medium
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> <ul> <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> <p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code>&nbsp;where <code>i &gt;= 0</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 39 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>0</sup> = 1 to n, so now n = 40. - Subtract 2<sup>3</sup> = 8 from n, so now n = 32. - Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 54 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>1</sup> = 2 to n, so now n = 56. - Add 2<sup>3</sup> = 8 to n, so now n = 64. - Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Bit Manipulation; Dynamic Programming
Go
func minOperations(n int) (ans int) { cnt := 0 for ; n > 0; n >>= 1 { if n&1 == 1 { cnt++ } else if cnt > 0 { ans++ if cnt == 1 { cnt = 0 } else { cnt = 1 } } } if cnt == 1 { ans++ } else if cnt > 1 { ans += 2 } return }
2,571
Minimum Operations to Reduce an Integer to 0
Medium
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> <ul> <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> <p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code>&nbsp;where <code>i &gt;= 0</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 39 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>0</sup> = 1 to n, so now n = 40. - Subtract 2<sup>3</sup> = 8 from n, so now n = 32. - Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 54 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>1</sup> = 2 to n, so now n = 56. - Add 2<sup>3</sup> = 8 to n, so now n = 64. - Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Bit Manipulation; Dynamic Programming
Java
class Solution { public int minOperations(int n) { int ans = 0, cnt = 0; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ++cnt; } else if (cnt > 0) { ++ans; cnt = cnt == 1 ? 0 : 1; } } ans += cnt == 1 ? 1 : 0; ans += cnt > 1 ? 2 : 0; return ans; } }
2,571
Minimum Operations to Reduce an Integer to 0
Medium
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> <ul> <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> <p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code>&nbsp;where <code>i &gt;= 0</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 39 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>0</sup> = 1 to n, so now n = 40. - Subtract 2<sup>3</sup> = 8 from n, so now n = 32. - Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 54 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>1</sup> = 2 to n, so now n = 56. - Add 2<sup>3</sup> = 8 to n, so now n = 64. - Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Bit Manipulation; Dynamic Programming
Python
class Solution: def minOperations(self, n: int) -> int: ans = cnt = 0 while n: if n & 1: cnt += 1 elif cnt: ans += 1 cnt = 0 if cnt == 1 else 1 n >>= 1 if cnt == 1: ans += 1 elif cnt > 1: ans += 2 return ans
2,571
Minimum Operations to Reduce an Integer to 0
Medium
<p>You are given a positive integer <code>n</code>, you can do the following operation <strong>any</strong> number of times:</p> <ul> <li>Add or subtract a <strong>power</strong> of <code>2</code> from <code>n</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make </em><code>n</code><em> equal to </em><code>0</code>.</p> <p>A number <code>x</code> is power of <code>2</code> if <code>x == 2<sup>i</sup></code>&nbsp;where <code>i &gt;= 0</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 39 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>0</sup> = 1 to n, so now n = 40. - Subtract 2<sup>3</sup> = 8 from n, so now n = 32. - Subtract 2<sup>5</sup> = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 54 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations: - Add 2<sup>1</sup> = 2 to n, so now n = 56. - Add 2<sup>3</sup> = 8 to n, so now n = 64. - Subtract 2<sup>6</sup> = 64 from n, so now n = 0. So the minimum number of operations is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Bit Manipulation; Dynamic Programming
TypeScript
function minOperations(n: number): number { let [ans, cnt] = [0, 0]; for (; n; n >>= 1) { if (n & 1) { ++cnt; } else if (cnt) { ++ans; cnt = cnt === 1 ? 0 : 1; } } if (cnt === 1) { ++ans; } else if (cnt > 1) { ans += 2; } return ans; }
2,572
Count the Number of Square-Free Subsets
Medium
<p>You are given a positive integer <strong>0-indexed</strong>&nbsp;array <code>nums</code>.</p> <p>A subset of the array <code>nums</code> is <strong>square-free</strong> if the product of its elements is a <strong>square-free integer</strong>.</p> <p>A <strong>square-free integer</strong> is an integer that is divisible by no square number other than <code>1</code>.</p> <p>Return <em>the number of square-free non-empty subsets of the array</em> <strong>nums</strong>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>A <strong>non-empty</strong>&nbsp;<strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none but not all) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 square-free subsets in this example: - The subset consisting of the 0<sup>th</sup> element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3<sup>rd</sup> element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0<sup>th</sup> and 3<sup>rd</sup> elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There is 1 square-free subset in this example: - The subset consisting of the 0<sup>th</sup> element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length&nbsp;&lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Bit Manipulation; Array; Math; Dynamic Programming; Bitmask
C++
class Solution { public: int squareFreeSubsets(vector<int>& nums) { int primes[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; int cnt[31]{}; for (int& x : nums) { ++cnt[x]; } int n = 10; const int mod = 1e9 + 7; vector<long long> f(1 << n); f[0] = 1; for (int i = 0; i < cnt[1]; ++i) { f[0] = f[0] * 2 % mod; } for (int x = 2; x < 31; ++x) { if (cnt[x] == 0 || x % 4 == 0 || x % 9 == 0 || x % 25 == 0) { continue; } int mask = 0; for (int i = 0; i < n; ++i) { if (x % primes[i] == 0) { mask |= 1 << i; } } for (int state = (1 << n) - 1; state; --state) { if ((state & mask) == mask) { f[state] = (f[state] + 1LL * cnt[x] * f[state ^ mask]) % mod; } } } long long ans = -1; for (int i = 0; i < 1 << n; ++i) { ans = (ans + f[i]) % mod; } return ans; } };
2,572
Count the Number of Square-Free Subsets
Medium
<p>You are given a positive integer <strong>0-indexed</strong>&nbsp;array <code>nums</code>.</p> <p>A subset of the array <code>nums</code> is <strong>square-free</strong> if the product of its elements is a <strong>square-free integer</strong>.</p> <p>A <strong>square-free integer</strong> is an integer that is divisible by no square number other than <code>1</code>.</p> <p>Return <em>the number of square-free non-empty subsets of the array</em> <strong>nums</strong>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>A <strong>non-empty</strong>&nbsp;<strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none but not all) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 square-free subsets in this example: - The subset consisting of the 0<sup>th</sup> element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3<sup>rd</sup> element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0<sup>th</sup> and 3<sup>rd</sup> elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There is 1 square-free subset in this example: - The subset consisting of the 0<sup>th</sup> element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length&nbsp;&lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Bit Manipulation; Array; Math; Dynamic Programming; Bitmask
Go
func squareFreeSubsets(nums []int) (ans int) { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} cnt := [31]int{} for _, x := range nums { cnt[x]++ } const mod int = 1e9 + 7 n := 10 f := make([]int, 1<<n) f[0] = 1 for i := 0; i < cnt[1]; i++ { f[0] = f[0] * 2 % mod } for x := 2; x < 31; x++ { if cnt[x] == 0 || x%4 == 0 || x%9 == 0 || x%25 == 0 { continue } mask := 0 for i, p := range primes { if x%p == 0 { mask |= 1 << i } } for state := 1<<n - 1; state > 0; state-- { if state&mask == mask { f[state] = (f[state] + f[state^mask]*cnt[x]) % mod } } } ans = -1 for _, v := range f { ans = (ans + v) % mod } return }
2,572
Count the Number of Square-Free Subsets
Medium
<p>You are given a positive integer <strong>0-indexed</strong>&nbsp;array <code>nums</code>.</p> <p>A subset of the array <code>nums</code> is <strong>square-free</strong> if the product of its elements is a <strong>square-free integer</strong>.</p> <p>A <strong>square-free integer</strong> is an integer that is divisible by no square number other than <code>1</code>.</p> <p>Return <em>the number of square-free non-empty subsets of the array</em> <strong>nums</strong>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>A <strong>non-empty</strong>&nbsp;<strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none but not all) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 square-free subsets in this example: - The subset consisting of the 0<sup>th</sup> element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3<sup>rd</sup> element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0<sup>th</sup> and 3<sup>rd</sup> elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There is 1 square-free subset in this example: - The subset consisting of the 0<sup>th</sup> element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length&nbsp;&lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Bit Manipulation; Array; Math; Dynamic Programming; Bitmask
Java
class Solution { public int squareFreeSubsets(int[] nums) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; int[] cnt = new int[31]; for (int x : nums) { ++cnt[x]; } final int mod = (int) 1e9 + 7; int n = primes.length; long[] f = new long[1 << n]; f[0] = 1; for (int i = 0; i < cnt[1]; ++i) { f[0] = (f[0] * 2) % mod; } for (int x = 2; x < 31; ++x) { if (cnt[x] == 0 || x % 4 == 0 || x % 9 == 0 || x % 25 == 0) { continue; } int mask = 0; for (int i = 0; i < n; ++i) { if (x % primes[i] == 0) { mask |= 1 << i; } } for (int state = (1 << n) - 1; state > 0; --state) { if ((state & mask) == mask) { f[state] = (f[state] + cnt[x] * f[state ^ mask]) % mod; } } } long ans = 0; for (int i = 0; i < 1 << n; ++i) { ans = (ans + f[i]) % mod; } ans -= 1; return (int) ans; } }
2,572
Count the Number of Square-Free Subsets
Medium
<p>You are given a positive integer <strong>0-indexed</strong>&nbsp;array <code>nums</code>.</p> <p>A subset of the array <code>nums</code> is <strong>square-free</strong> if the product of its elements is a <strong>square-free integer</strong>.</p> <p>A <strong>square-free integer</strong> is an integer that is divisible by no square number other than <code>1</code>.</p> <p>Return <em>the number of square-free non-empty subsets of the array</em> <strong>nums</strong>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>A <strong>non-empty</strong>&nbsp;<strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none but not all) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 square-free subsets in this example: - The subset consisting of the 0<sup>th</sup> element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3<sup>rd</sup> element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0<sup>th</sup> and 3<sup>rd</sup> elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There is 1 square-free subset in this example: - The subset consisting of the 0<sup>th</sup> element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length&nbsp;&lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Bit Manipulation; Array; Math; Dynamic Programming; Bitmask
Python
class Solution: def squareFreeSubsets(self, nums: List[int]) -> int: primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] cnt = Counter(nums) mod = 10**9 + 7 n = len(primes) f = [0] * (1 << n) f[0] = pow(2, cnt[1]) for x in range(2, 31): if cnt[x] == 0 or x % 4 == 0 or x % 9 == 0 or x % 25 == 0: continue mask = 0 for i, p in enumerate(primes): if x % p == 0: mask |= 1 << i for state in range((1 << n) - 1, 0, -1): if state & mask == mask: f[state] = (f[state] + cnt[x] * f[state ^ mask]) % mod return sum(v for v in f) % mod - 1
2,572
Count the Number of Square-Free Subsets
Medium
<p>You are given a positive integer <strong>0-indexed</strong>&nbsp;array <code>nums</code>.</p> <p>A subset of the array <code>nums</code> is <strong>square-free</strong> if the product of its elements is a <strong>square-free integer</strong>.</p> <p>A <strong>square-free integer</strong> is an integer that is divisible by no square number other than <code>1</code>.</p> <p>Return <em>the number of square-free non-empty subsets of the array</em> <strong>nums</strong>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>A <strong>non-empty</strong>&nbsp;<strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none but not all) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,4,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 square-free subsets in this example: - The subset consisting of the 0<sup>th</sup> element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3<sup>rd</sup> element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0<sup>th</sup> and 3<sup>rd</sup> elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> 1 <strong>Explanation:</strong> There is 1 square-free subset in this example: - The subset consisting of the 0<sup>th</sup> element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length&nbsp;&lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 30</code></li> </ul>
Bit Manipulation; Array; Math; Dynamic Programming; Bitmask
TypeScript
function squareFreeSubsets(nums: number[]): number { const primes: number[] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; const cnt: number[] = Array(31).fill(0); for (const x of nums) { ++cnt[x]; } const mod: number = Math.pow(10, 9) + 7; const n: number = primes.length; const f: number[] = Array(1 << n).fill(0); f[0] = 1; for (let i = 0; i < cnt[1]; ++i) { f[0] = (f[0] * 2) % mod; } for (let x = 2; x < 31; ++x) { if (cnt[x] === 0 || x % 4 === 0 || x % 9 === 0 || x % 25 === 0) { continue; } let mask: number = 0; for (let i = 0; i < n; ++i) { if (x % primes[i] === 0) { mask |= 1 << i; } } for (let state = (1 << n) - 1; state > 0; --state) { if ((state & mask) === mask) { f[state] = (f[state] + cnt[x] * f[state ^ mask]) % mod; } } } let ans: number = 0; for (let i = 0; i < 1 << n; ++i) { ans = (ans + f[i]) % mod; } ans -= 1; return ans >= 0 ? ans : ans + mod; }
2,573
Find the String with LCP
Hard
<p>We define the <code>lcp</code> matrix of any <strong>0-indexed</strong> string <code>word</code> of <code>n</code> lowercase English letters as an <code>n x n</code> grid such that:</p> <ul> <li><code>lcp[i][j]</code> is equal to the length of the <strong>longest common prefix</strong> between the substrings <code>word[i,n-1]</code> and <code>word[j,n-1]</code>.</li> </ul> <p>Given an&nbsp;<code>n x n</code> matrix <code>lcp</code>, return the alphabetically smallest string <code>word</code> that corresponds to <code>lcp</code>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>. For example, <code>&quot;aabd&quot;</code> is lexicographically smaller than <code>&quot;aaca&quot;</code> because the first position they differ is at the third letter, and <code>&#39;b&#39;</code> comes before <code>&#39;c&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] <strong>Output:</strong> &quot;abab&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is &quot;abab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] <strong>Output:</strong> &quot;aaaa&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is &quot;aaaa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n ==&nbsp;</code><code>lcp.length == </code><code>lcp[i].length</code>&nbsp;<code>&lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= lcp[i][j] &lt;= n</font></code></li> </ul>
Greedy; Union Find; Array; String; Dynamic Programming; Matrix
C++
class Solution { public: string findTheString(vector<vector<int>>& lcp) { int i = 0, n = lcp.size(); string s(n, '\0'); for (char c = 'a'; c <= 'z'; ++c) { while (i < n && s[i]) { ++i; } if (i == n) { break; } for (int j = i; j < n; ++j) { if (lcp[i][j]) { s[j] = c; } } } if (s.find('\0') != -1) { return ""; } for (i = n - 1; ~i; --i) { for (int j = n - 1; ~j; --j) { if (s[i] == s[j]) { if (i == n - 1 || j == n - 1) { if (lcp[i][j] != 1) { return ""; } } else if (lcp[i][j] != lcp[i + 1][j + 1] + 1) { return ""; } } else if (lcp[i][j]) { return ""; } } } return s; } };
2,573
Find the String with LCP
Hard
<p>We define the <code>lcp</code> matrix of any <strong>0-indexed</strong> string <code>word</code> of <code>n</code> lowercase English letters as an <code>n x n</code> grid such that:</p> <ul> <li><code>lcp[i][j]</code> is equal to the length of the <strong>longest common prefix</strong> between the substrings <code>word[i,n-1]</code> and <code>word[j,n-1]</code>.</li> </ul> <p>Given an&nbsp;<code>n x n</code> matrix <code>lcp</code>, return the alphabetically smallest string <code>word</code> that corresponds to <code>lcp</code>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>. For example, <code>&quot;aabd&quot;</code> is lexicographically smaller than <code>&quot;aaca&quot;</code> because the first position they differ is at the third letter, and <code>&#39;b&#39;</code> comes before <code>&#39;c&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] <strong>Output:</strong> &quot;abab&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is &quot;abab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] <strong>Output:</strong> &quot;aaaa&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is &quot;aaaa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n ==&nbsp;</code><code>lcp.length == </code><code>lcp[i].length</code>&nbsp;<code>&lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= lcp[i][j] &lt;= n</font></code></li> </ul>
Greedy; Union Find; Array; String; Dynamic Programming; Matrix
Go
func findTheString(lcp [][]int) string { i, n := 0, len(lcp) s := make([]byte, n) for c := 'a'; c <= 'z'; c++ { for i < n && s[i] != 0 { i++ } if i == n { break } for j := i; j < n; j++ { if lcp[i][j] > 0 { s[j] = byte(c) } } } if bytes.IndexByte(s, 0) >= 0 { return "" } for i := n - 1; i >= 0; i-- { for j := n - 1; j >= 0; j-- { if s[i] == s[j] { if i == n-1 || j == n-1 { if lcp[i][j] != 1 { return "" } } else if lcp[i][j] != lcp[i+1][j+1]+1 { return "" } } else if lcp[i][j] > 0 { return "" } } } return string(s) }
2,573
Find the String with LCP
Hard
<p>We define the <code>lcp</code> matrix of any <strong>0-indexed</strong> string <code>word</code> of <code>n</code> lowercase English letters as an <code>n x n</code> grid such that:</p> <ul> <li><code>lcp[i][j]</code> is equal to the length of the <strong>longest common prefix</strong> between the substrings <code>word[i,n-1]</code> and <code>word[j,n-1]</code>.</li> </ul> <p>Given an&nbsp;<code>n x n</code> matrix <code>lcp</code>, return the alphabetically smallest string <code>word</code> that corresponds to <code>lcp</code>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>. For example, <code>&quot;aabd&quot;</code> is lexicographically smaller than <code>&quot;aaca&quot;</code> because the first position they differ is at the third letter, and <code>&#39;b&#39;</code> comes before <code>&#39;c&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] <strong>Output:</strong> &quot;abab&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is &quot;abab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] <strong>Output:</strong> &quot;aaaa&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is &quot;aaaa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n ==&nbsp;</code><code>lcp.length == </code><code>lcp[i].length</code>&nbsp;<code>&lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= lcp[i][j] &lt;= n</font></code></li> </ul>
Greedy; Union Find; Array; String; Dynamic Programming; Matrix
Java
class Solution { public String findTheString(int[][] lcp) { int n = lcp.length; char[] s = new char[n]; int i = 0; for (char c = 'a'; c <= 'z'; ++c) { while (i < n && s[i] != '\0') { ++i; } if (i == n) { break; } for (int j = i; j < n; ++j) { if (lcp[i][j] > 0) { s[j] = c; } } } for (i = 0; i < n; ++i) { if (s[i] == '\0') { return ""; } } for (i = n - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (s[i] == s[j]) { if (i == n - 1 || j == n - 1) { if (lcp[i][j] != 1) { return ""; } } else if (lcp[i][j] != lcp[i + 1][j + 1] + 1) { return ""; } } else if (lcp[i][j] > 0) { return ""; } } } return String.valueOf(s); } }
2,573
Find the String with LCP
Hard
<p>We define the <code>lcp</code> matrix of any <strong>0-indexed</strong> string <code>word</code> of <code>n</code> lowercase English letters as an <code>n x n</code> grid such that:</p> <ul> <li><code>lcp[i][j]</code> is equal to the length of the <strong>longest common prefix</strong> between the substrings <code>word[i,n-1]</code> and <code>word[j,n-1]</code>.</li> </ul> <p>Given an&nbsp;<code>n x n</code> matrix <code>lcp</code>, return the alphabetically smallest string <code>word</code> that corresponds to <code>lcp</code>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>. For example, <code>&quot;aabd&quot;</code> is lexicographically smaller than <code>&quot;aaca&quot;</code> because the first position they differ is at the third letter, and <code>&#39;b&#39;</code> comes before <code>&#39;c&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] <strong>Output:</strong> &quot;abab&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is &quot;abab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] <strong>Output:</strong> &quot;aaaa&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is &quot;aaaa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n ==&nbsp;</code><code>lcp.length == </code><code>lcp[i].length</code>&nbsp;<code>&lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= lcp[i][j] &lt;= n</font></code></li> </ul>
Greedy; Union Find; Array; String; Dynamic Programming; Matrix
Python
class Solution: def findTheString(self, lcp: List[List[int]]) -> str: n = len(lcp) s = [""] * n i = 0 for c in ascii_lowercase: while i < n and s[i]: i += 1 if i == n: break for j in range(i, n): if lcp[i][j]: s[j] = c if "" in s: return "" for i in range(n - 1, -1, -1): for j in range(n - 1, -1, -1): if s[i] == s[j]: if i == n - 1 or j == n - 1: if lcp[i][j] != 1: return "" elif lcp[i][j] != lcp[i + 1][j + 1] + 1: return "" elif lcp[i][j]: return "" return "".join(s)
2,573
Find the String with LCP
Hard
<p>We define the <code>lcp</code> matrix of any <strong>0-indexed</strong> string <code>word</code> of <code>n</code> lowercase English letters as an <code>n x n</code> grid such that:</p> <ul> <li><code>lcp[i][j]</code> is equal to the length of the <strong>longest common prefix</strong> between the substrings <code>word[i,n-1]</code> and <code>word[j,n-1]</code>.</li> </ul> <p>Given an&nbsp;<code>n x n</code> matrix <code>lcp</code>, return the alphabetically smallest string <code>word</code> that corresponds to <code>lcp</code>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>. For example, <code>&quot;aabd&quot;</code> is lexicographically smaller than <code>&quot;aaca&quot;</code> because the first position they differ is at the third letter, and <code>&#39;b&#39;</code> comes before <code>&#39;c&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]] <strong>Output:</strong> &quot;abab&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is &quot;abab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]] <strong>Output:</strong> &quot;aaaa&quot; <strong>Explanation:</strong> lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is &quot;aaaa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n ==&nbsp;</code><code>lcp.length == </code><code>lcp[i].length</code>&nbsp;<code>&lt;= 1000</code></li> <li><code><font face="monospace">0 &lt;= lcp[i][j] &lt;= n</font></code></li> </ul>
Greedy; Union Find; Array; String; Dynamic Programming; Matrix
TypeScript
function findTheString(lcp: number[][]): string { let i: number = 0; const n: number = lcp.length; let s: string = '\0'.repeat(n); for (let ascii = 97; ascii < 123; ++ascii) { const c: string = String.fromCharCode(ascii); while (i < n && s[i] !== '\0') { ++i; } if (i === n) { break; } for (let j = i; j < n; ++j) { if (lcp[i][j]) { s = s.substring(0, j) + c + s.substring(j + 1); } } } if (s.indexOf('\0') !== -1) { return ''; } for (i = n - 1; ~i; --i) { for (let j = n - 1; ~j; --j) { if (s[i] === s[j]) { if (i === n - 1 || j === n - 1) { if (lcp[i][j] !== 1) { return ''; } } else if (lcp[i][j] !== lcp[i + 1][j + 1] + 1) { return ''; } } else if (lcp[i][j]) { return ''; } } } return s; }
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
C
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { int left = 0; int right = 0; for (int i = 0; i < numsSize; i++) { right += nums[i]; } int* ans = malloc(sizeof(int) * numsSize); for (int i = 0; i < numsSize; i++) { right -= nums[i]; ans[i] = abs(left - right); left += nums[i]; } *returnSize = numsSize; return ans; }
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
C++
class Solution { public: vector<int> leftRigthDifference(vector<int>& nums) { int left = 0, right = accumulate(nums.begin(), nums.end(), 0); vector<int> ans; for (int& x : nums) { right -= x; ans.push_back(abs(left - right)); left += x; } return ans; } };
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
Go
func leftRigthDifference(nums []int) (ans []int) { var left, right int for _, x := range nums { right += x } for _, x := range nums { right -= x ans = append(ans, abs(left-right)) left += x } return } func abs(x int) int { if x < 0 { return -x } return x }
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
Java
class Solution { public int[] leftRigthDifference(int[] nums) { int left = 0, right = Arrays.stream(nums).sum(); int n = nums.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { right -= nums[i]; ans[i] = Math.abs(left - right); left += nums[i]; } return ans; } }
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
Python
class Solution: def leftRigthDifference(self, nums: List[int]) -> List[int]: left, right = 0, sum(nums) ans = [] for x in nums: right -= x ans.append(abs(left - right)) left += x return ans
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
Rust
impl Solution { pub fn left_rigth_difference(nums: Vec<i32>) -> Vec<i32> { let mut left = 0; let mut right = nums.iter().sum::<i32>(); nums.iter() .map(|v| { right -= v; let res = (left - right).abs(); left += v; res }) .collect() } }
2,574
Left and Right Sum Differences
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>.</p> <p>Define two arrays <code>leftSum</code> and <code>rightSum</code> where:</p> <ul> <li><code>leftSum[i]</code> is the sum of elements to the left of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>leftSum[i] = 0</code>.</li> <li><code>rightSum[i]</code> is the sum of elements to the right of the index <code>i</code> in the array <code>nums</code>. If there is no such element, <code>rightSum[i] = 0</code>.</li> </ul> <p>Return an integer array <code>answer</code> of size <code>n</code> where <code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,4,8,3] <strong>Output:</strong> [15,1,11,22] <strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0]. The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [0] <strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0]. The array answer is [|0 - 0|] = [0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Prefix Sum
TypeScript
function leftRigthDifference(nums: number[]): number[] { let left = 0, right = nums.reduce((a, b) => a + b); const ans: number[] = []; for (const x of nums) { right -= x; ans.push(Math.abs(left - right)); left += x; } return ans; }
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
C
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* divisibilityArray(char* word, int m, int* returnSize) { int n = strlen(word); int* ans = malloc(sizeof(int) * n); long long x = 0; for (int i = 0; i < n; i++) { x = (x * 10 + word[i] - '0') % m; ans[i] = x == 0 ? 1 : 0; } *returnSize = n; return ans; }
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
C++
class Solution { public: vector<int> divisibilityArray(string word, int m) { vector<int> ans; long long x = 0; for (char& c : word) { x = (x * 10 + c - '0') % m; ans.push_back(x == 0 ? 1 : 0); } return ans; } };
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
Go
func divisibilityArray(word string, m int) (ans []int) { x := 0 for _, c := range word { x = (x*10 + int(c-'0')) % m if x == 0 { ans = append(ans, 1) } else { ans = append(ans, 0) } } return ans }
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
Java
class Solution { public int[] divisibilityArray(String word, int m) { int n = word.length(); int[] ans = new int[n]; long x = 0; for (int i = 0; i < n; ++i) { x = (x * 10 + word.charAt(i) - '0') % m; if (x == 0) { ans[i] = 1; } } return ans; } }
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
Python
class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: ans = [] x = 0 for c in word: x = (x * 10 + int(c)) % m ans.append(1 if x == 0 else 0) return ans
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
Rust
impl Solution { pub fn divisibility_array(word: String, m: i32) -> Vec<i32> { let m = m as i64; let mut x = 0i64; word.as_bytes() .iter() .map(|&c| { x = (x * 10 + i64::from(c - b'0')) % m; if x == 0 { 1 } else { 0 } }) .collect() } }
2,575
Find the Divisibility Array of a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> of length <code>n</code>&nbsp;consisting of digits, and a positive integer&nbsp;<code>m</code>.</p> <p>The <strong>divisibility array</strong> <code>div</code> of <code>word</code> is an integer array of length <code>n</code> such that:</p> <ul> <li><code>div[i] = 1</code> if the&nbsp;<strong>numeric value</strong>&nbsp;of&nbsp;<code>word[0,...,i]</code> is divisible by <code>m</code>, or</li> <li><code>div[i] = 0</code> otherwise.</li> </ul> <p>Return<em> the divisibility array of</em><em> </em><code>word</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;998244353&quot;, m = 3 <strong>Output:</strong> [1,1,0,0,0,1,1,0,0] <strong>Explanation:</strong> There are only 4 prefixes that are divisible by 3: &quot;9&quot;, &quot;99&quot;, &quot;998244&quot;, and &quot;9982443&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;1010&quot;, m = 10 <strong>Output:</strong> [0,1,0,1] <strong>Explanation:</strong> There are only 2 prefixes that are divisible by 10: &quot;10&quot;, and &quot;1010&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code><font face="monospace">word.length == n</font></code></li> <li><code><font face="monospace">word</font></code><font face="monospace"> consists of digits from <code>0</code>&nbsp;to <code>9</code></font></li> <li><code><font face="monospace">1 &lt;= m &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Math; String
TypeScript
function divisibilityArray(word: string, m: number): number[] { const ans: number[] = []; let x = 0; for (const c of word) { x = (x * 10 + Number(c)) % m; ans.push(x === 0 ? 1 : 0); } return ans; }
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
C++
class Solution { public: int maxNumOfMarkedIndices(vector<int>& nums) { ranges::sort(nums); int i = 0, n = nums.size(); for (int j = (n + 1) / 2; j < n; ++j) { if (nums[i] * 2 <= nums[j]) { ++i; } } return i * 2; } };
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
Go
func maxNumOfMarkedIndices(nums []int) (ans int) { sort.Ints(nums) i, n := 0, len(nums) for _, x := range nums[(n+1)/2:] { if nums[i]*2 <= x { i++ } } return i * 2 }
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
Java
class Solution { public int maxNumOfMarkedIndices(int[] nums) { Arrays.sort(nums); int i = 0, n = nums.length; for (int j = (n + 1) / 2; j < n; ++j) { if (nums[i] * 2 <= nums[j]) { ++i; } } return i * 2; } }
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
Python
class Solution: def maxNumOfMarkedIndices(self, nums: List[int]) -> int: nums.sort() i, n = 0, len(nums) for x in nums[(n + 1) // 2 :]: if nums[i] * 2 <= x: i += 1 return i * 2
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
Rust
impl Solution { pub fn max_num_of_marked_indices(mut nums: Vec<i32>) -> i32 { nums.sort(); let mut i = 0; let n = nums.len(); for j in (n + 1) / 2..n { if nums[i] * 2 <= nums[j] { i += 1; } } (i * 2) as i32 } }
2,576
Find the Maximum Number of Marked Indices
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:</p> <ul> <li>Pick two <strong>different unmarked</strong> indices <code>i</code> and <code>j</code> such that <code>2 * nums[i] &lt;= nums[j]</code>, then mark <code>i</code> and <code>j</code>.</li> </ul> <p>Return <em>the maximum possible number of marked indices in <code>nums</code> using the above operation any number of times</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,4] <strong>Output:</strong> 2 <strong>Explanation: </strong>In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] &lt;= nums[1]. Then mark index 2 and 1. It can be shown that there&#39;s no other valid operation so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [9,2,5,4] <strong>Output:</strong> 4 <strong>Explanation: </strong>In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] &lt;= nums[0]. Then mark index 3 and 0. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] &lt;= nums[2]. Then mark index 1 and 2. Since there is no other operation, the answer is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,8] <strong>Output:</strong> 0 <strong>Explanation: </strong>There is no valid operation to do, so the answer is 0. </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> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array; Two Pointers; Binary Search; Sorting
TypeScript
function maxNumOfMarkedIndices(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; let i = 0; for (let j = (n + 1) >> 1; j < n; ++j) { if (nums[i] * 2 <= nums[j]) { ++i; } } return i * 2; }
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int minimumTime(vector<vector<int>>& grid) { if (grid[0][1] > 1 && grid[1][0] > 1) { return -1; } int m = grid.size(), n = grid[0].size(); int dist[m][n]; memset(dist, 0x3f, sizeof dist); dist[0][0] = 0; using tii = tuple<int, int, int>; priority_queue<tii, vector<tii>, greater<tii>> pq; pq.emplace(0, 0, 0); int dirs[5] = {-1, 0, 1, 0, -1}; while (1) { auto [t, i, j] = pq.top(); pq.pop(); if (i == m - 1 && j == n - 1) { return t; } for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n) { int nt = t + 1; if (nt < grid[x][y]) { nt = grid[x][y] + (grid[x][y] - nt) % 2; } if (nt < dist[x][y]) { dist[x][y] = nt; pq.emplace(nt, x, y); } } } } } };
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Go
func minimumTime(grid [][]int) int { if grid[0][1] > 1 && grid[1][0] > 1 { return -1 } m, n := len(grid), len(grid[0]) dist := make([][]int, m) for i := range dist { dist[i] = make([]int, n) for j := range dist[i] { dist[i][j] = 1 << 30 } } dist[0][0] = 0 pq := hp{} heap.Push(&pq, tuple{0, 0, 0}) dirs := [5]int{-1, 0, 1, 0, -1} for { p := heap.Pop(&pq).(tuple) i, j := p.i, p.j if i == m-1 && j == n-1 { return p.t } for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n { nt := p.t + 1 if nt < grid[x][y] { nt = grid[x][y] + (grid[x][y]-nt)%2 } if nt < dist[x][y] { dist[x][y] = nt heap.Push(&pq, tuple{nt, x, y}) } } } } } type tuple struct{ t, i, j int } type hp []tuple func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int minimumTime(int[][] grid) { if (grid[0][1] > 1 && grid[1][0] > 1) { return -1; } int m = grid.length, n = grid[0].length; int[][] dist = new int[m][n]; for (var e : dist) { Arrays.fill(e, 1 << 30); } dist[0][0] = 0; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); pq.offer(new int[] {0, 0, 0}); int[] dirs = {-1, 0, 1, 0, -1}; while (true) { var p = pq.poll(); int i = p[1], j = p[2]; if (i == m - 1 && j == n - 1) { return p[0]; } for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n) { int nt = p[0] + 1; if (nt < grid[x][y]) { nt = grid[x][y] + (grid[x][y] - nt) % 2; } if (nt < dist[x][y]) { dist[x][y] = nt; pq.offer(new int[] {nt, x, y}); } } } } } }
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
JavaScript
function minimumTime(grid) { if (grid[0][1] > 1 && grid[1][0] > 1) return -1; const [m, n] = [grid.length, grid[0].length]; const DIRS = [-1, 0, 1, 0, -1]; const q = new MinPriorityQueue({ priority: ([x]) => x }); const dist = Array.from({ length: m }, () => new Array(n).fill(Number.POSITIVE_INFINITY)); dist[0][0] = 0; q.enqueue([0, 0, 0]); while (true) { const [t, i, j] = q.dequeue().element; if (i === m - 1 && j === n - 1) return t; for (let k = 0; k < 4; k++) { const [x, y] = [i + DIRS[k], j + DIRS[k + 1]]; if (x < 0 || x >= m || y < 0 || y >= n) continue; let nt = t + 1; if (nt < grid[x][y]) { nt = grid[x][y] + ((grid[x][y] - nt) % 2); } if (nt < dist[x][y]) { dist[x][y] = nt; q.enqueue([nt, x, y]); } } } }
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Python
class Solution: def minimumTime(self, grid: List[List[int]]) -> int: if grid[0][1] > 1 and grid[1][0] > 1: return -1 m, n = len(grid), len(grid[0]) dist = [[inf] * n for _ in range(m)] dist[0][0] = 0 q = [(0, 0, 0)] dirs = (-1, 0, 1, 0, -1) while 1: t, i, j = heappop(q) if i == m - 1 and j == n - 1: return t for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: nt = t + 1 if nt < grid[x][y]: nt = grid[x][y] + (grid[x][y] - nt) % 2 if nt < dist[x][y]: dist[x][y] = nt heappush(q, (nt, x, y))
2,577
Minimum Time to Visit a Cell In a Grid
Hard
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers where <code>grid[row][col]</code> represents the <strong>minimum</strong> time required to be able to visit the cell <code>(row, col)</code>, which means you can visit the cell <code>(row, col)</code> only when the time you visit it is greater than or equal to <code>grid[row][col]</code>.</p> <p>You are standing in the <strong>top-left</strong> cell of the matrix in the <code>0<sup>th</sup></code> second, and you must move to <strong>any</strong> adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.</p> <p>Return <em>the <strong>minimum</strong> time required in which you can visit the bottom-right cell of the matrix</em>. If you cannot visit the bottom-right cell, then return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-8.png" /></p> <pre> <strong>Input:</strong> grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]] <strong>Output:</strong> 7 <strong>Explanation:</strong> One of the paths that we can take is the following: - at t = 0, we are on the cell (0,0). - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] &lt;= 1. - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 2. - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 3. - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] &lt;= 4. - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] &lt;= 5. - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] &lt;= 6. - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] &lt;= 7. The final time is 7. It can be shown that it is the minimum time possible. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2577.Minimum%20Time%20to%20Visit%20a%20Cell%20In%20a%20Grid/images/yetgriddrawio-9.png" style="width: 151px; height: 151px;" /></p> <pre> <strong>Input:</strong> grid = [[0,2,4],[3,2,1],[1,0,4]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no path from the top left to the bottom-right cell. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>grid[0][0] == 0</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
TypeScript
function minimumTime(grid: number[][]): number { if (grid[0][1] > 1 && grid[1][0] > 1) return -1; const [m, n] = [grid.length, grid[0].length]; const DIRS = [-1, 0, 1, 0, -1]; const q = new MinPriorityQueue({ priority: ([x]) => x }); const dist: number[][] = Array.from({ length: m }, () => new Array(n).fill(Number.POSITIVE_INFINITY), ); dist[0][0] = 0; q.enqueue([0, 0, 0]); while (true) { const [t, i, j] = q.dequeue().element; if (i === m - 1 && j === n - 1) return t; for (let k = 0; k < 4; k++) { const [x, y] = [i + DIRS[k], j + DIRS[k + 1]]; if (x < 0 || x >= m || y < 0 || y >= n) continue; let nt = t + 1; if (nt < grid[x][y]) { nt = grid[x][y] + ((grid[x][y] - nt) % 2); } if (nt < dist[x][y]) { dist[x][y] = nt; q.enqueue([nt, x, y]); } } } }
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
C++
class Solution { public: int splitNum(int num) { int cnt[10]{}; int n = 0; for (; num; num /= 10) { ++cnt[num % 10]; ++n; } int ans[2]{}; for (int i = 0, j = 0; i < n; ++i) { while (cnt[j] == 0) { ++j; } --cnt[j]; ans[i & 1] = ans[i & 1] * 10 + j; } return ans[0] + ans[1]; } };
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
Go
func splitNum(num int) int { cnt := [10]int{} n := 0 for ; num > 0; num /= 10 { cnt[num%10]++ n++ } ans := [2]int{} for i, j := 0, 0; i < n; i++ { for cnt[j] == 0 { j++ } cnt[j]-- ans[i&1] = ans[i&1]*10 + j } return ans[0] + ans[1] }
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
Java
class Solution { public int splitNum(int num) { int[] cnt = new int[10]; int n = 0; for (; num > 0; num /= 10) { ++cnt[num % 10]; ++n; } int[] ans = new int[2]; for (int i = 0, j = 0; i < n; ++i) { while (cnt[j] == 0) { ++j; } --cnt[j]; ans[i & 1] = ans[i & 1] * 10 + j; } return ans[0] + ans[1]; } }
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
Python
class Solution: def splitNum(self, num: int) -> int: cnt = Counter() n = 0 while num: cnt[num % 10] += 1 num //= 10 n += 1 ans = [0] * 2 j = 0 for i in range(n): while cnt[j] == 0: j += 1 cnt[j] -= 1 ans[i & 1] = ans[i & 1] * 10 + j return sum(ans)
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
Rust
impl Solution { pub fn split_num(mut num: i32) -> i32 { let mut cnt = vec![0; 10]; let mut n = 0; while num != 0 { cnt[(num as usize) % 10] += 1; num /= 10; n += 1; } let mut ans = vec![0; 2]; let mut j = 0; for i in 0..n { while cnt[j] == 0 { j += 1; } cnt[j] -= 1; ans[i & 1] = ans[i & 1] * 10 + (j as i32); } ans[0] + ans[1] } }
2,578
Split With Minimum Sum
Easy
<p>Given a positive integer <code>num</code>, split it into two non-negative integers <code>num1</code> and <code>num2</code> such that:</p> <ul> <li>The concatenation of <code>num1</code> and <code>num2</code> is a permutation of <code>num</code>. <ul> <li>In other words, the sum of the number of occurrences of each digit in <code>num1</code> and <code>num2</code> is equal to the number of occurrences of that digit in <code>num</code>.</li> </ul> </li> <li><code>num1</code> and <code>num2</code> can contain leading zeros.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum of</em> <code>num1</code> <em>and</em> <code>num2</code>.</p> <p><strong>Notes:</strong></p> <ul> <li>It is guaranteed that <code>num</code> does not contain any leading zeros.</li> <li>The order of occurrence of the digits in <code>num1</code> and <code>num2</code> may differ from the order of occurrence of <code>num</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 4325 <strong>Output:</strong> 59 <strong>Explanation:</strong> We can split 4325 so that <code>num1</code> is 24 and <code>num2</code> is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 687 <strong>Output:</strong> 75 <strong>Explanation:</strong> We can split 687 so that <code>num1</code> is 68 and <code>num2</code> is 7, which would give an optimal sum of 75. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= num &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math; Sorting
TypeScript
function splitNum(num: number): number { const cnt: number[] = Array(10).fill(0); let n = 0; for (; num > 0; num = Math.floor(num / 10)) { ++cnt[num % 10]; ++n; } const ans: number[] = Array(2).fill(0); for (let i = 0, j = 0; i < n; ++i) { while (cnt[j] === 0) { ++j; } --cnt[j]; ans[i & 1] = ans[i & 1] * 10 + j; } return ans[0] + ans[1]; }
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
C++
class Solution { public: long long coloredCells(int n) { return 2LL * n * (n - 1) + 1; } };
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
Go
func coloredCells(n int) int64 { return int64(2*n*(n-1) + 1) }
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
Java
class Solution { public long coloredCells(int n) { return 2L * n * (n - 1) + 1; } }
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
Python
class Solution: def coloredCells(self, n: int) -> int: return 2 * n * (n - 1) + 1
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
Rust
impl Solution { pub fn colored_cells(n: i32) -> i64 { 2 * (n as i64) * ((n as i64) - 1) + 1 } }
2,579
Count Total Number of Colored Cells
Medium
<p>There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer <code>n</code>, indicating that you must do the following routine for <code>n</code> minutes:</p> <ul> <li>At the first minute, color <strong>any</strong> arbitrary unit cell blue.</li> <li>Every minute thereafter, color blue <strong>every</strong> uncolored cell that touches a blue cell.</li> </ul> <p>Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2579.Count%20Total%20Number%20of%20Colored%20Cells/images/example-copy-2.png" style="width: 500px; height: 279px;" /> <p>Return <em>the number of <strong>colored cells</strong> at the end of </em><code>n</code> <em>minutes</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> After 1 minute, there is only 1 blue cell, so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> </ul>
Math
TypeScript
function coloredCells(n: number): number { return 2 * n * (n - 1) + 1; }
2,580
Count Ways to Group Overlapping Ranges
Medium
<p>You are given a 2D integer array <code>ranges</code> where <code>ranges[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> denotes that all integers between <code>start<sub>i</sub></code> and <code>end<sub>i</sub></code> (both <strong>inclusive</strong>) are contained in the <code>i<sup>th</sup></code> range.</p> <p>You are to split <code>ranges</code> into <strong>two</strong> (possibly empty) groups such that:</p> <ul> <li>Each range belongs to exactly one group.</li> <li>Any two <strong>overlapping</strong> ranges must belong to the <strong>same</strong> group.</li> </ul> <p>Two ranges are said to be <strong>overlapping</strong>&nbsp;if there exists at least <strong>one</strong> integer that is present in both ranges.</p> <ul> <li>For example, <code>[1, 3]</code> and <code>[2, 5]</code> are overlapping because <code>2</code> and <code>3</code> occur in both ranges.</li> </ul> <p>Return <em>the <strong>total number</strong> of ways to split</em> <code>ranges</code> <em>into two groups</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> ranges = [[6,10],[5,15]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ranges = [[1,3],[10,20],[2,5],[4,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ranges.length &lt;= 10<sup>5</sup></code></li> <li><code>ranges[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Array; Sorting
C++
class Solution { public: int countWays(vector<vector<int>>& ranges) { sort(ranges.begin(), ranges.end()); int cnt = 0, mx = -1; for (auto& e : ranges) { cnt += e[0] > mx; mx = max(mx, e[1]); } using ll = long long; auto qpow = [&](ll a, int n, int mod) { ll ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return ans; }; return qpow(2, cnt, 1e9 + 7); } };
2,580
Count Ways to Group Overlapping Ranges
Medium
<p>You are given a 2D integer array <code>ranges</code> where <code>ranges[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> denotes that all integers between <code>start<sub>i</sub></code> and <code>end<sub>i</sub></code> (both <strong>inclusive</strong>) are contained in the <code>i<sup>th</sup></code> range.</p> <p>You are to split <code>ranges</code> into <strong>two</strong> (possibly empty) groups such that:</p> <ul> <li>Each range belongs to exactly one group.</li> <li>Any two <strong>overlapping</strong> ranges must belong to the <strong>same</strong> group.</li> </ul> <p>Two ranges are said to be <strong>overlapping</strong>&nbsp;if there exists at least <strong>one</strong> integer that is present in both ranges.</p> <ul> <li>For example, <code>[1, 3]</code> and <code>[2, 5]</code> are overlapping because <code>2</code> and <code>3</code> occur in both ranges.</li> </ul> <p>Return <em>the <strong>total number</strong> of ways to split</em> <code>ranges</code> <em>into two groups</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> ranges = [[6,10],[5,15]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ranges = [[1,3],[10,20],[2,5],[4,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ranges.length &lt;= 10<sup>5</sup></code></li> <li><code>ranges[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Array; Sorting
Go
func countWays(ranges [][]int) int { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) cnt, mx := 0, -1 for _, e := range ranges { if e[0] > mx { cnt++ } if mx < e[1] { mx = e[1] } } qpow := func(a, n, mod int) int { ans := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { ans = ans * a % mod } a = a * a % mod } return ans } return qpow(2, cnt, 1e9+7) }
2,580
Count Ways to Group Overlapping Ranges
Medium
<p>You are given a 2D integer array <code>ranges</code> where <code>ranges[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> denotes that all integers between <code>start<sub>i</sub></code> and <code>end<sub>i</sub></code> (both <strong>inclusive</strong>) are contained in the <code>i<sup>th</sup></code> range.</p> <p>You are to split <code>ranges</code> into <strong>two</strong> (possibly empty) groups such that:</p> <ul> <li>Each range belongs to exactly one group.</li> <li>Any two <strong>overlapping</strong> ranges must belong to the <strong>same</strong> group.</li> </ul> <p>Two ranges are said to be <strong>overlapping</strong>&nbsp;if there exists at least <strong>one</strong> integer that is present in both ranges.</p> <ul> <li>For example, <code>[1, 3]</code> and <code>[2, 5]</code> are overlapping because <code>2</code> and <code>3</code> occur in both ranges.</li> </ul> <p>Return <em>the <strong>total number</strong> of ways to split</em> <code>ranges</code> <em>into two groups</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> ranges = [[6,10],[5,15]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ranges = [[1,3],[10,20],[2,5],[4,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ranges.length &lt;= 10<sup>5</sup></code></li> <li><code>ranges[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Array; Sorting
Java
class Solution { public int countWays(int[][] ranges) { Arrays.sort(ranges, (a, b) -> a[0] - b[0]); int cnt = 0, mx = -1; for (int[] e : ranges) { if (e[0] > mx) { ++cnt; } mx = Math.max(mx, e[1]); } return qpow(2, cnt, (int) 1e9 + 7); } private int qpow(long a, int n, int mod) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; } }
2,580
Count Ways to Group Overlapping Ranges
Medium
<p>You are given a 2D integer array <code>ranges</code> where <code>ranges[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> denotes that all integers between <code>start<sub>i</sub></code> and <code>end<sub>i</sub></code> (both <strong>inclusive</strong>) are contained in the <code>i<sup>th</sup></code> range.</p> <p>You are to split <code>ranges</code> into <strong>two</strong> (possibly empty) groups such that:</p> <ul> <li>Each range belongs to exactly one group.</li> <li>Any two <strong>overlapping</strong> ranges must belong to the <strong>same</strong> group.</li> </ul> <p>Two ranges are said to be <strong>overlapping</strong>&nbsp;if there exists at least <strong>one</strong> integer that is present in both ranges.</p> <ul> <li>For example, <code>[1, 3]</code> and <code>[2, 5]</code> are overlapping because <code>2</code> and <code>3</code> occur in both ranges.</li> </ul> <p>Return <em>the <strong>total number</strong> of ways to split</em> <code>ranges</code> <em>into two groups</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> ranges = [[6,10],[5,15]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ranges = [[1,3],[10,20],[2,5],[4,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ranges.length &lt;= 10<sup>5</sup></code></li> <li><code>ranges[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Array; Sorting
Python
class Solution: def countWays(self, ranges: List[List[int]]) -> int: ranges.sort() cnt, mx = 0, -1 for start, end in ranges: if start > mx: cnt += 1 mx = max(mx, end) mod = 10**9 + 7 return pow(2, cnt, mod)
2,580
Count Ways to Group Overlapping Ranges
Medium
<p>You are given a 2D integer array <code>ranges</code> where <code>ranges[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> denotes that all integers between <code>start<sub>i</sub></code> and <code>end<sub>i</sub></code> (both <strong>inclusive</strong>) are contained in the <code>i<sup>th</sup></code> range.</p> <p>You are to split <code>ranges</code> into <strong>two</strong> (possibly empty) groups such that:</p> <ul> <li>Each range belongs to exactly one group.</li> <li>Any two <strong>overlapping</strong> ranges must belong to the <strong>same</strong> group.</li> </ul> <p>Two ranges are said to be <strong>overlapping</strong>&nbsp;if there exists at least <strong>one</strong> integer that is present in both ranges.</p> <ul> <li>For example, <code>[1, 3]</code> and <code>[2, 5]</code> are overlapping because <code>2</code> and <code>3</code> occur in both ranges.</li> </ul> <p>Return <em>the <strong>total number</strong> of ways to split</em> <code>ranges</code> <em>into two groups</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> ranges = [[6,10],[5,15]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ranges = [[1,3],[10,20],[2,5],[4,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ranges.length &lt;= 10<sup>5</sup></code></li> <li><code>ranges[i].length == 2</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>9</sup></code></li> </ul>
Array; Sorting
TypeScript
function countWays(ranges: number[][]): number { ranges.sort((a, b) => a[0] - b[0]); let mx = -1; let ans = 1; const mod = 10 ** 9 + 7; for (const [start, end] of ranges) { if (start > mx) { ans = (ans * 2) % mod; } mx = Math.max(mx, end); } return ans; }