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,708
Maximum Strength of a Group
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the score of students in an exam. The teacher would like to form one <strong>non-empty</strong> group of students with maximal <strong>strength</strong>, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>​]</code>.</p> <p>Return <em>the maximum strength of a group the teacher can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,-1,-5,2,5,-9] <strong>Output:</strong> 1350 <strong>Explanation:</strong> One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-4,-5,-4] <strong>Output:</strong> 20 <strong>Explanation:</strong> Group the students at indices [0, 1] . Then, we&rsquo;ll have a resulting strength of 20. We cannot achieve greater strength. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 13</code></li> <li><code>-9 &lt;= nums[i] &lt;= 9</code></li> </ul>
Greedy; Bit Manipulation; Array; Dynamic Programming; Backtracking; Enumeration; Sorting
Python
class Solution: def maxStrength(self, nums: List[int]) -> int: ans = -inf for i in range(1, 1 << len(nums)): t = 1 for j, x in enumerate(nums): if i >> j & 1: t *= x ans = max(ans, t) return ans
2,708
Maximum Strength of a Group
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the score of students in an exam. The teacher would like to form one <strong>non-empty</strong> group of students with maximal <strong>strength</strong>, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>​]</code>.</p> <p>Return <em>the maximum strength of a group the teacher can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,-1,-5,2,5,-9] <strong>Output:</strong> 1350 <strong>Explanation:</strong> One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-4,-5,-4] <strong>Output:</strong> 20 <strong>Explanation:</strong> Group the students at indices [0, 1] . Then, we&rsquo;ll have a resulting strength of 20. We cannot achieve greater strength. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 13</code></li> <li><code>-9 &lt;= nums[i] &lt;= 9</code></li> </ul>
Greedy; Bit Manipulation; Array; Dynamic Programming; Backtracking; Enumeration; Sorting
TypeScript
function maxStrength(nums: number[]): number { let ans = -Infinity; const n = nums.length; for (let i = 1; i < 1 << n; ++i) { let t = 1; for (let j = 0; j < n; ++j) { if ((i >> j) & 1) { t *= nums[j]; } } ans = Math.max(ans, t); } return ans; }
2,709
Greatest Common Divisor Traversal
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and you are allowed to <strong>traverse</strong> between its indices. You can traverse between index <code>i</code> and index <code>j</code>, <code>i != j</code>, if and only if <code>gcd(nums[i], nums[j]) &gt; 1</code>, where <code>gcd</code> is the <strong>greatest common divisor</strong>.</p> <p>Your task is to determine if for <strong>every pair</strong> of indices <code>i</code> and <code>j</code> in nums, where <code>i &lt; j</code>, there exists a <strong>sequence of traversals</strong> that can take us from <code>i</code> to <code>j</code>.</p> <p>Return <code>true</code><em> if it is possible to traverse between all such pairs of indices,</em><em> or </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,6] <strong>Output:</strong> true <strong>Explanation:</strong> In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -&gt; 2 -&gt; 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 &gt; 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 &gt; 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,9,5] <strong>Output:</strong> false <strong>Explanation:</strong> No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,12,8] <strong>Output:</strong> true <strong>Explanation:</strong> There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true. </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>5</sup></code></li> </ul>
Union Find; Array; Math; Number Theory
C++
int MX = 100010; vector<int> P[100010]; int init = []() { for (int x = 1; x < MX; ++x) { int v = x; int i = 2; while (i <= v / i) { if (v % i == 0) { P[x].push_back(i); while (v % i == 0) { v /= i; } } ++i; } if (v > 1) { P[x].push_back(v); } } return 0; }(); class UnionFind { public: UnionFind(int n) { p = vector<int>(n); size = vector<int>(n, 1); iota(p.begin(), p.end(), 0); } bool unite(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } private: vector<int> p, size; }; class Solution { public: bool canTraverseAllPairs(vector<int>& nums) { int m = *max_element(nums.begin(), nums.end()); int n = nums.size(); UnionFind uf(m + n + 1); for (int i = 0; i < n; ++i) { for (int j : P[nums[i]]) { uf.unite(i, j + n); } } unordered_set<int> s; for (int i = 0; i < n; ++i) { s.insert(uf.find(i)); } return s.size() == 1; } };
2,709
Greatest Common Divisor Traversal
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and you are allowed to <strong>traverse</strong> between its indices. You can traverse between index <code>i</code> and index <code>j</code>, <code>i != j</code>, if and only if <code>gcd(nums[i], nums[j]) &gt; 1</code>, where <code>gcd</code> is the <strong>greatest common divisor</strong>.</p> <p>Your task is to determine if for <strong>every pair</strong> of indices <code>i</code> and <code>j</code> in nums, where <code>i &lt; j</code>, there exists a <strong>sequence of traversals</strong> that can take us from <code>i</code> to <code>j</code>.</p> <p>Return <code>true</code><em> if it is possible to traverse between all such pairs of indices,</em><em> or </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,6] <strong>Output:</strong> true <strong>Explanation:</strong> In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -&gt; 2 -&gt; 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 &gt; 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 &gt; 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,9,5] <strong>Output:</strong> false <strong>Explanation:</strong> No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,12,8] <strong>Output:</strong> true <strong>Explanation:</strong> There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true. </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>5</sup></code></li> </ul>
Union Find; Array; Math; Number Theory
Go
const mx = 100010 var p = make([][]int, mx) func init() { for x := 1; x < mx; x++ { v := x i := 2 for i <= v/i { if v%i == 0 { p[x] = append(p[x], i) for v%i == 0 { v /= i } } i++ } if v > 1 { p[x] = append(p[x], v) } } } type unionFind struct { p, size []int } func newUnionFind(n int) *unionFind { p := make([]int, n) size := make([]int, n) for i := range p { p[i] = i size[i] = 1 } return &unionFind{p, size} } func (uf *unionFind) find(x int) int { if uf.p[x] != x { uf.p[x] = uf.find(uf.p[x]) } return uf.p[x] } func (uf *unionFind) union(a, b int) bool { pa, pb := uf.find(a), uf.find(b) if pa == pb { return false } if uf.size[pa] > uf.size[pb] { uf.p[pb] = pa uf.size[pa] += uf.size[pb] } else { uf.p[pa] = pb uf.size[pb] += uf.size[pa] } return true } func canTraverseAllPairs(nums []int) bool { m := slices.Max(nums) n := len(nums) uf := newUnionFind(m + n + 1) for i, x := range nums { for _, j := range p[x] { uf.union(i, j+n) } } s := map[int]bool{} for i := 0; i < n; i++ { s[uf.find(i)] = true } return len(s) == 1 }
2,709
Greatest Common Divisor Traversal
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and you are allowed to <strong>traverse</strong> between its indices. You can traverse between index <code>i</code> and index <code>j</code>, <code>i != j</code>, if and only if <code>gcd(nums[i], nums[j]) &gt; 1</code>, where <code>gcd</code> is the <strong>greatest common divisor</strong>.</p> <p>Your task is to determine if for <strong>every pair</strong> of indices <code>i</code> and <code>j</code> in nums, where <code>i &lt; j</code>, there exists a <strong>sequence of traversals</strong> that can take us from <code>i</code> to <code>j</code>.</p> <p>Return <code>true</code><em> if it is possible to traverse between all such pairs of indices,</em><em> or </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,6] <strong>Output:</strong> true <strong>Explanation:</strong> In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -&gt; 2 -&gt; 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 &gt; 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 &gt; 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,9,5] <strong>Output:</strong> false <strong>Explanation:</strong> No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,12,8] <strong>Output:</strong> true <strong>Explanation:</strong> There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true. </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>5</sup></code></li> </ul>
Union Find; Array; Math; Number Theory
Java
class UnionFind { private int[] p; private int[] size; public UnionFind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; ++i) { p[i] = i; size[i] = 1; } } public int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } public boolean union(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } } class Solution { private static final int MX = 100010; private static final List<Integer>[] P = new List[MX]; static { Arrays.setAll(P, k -> new ArrayList<>()); for (int x = 1; x < MX; ++x) { int v = x; int i = 2; while (i <= v / i) { if (v % i == 0) { P[x].add(i); while (v % i == 0) { v /= i; } } ++i; } if (v > 1) { P[x].add(v); } } } public boolean canTraverseAllPairs(int[] nums) { int m = Arrays.stream(nums).max().getAsInt(); int n = nums.length; UnionFind uf = new UnionFind(n + m + 1); for (int i = 0; i < n; ++i) { for (int j : P[nums[i]]) { uf.union(i, j + n); } } Set<Integer> s = new HashSet<>(); for (int i = 0; i < n; ++i) { s.add(uf.find(i)); } return s.size() == 1; } }
2,709
Greatest Common Divisor Traversal
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, and you are allowed to <strong>traverse</strong> between its indices. You can traverse between index <code>i</code> and index <code>j</code>, <code>i != j</code>, if and only if <code>gcd(nums[i], nums[j]) &gt; 1</code>, where <code>gcd</code> is the <strong>greatest common divisor</strong>.</p> <p>Your task is to determine if for <strong>every pair</strong> of indices <code>i</code> and <code>j</code> in nums, where <code>i &lt; j</code>, there exists a <strong>sequence of traversals</strong> that can take us from <code>i</code> to <code>j</code>.</p> <p>Return <code>true</code><em> if it is possible to traverse between all such pairs of indices,</em><em> or </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,6] <strong>Output:</strong> true <strong>Explanation:</strong> In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2). To go from index 0 to index 1, we can use the sequence of traversals 0 -&gt; 2 -&gt; 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 &gt; 1. To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 &gt; 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 &gt; 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,9,5] <strong>Output:</strong> false <strong>Explanation:</strong> No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,12,8] <strong>Output:</strong> true <strong>Explanation:</strong> There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true. </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>5</sup></code></li> </ul>
Union Find; Array; Math; Number Theory
Python
class UnionFind: def __init__(self, n): self.p = list(range(n)) self.size = [1] * n def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, a, b): pa, pb = self.find(a), self.find(b) if pa == pb: return False if self.size[pa] > self.size[pb]: self.p[pb] = pa self.size[pa] += self.size[pb] else: self.p[pa] = pb self.size[pb] += self.size[pa] return True mx = 100010 p = defaultdict(list) for x in range(1, mx + 1): v = x i = 2 while i <= v // i: if v % i == 0: p[x].append(i) while v % i == 0: v //= i i += 1 if v > 1: p[x].append(v) class Solution: def canTraverseAllPairs(self, nums: List[int]) -> bool: n = len(nums) m = max(nums) uf = UnionFind(n + m + 1) for i, x in enumerate(nums): for j in p[x]: uf.union(i, j + n) return len(set(uf.find(i) for i in range(n))) == 1
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
C++
class Solution { public: string removeTrailingZeros(string num) { while (num.back() == '0') { num.pop_back(); } return num; } };
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
Go
func removeTrailingZeros(num string) string { i := len(num) - 1 for num[i] == '0' { i-- } return num[:i+1] }
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
Java
class Solution { public String removeTrailingZeros(String num) { int i = num.length() - 1; while (num.charAt(i) == '0') { --i; } return num.substring(0, i + 1); } }
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
Python
class Solution: def removeTrailingZeros(self, num: str) -> str: return num.rstrip("0")
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
Rust
impl Solution { pub fn remove_trailing_zeros(num: String) -> String { let mut i = num.len() - 1; while num.chars().nth(i) == Some('0') { i -= 1; } num[..i + 1].to_string() } }
2,710
Remove Trailing Zeros From a String
Easy
<p>Given a <strong>positive</strong> integer <code>num</code> represented as a string, return <em>the integer </em><code>num</code><em> without trailing zeros as a string</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;51230100&quot; <strong>Output:</strong> &quot;512301&quot; <strong>Explanation:</strong> Integer &quot;51230100&quot; has 2 trailing zeros, we remove them and return integer &quot;512301&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot; <strong>Output:</strong> &quot;123&quot; <strong>Explanation:</strong> Integer &quot;123&quot; has no trailing zeros, we return integer &quot;123&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 1000</code></li> <li><code>num</code> consists&nbsp;of only digits.</li> <li><code>num</code> doesn&#39;t&nbsp;have any leading zeros.</li> </ul>
String
TypeScript
function removeTrailingZeros(num: string): string { let i = num.length - 1; while (num[i] === '0') { --i; } return num.substring(0, i + 1); }
2,711
Difference of Number of Distinct Values on Diagonals
Medium
<p>Given a 2D <code>grid</code> of size <code>m x n</code>, you should find the matrix <code>answer</code> of size <code>m x n</code>.</p> <p>The cell <code>answer[r][c]</code> is calculated by looking at the diagonal values of the cell <code>grid[r][c]</code>:</p> <ul> <li>Let <code>leftAbove[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the left and above the cell <code>grid[r][c]</code> not including the cell <code>grid[r][c]</code> itself.</li> <li>Let <code>rightBelow[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the right and below the cell <code>grid[r][c]</code>, not including the cell <code>grid[r][c]</code> itself.</li> <li>Then <code>answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|</code>.</li> </ul> <p>A <strong>matrix diagonal</strong> is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.</p> <ul> <li>For example, in the below diagram the diagonal is highlighted using the cell with indices <code>(2, 3)</code> colored gray: <ul> <li>Red-colored cells are left and above the cell.</li> <li>Blue-colored cells are right and below the cell.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2711.Difference%20of%20Number%20of%20Distinct%20Values%20on%20Diagonals/images/diagonal.png" style="width: 200px; height: 160px;" /></p> <p>Return the matrix <code>answer</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">grid = [[1,2,3],[3,1,5],[3,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[1,1,0],[1,0,1],[0,1,1]]</span></p> <p><strong>Explanation:</strong></p> <p>To calculate the <code>answer</code> cells:</p> <table> <thead> <tr> <th>answer</th> <th>left-above elements</th> <th>leftAbove</th> <th>right-below elements</th> <th>rightBelow</th> <th>|leftAbove - rightBelow|</th> </tr> </thead> <tbody> <tr> <td>[0][0]</td> <td>[]</td> <td>0</td> <td>[grid[1][1], grid[2][2]]</td> <td>|{1, 1}| = 1</td> <td>1</td> </tr> <tr> <td>[0][1]</td> <td>[]</td> <td>0</td> <td>[grid[1][2]]</td> <td>|{5}| = 1</td> <td>1</td> </tr> <tr> <td>[0][2]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[1][0]</td> <td>[]</td> <td>0</td> <td>[grid[2][1]]</td> <td>|{2}| = 1</td> <td>1</td> </tr> <tr> <td>[1][1]</td> <td>[grid[0][0]]</td> <td>|{1}| = 1</td> <td>[grid[2][2]]</td> <td>|{1}| = 1</td> <td>0</td> </tr> <tr> <td>[1][2]</td> <td>[grid[0][1]]</td> <td>|{2}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][0]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[2][1]</td> <td>[grid[1][0]]</td> <td>|{3}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][2]</td> <td>[grid[0][0], grid[1][1]]</td> <td>|{1, 1}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[0]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n, grid[i][j] &lt;= 50</code></li> </ul>
Array; Hash Table; Matrix
C++
class Solution { public: vector<vector<int>> differenceOfDistinctValues(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> ans(m, vector<int>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int x = i, y = j; unordered_set<int> s; while (x > 0 && y > 0) { s.insert(grid[--x][--y]); } int tl = s.size(); x = i; y = j; s.clear(); while (x < m - 1 && y < n - 1) { s.insert(grid[++x][++y]); } int br = s.size(); ans[i][j] = abs(tl - br); } } return ans; } };
2,711
Difference of Number of Distinct Values on Diagonals
Medium
<p>Given a 2D <code>grid</code> of size <code>m x n</code>, you should find the matrix <code>answer</code> of size <code>m x n</code>.</p> <p>The cell <code>answer[r][c]</code> is calculated by looking at the diagonal values of the cell <code>grid[r][c]</code>:</p> <ul> <li>Let <code>leftAbove[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the left and above the cell <code>grid[r][c]</code> not including the cell <code>grid[r][c]</code> itself.</li> <li>Let <code>rightBelow[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the right and below the cell <code>grid[r][c]</code>, not including the cell <code>grid[r][c]</code> itself.</li> <li>Then <code>answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|</code>.</li> </ul> <p>A <strong>matrix diagonal</strong> is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.</p> <ul> <li>For example, in the below diagram the diagonal is highlighted using the cell with indices <code>(2, 3)</code> colored gray: <ul> <li>Red-colored cells are left and above the cell.</li> <li>Blue-colored cells are right and below the cell.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2711.Difference%20of%20Number%20of%20Distinct%20Values%20on%20Diagonals/images/diagonal.png" style="width: 200px; height: 160px;" /></p> <p>Return the matrix <code>answer</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">grid = [[1,2,3],[3,1,5],[3,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[1,1,0],[1,0,1],[0,1,1]]</span></p> <p><strong>Explanation:</strong></p> <p>To calculate the <code>answer</code> cells:</p> <table> <thead> <tr> <th>answer</th> <th>left-above elements</th> <th>leftAbove</th> <th>right-below elements</th> <th>rightBelow</th> <th>|leftAbove - rightBelow|</th> </tr> </thead> <tbody> <tr> <td>[0][0]</td> <td>[]</td> <td>0</td> <td>[grid[1][1], grid[2][2]]</td> <td>|{1, 1}| = 1</td> <td>1</td> </tr> <tr> <td>[0][1]</td> <td>[]</td> <td>0</td> <td>[grid[1][2]]</td> <td>|{5}| = 1</td> <td>1</td> </tr> <tr> <td>[0][2]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[1][0]</td> <td>[]</td> <td>0</td> <td>[grid[2][1]]</td> <td>|{2}| = 1</td> <td>1</td> </tr> <tr> <td>[1][1]</td> <td>[grid[0][0]]</td> <td>|{1}| = 1</td> <td>[grid[2][2]]</td> <td>|{1}| = 1</td> <td>0</td> </tr> <tr> <td>[1][2]</td> <td>[grid[0][1]]</td> <td>|{2}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][0]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[2][1]</td> <td>[grid[1][0]]</td> <td>|{3}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][2]</td> <td>[grid[0][0], grid[1][1]]</td> <td>|{1, 1}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[0]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n, grid[i][j] &lt;= 50</code></li> </ul>
Array; Hash Table; Matrix
Go
func differenceOfDistinctValues(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) ans := make([][]int, m) for i := range grid { ans[i] = make([]int, n) for j := range grid[i] { x, y := i, j s := map[int]bool{} for x > 0 && y > 0 { x, y = x-1, y-1 s[grid[x][y]] = true } tl := len(s) x, y = i, j s = map[int]bool{} for x+1 < m && y+1 < n { x, y = x+1, y+1 s[grid[x][y]] = true } br := len(s) ans[i][j] = abs(tl - br) } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
2,711
Difference of Number of Distinct Values on Diagonals
Medium
<p>Given a 2D <code>grid</code> of size <code>m x n</code>, you should find the matrix <code>answer</code> of size <code>m x n</code>.</p> <p>The cell <code>answer[r][c]</code> is calculated by looking at the diagonal values of the cell <code>grid[r][c]</code>:</p> <ul> <li>Let <code>leftAbove[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the left and above the cell <code>grid[r][c]</code> not including the cell <code>grid[r][c]</code> itself.</li> <li>Let <code>rightBelow[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the right and below the cell <code>grid[r][c]</code>, not including the cell <code>grid[r][c]</code> itself.</li> <li>Then <code>answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|</code>.</li> </ul> <p>A <strong>matrix diagonal</strong> is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.</p> <ul> <li>For example, in the below diagram the diagonal is highlighted using the cell with indices <code>(2, 3)</code> colored gray: <ul> <li>Red-colored cells are left and above the cell.</li> <li>Blue-colored cells are right and below the cell.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2711.Difference%20of%20Number%20of%20Distinct%20Values%20on%20Diagonals/images/diagonal.png" style="width: 200px; height: 160px;" /></p> <p>Return the matrix <code>answer</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">grid = [[1,2,3],[3,1,5],[3,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[1,1,0],[1,0,1],[0,1,1]]</span></p> <p><strong>Explanation:</strong></p> <p>To calculate the <code>answer</code> cells:</p> <table> <thead> <tr> <th>answer</th> <th>left-above elements</th> <th>leftAbove</th> <th>right-below elements</th> <th>rightBelow</th> <th>|leftAbove - rightBelow|</th> </tr> </thead> <tbody> <tr> <td>[0][0]</td> <td>[]</td> <td>0</td> <td>[grid[1][1], grid[2][2]]</td> <td>|{1, 1}| = 1</td> <td>1</td> </tr> <tr> <td>[0][1]</td> <td>[]</td> <td>0</td> <td>[grid[1][2]]</td> <td>|{5}| = 1</td> <td>1</td> </tr> <tr> <td>[0][2]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[1][0]</td> <td>[]</td> <td>0</td> <td>[grid[2][1]]</td> <td>|{2}| = 1</td> <td>1</td> </tr> <tr> <td>[1][1]</td> <td>[grid[0][0]]</td> <td>|{1}| = 1</td> <td>[grid[2][2]]</td> <td>|{1}| = 1</td> <td>0</td> </tr> <tr> <td>[1][2]</td> <td>[grid[0][1]]</td> <td>|{2}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][0]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[2][1]</td> <td>[grid[1][0]]</td> <td>|{3}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][2]</td> <td>[grid[0][0], grid[1][1]]</td> <td>|{1, 1}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[0]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n, grid[i][j] &lt;= 50</code></li> </ul>
Array; Hash Table; Matrix
Java
class Solution { public int[][] differenceOfDistinctValues(int[][] grid) { int m = grid.length, n = grid[0].length; int[][] ans = new int[m][n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int x = i, y = j; Set<Integer> s = new HashSet<>(); while (x > 0 && y > 0) { s.add(grid[--x][--y]); } int tl = s.size(); x = i; y = j; s.clear(); while (x < m - 1 && y < n - 1) { s.add(grid[++x][++y]); } int br = s.size(); ans[i][j] = Math.abs(tl - br); } } return ans; } }
2,711
Difference of Number of Distinct Values on Diagonals
Medium
<p>Given a 2D <code>grid</code> of size <code>m x n</code>, you should find the matrix <code>answer</code> of size <code>m x n</code>.</p> <p>The cell <code>answer[r][c]</code> is calculated by looking at the diagonal values of the cell <code>grid[r][c]</code>:</p> <ul> <li>Let <code>leftAbove[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the left and above the cell <code>grid[r][c]</code> not including the cell <code>grid[r][c]</code> itself.</li> <li>Let <code>rightBelow[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the right and below the cell <code>grid[r][c]</code>, not including the cell <code>grid[r][c]</code> itself.</li> <li>Then <code>answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|</code>.</li> </ul> <p>A <strong>matrix diagonal</strong> is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.</p> <ul> <li>For example, in the below diagram the diagonal is highlighted using the cell with indices <code>(2, 3)</code> colored gray: <ul> <li>Red-colored cells are left and above the cell.</li> <li>Blue-colored cells are right and below the cell.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2711.Difference%20of%20Number%20of%20Distinct%20Values%20on%20Diagonals/images/diagonal.png" style="width: 200px; height: 160px;" /></p> <p>Return the matrix <code>answer</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">grid = [[1,2,3],[3,1,5],[3,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[1,1,0],[1,0,1],[0,1,1]]</span></p> <p><strong>Explanation:</strong></p> <p>To calculate the <code>answer</code> cells:</p> <table> <thead> <tr> <th>answer</th> <th>left-above elements</th> <th>leftAbove</th> <th>right-below elements</th> <th>rightBelow</th> <th>|leftAbove - rightBelow|</th> </tr> </thead> <tbody> <tr> <td>[0][0]</td> <td>[]</td> <td>0</td> <td>[grid[1][1], grid[2][2]]</td> <td>|{1, 1}| = 1</td> <td>1</td> </tr> <tr> <td>[0][1]</td> <td>[]</td> <td>0</td> <td>[grid[1][2]]</td> <td>|{5}| = 1</td> <td>1</td> </tr> <tr> <td>[0][2]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[1][0]</td> <td>[]</td> <td>0</td> <td>[grid[2][1]]</td> <td>|{2}| = 1</td> <td>1</td> </tr> <tr> <td>[1][1]</td> <td>[grid[0][0]]</td> <td>|{1}| = 1</td> <td>[grid[2][2]]</td> <td>|{1}| = 1</td> <td>0</td> </tr> <tr> <td>[1][2]</td> <td>[grid[0][1]]</td> <td>|{2}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][0]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[2][1]</td> <td>[grid[1][0]]</td> <td>|{3}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][2]</td> <td>[grid[0][0], grid[1][1]]</td> <td>|{1, 1}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[0]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n, grid[i][j] &lt;= 50</code></li> </ul>
Array; Hash Table; Matrix
Python
class Solution: def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): x, y = i, j s = set() while x and y: x, y = x - 1, y - 1 s.add(grid[x][y]) tl = len(s) x, y = i, j s = set() while x + 1 < m and y + 1 < n: x, y = x + 1, y + 1 s.add(grid[x][y]) br = len(s) ans[i][j] = abs(tl - br) return ans
2,711
Difference of Number of Distinct Values on Diagonals
Medium
<p>Given a 2D <code>grid</code> of size <code>m x n</code>, you should find the matrix <code>answer</code> of size <code>m x n</code>.</p> <p>The cell <code>answer[r][c]</code> is calculated by looking at the diagonal values of the cell <code>grid[r][c]</code>:</p> <ul> <li>Let <code>leftAbove[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the left and above the cell <code>grid[r][c]</code> not including the cell <code>grid[r][c]</code> itself.</li> <li>Let <code>rightBelow[r][c]</code> be the number of <strong>distinct</strong> values on the diagonal to the right and below the cell <code>grid[r][c]</code>, not including the cell <code>grid[r][c]</code> itself.</li> <li>Then <code>answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|</code>.</li> </ul> <p>A <strong>matrix diagonal</strong> is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.</p> <ul> <li>For example, in the below diagram the diagonal is highlighted using the cell with indices <code>(2, 3)</code> colored gray: <ul> <li>Red-colored cells are left and above the cell.</li> <li>Blue-colored cells are right and below the cell.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2711.Difference%20of%20Number%20of%20Distinct%20Values%20on%20Diagonals/images/diagonal.png" style="width: 200px; height: 160px;" /></p> <p>Return the matrix <code>answer</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">grid = [[1,2,3],[3,1,5],[3,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[1,1,0],[1,0,1],[0,1,1]]</span></p> <p><strong>Explanation:</strong></p> <p>To calculate the <code>answer</code> cells:</p> <table> <thead> <tr> <th>answer</th> <th>left-above elements</th> <th>leftAbove</th> <th>right-below elements</th> <th>rightBelow</th> <th>|leftAbove - rightBelow|</th> </tr> </thead> <tbody> <tr> <td>[0][0]</td> <td>[]</td> <td>0</td> <td>[grid[1][1], grid[2][2]]</td> <td>|{1, 1}| = 1</td> <td>1</td> </tr> <tr> <td>[0][1]</td> <td>[]</td> <td>0</td> <td>[grid[1][2]]</td> <td>|{5}| = 1</td> <td>1</td> </tr> <tr> <td>[0][2]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[1][0]</td> <td>[]</td> <td>0</td> <td>[grid[2][1]]</td> <td>|{2}| = 1</td> <td>1</td> </tr> <tr> <td>[1][1]</td> <td>[grid[0][0]]</td> <td>|{1}| = 1</td> <td>[grid[2][2]]</td> <td>|{1}| = 1</td> <td>0</td> </tr> <tr> <td>[1][2]</td> <td>[grid[0][1]]</td> <td>|{2}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][0]</td> <td>[]</td> <td>0</td> <td>[]</td> <td>0</td> <td>0</td> </tr> <tr> <td>[2][1]</td> <td>[grid[1][0]]</td> <td>|{3}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> <tr> <td>[2][2]</td> <td>[grid[0][0], grid[1][1]]</td> <td>|{1, 1}| = 1</td> <td>[]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">Output: [[0]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n, grid[i][j] &lt;= 50</code></li> </ul>
Array; Hash Table; Matrix
TypeScript
function differenceOfDistinctValues(grid: number[][]): number[][] { const m = grid.length; const n = grid[0].length; const ans: number[][] = Array(m) .fill(0) .map(() => Array(n).fill(0)); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { let [x, y] = [i, j]; const s = new Set<number>(); while (x && y) { s.add(grid[--x][--y]); } const tl = s.size; [x, y] = [i, j]; s.clear(); while (x + 1 < m && y + 1 < n) { s.add(grid[++x][++y]); } const br = s.size; ans[i][j] = Math.abs(tl - br); } } return ans; }
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
C++
class Solution { public: long long minimumCost(string s) { long long ans = 0; int n = s.size(); for (int i = 1; i < n; ++i) { if (s[i] != s[i - 1]) { ans += min(i, n - i); } } return ans; } };
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
Go
func minimumCost(s string) (ans int64) { n := len(s) for i := 1; i < n; i++ { if s[i] != s[i-1] { ans += int64(min(i, n-i)) } } return }
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
Java
class Solution { public long minimumCost(String s) { long ans = 0; int n = s.length(); for (int i = 1; i < n; ++i) { if (s.charAt(i) != s.charAt(i - 1)) { ans += Math.min(i, n - i); } } return ans; } }
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
Python
class Solution: def minimumCost(self, s: str) -> int: ans, n = 0, len(s) for i in range(1, n): if s[i] != s[i - 1]: ans += min(i, n - i) return ans
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
Rust
impl Solution { pub fn minimum_cost(s: String) -> i64 { let mut ans = 0; let n = s.len(); let s = s.as_bytes(); for i in 1..n { if s[i] != s[i - 1] { ans += i.min(n - i); } } ans as i64 } }
2,712
Minimum Cost to Make All Characters Equal
Medium
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code> on which you can apply two types of operations:</p> <ul> <li>Choose an index <code>i</code> and invert all characters from&nbsp;index <code>0</code> to index <code>i</code>&nbsp;(both inclusive), with a cost of <code>i + 1</code></li> <li>Choose an index <code>i</code> and invert all characters&nbsp;from&nbsp;index <code>i</code> to index <code>n - 1</code>&nbsp;(both inclusive), with a cost of <code>n - i</code></li> </ul> <p>Return <em>the <strong>minimum cost </strong>to make all characters of the string <strong>equal</strong></em>.</p> <p><strong>Invert</strong> a character means&nbsp;if its value is &#39;0&#39; it becomes &#39;1&#39; and vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;0011&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Apply the second operation with <code>i = 2</code> to obtain <code>s = &quot;0000&quot; for a cost of 2</code>. It can be shown that 2 is the minimum cost to make all characters equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;010101&quot; <strong>Output:</strong> 9 <strong>Explanation:</strong> Apply the first operation with i = 2 to obtain s = &quot;101101&quot; for a cost of 3. Apply the first operation with i = 1 to obtain s = &quot;011101&quot; for a cost of 2. Apply the first operation with i = 0 to obtain s = &quot;111101&quot; for a cost of 1. Apply the second operation with i = 4 to obtain s = &quot;111110&quot; for a cost of 2. Apply the second operation with i = 5 to obtain s = &quot;111111&quot; for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == n &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
Greedy; String; Dynamic Programming
TypeScript
function minimumCost(s: string): number { let ans = 0; const n = s.length; for (let i = 1; i < n; ++i) { if (s[i] !== s[i - 1]) { ans += Math.min(i, n - i); } } return ans; }
2,713
Maximum Strictly Increasing Cells in a Matrix
Hard
<p>Given a <strong>1-indexed</strong>&nbsp;<code>m x n</code> integer matrix <code>mat</code>, you can select any cell in the matrix as your <strong>starting cell</strong>.</p> <p>From the starting cell, you can move to any other cell <strong>in the</strong> <strong>same row or column</strong>, but only if the value of the destination cell is <strong>strictly greater</strong> than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.</p> <p>Your task is to find the <strong>maximum number of cells</strong> that you can visit in the matrix by starting from some cell.</p> <p>Return <em>an integer denoting the maximum number of cells that can be visited.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag1drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag3drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[1,1],[1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> Since the cells must be strictly increasing, we can only visit one cell in this example. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag4drawio.png" style="width: 350px; height: 250px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1,6],[-9,5,7]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length&nbsp;</code></li> <li><code>n == mat[i].length&nbsp;</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Memoization; Array; Hash Table; Binary Search; Dynamic Programming; Matrix; Ordered Set; Sorting
C++
class Solution { public: int maxIncreasingCells(vector<vector<int>>& mat) { int m = mat.size(), n = mat[0].size(); map<int, vector<pair<int, int>>> g; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { g[mat[i][j]].emplace_back(i, j); } } vector<int> rowMax(m); vector<int> colMax(n); int ans = 0; for (auto& [_, pos] : g) { vector<int> mx; for (auto& [i, j] : pos) { mx.push_back(max(rowMax[i], colMax[j]) + 1); ans = max(ans, mx.back()); } for (int k = 0; k < mx.size(); ++k) { auto& [i, j] = pos[k]; rowMax[i] = max(rowMax[i], mx[k]); colMax[j] = max(colMax[j], mx[k]); } } return ans; } };
2,713
Maximum Strictly Increasing Cells in a Matrix
Hard
<p>Given a <strong>1-indexed</strong>&nbsp;<code>m x n</code> integer matrix <code>mat</code>, you can select any cell in the matrix as your <strong>starting cell</strong>.</p> <p>From the starting cell, you can move to any other cell <strong>in the</strong> <strong>same row or column</strong>, but only if the value of the destination cell is <strong>strictly greater</strong> than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.</p> <p>Your task is to find the <strong>maximum number of cells</strong> that you can visit in the matrix by starting from some cell.</p> <p>Return <em>an integer denoting the maximum number of cells that can be visited.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag1drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag3drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[1,1],[1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> Since the cells must be strictly increasing, we can only visit one cell in this example. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag4drawio.png" style="width: 350px; height: 250px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1,6],[-9,5,7]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length&nbsp;</code></li> <li><code>n == mat[i].length&nbsp;</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Memoization; Array; Hash Table; Binary Search; Dynamic Programming; Matrix; Ordered Set; Sorting
Go
func maxIncreasingCells(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) g := map[int][][2]int{} for i, row := range mat { for j, v := range row { g[v] = append(g[v], [2]int{i, j}) } } nums := make([]int, 0, len(g)) for k := range g { nums = append(nums, k) } sort.Ints(nums) rowMax := make([]int, m) colMax := make([]int, n) for _, k := range nums { pos := g[k] mx := make([]int, len(pos)) for i, p := range pos { mx[i] = max(rowMax[p[0]], colMax[p[1]]) + 1 ans = max(ans, mx[i]) } for i, p := range pos { rowMax[p[0]] = max(rowMax[p[0]], mx[i]) colMax[p[1]] = max(colMax[p[1]], mx[i]) } } return }
2,713
Maximum Strictly Increasing Cells in a Matrix
Hard
<p>Given a <strong>1-indexed</strong>&nbsp;<code>m x n</code> integer matrix <code>mat</code>, you can select any cell in the matrix as your <strong>starting cell</strong>.</p> <p>From the starting cell, you can move to any other cell <strong>in the</strong> <strong>same row or column</strong>, but only if the value of the destination cell is <strong>strictly greater</strong> than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.</p> <p>Your task is to find the <strong>maximum number of cells</strong> that you can visit in the matrix by starting from some cell.</p> <p>Return <em>an integer denoting the maximum number of cells that can be visited.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag1drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag3drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[1,1],[1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> Since the cells must be strictly increasing, we can only visit one cell in this example. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag4drawio.png" style="width: 350px; height: 250px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1,6],[-9,5,7]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length&nbsp;</code></li> <li><code>n == mat[i].length&nbsp;</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Memoization; Array; Hash Table; Binary Search; Dynamic Programming; Matrix; Ordered Set; Sorting
Java
class Solution { public int maxIncreasingCells(int[][] mat) { int m = mat.length, n = mat[0].length; TreeMap<Integer, List<int[]>> g = new TreeMap<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { g.computeIfAbsent(mat[i][j], k -> new ArrayList<>()).add(new int[] {i, j}); } } int[] rowMax = new int[m]; int[] colMax = new int[n]; int ans = 0; for (var e : g.entrySet()) { var pos = e.getValue(); int[] mx = new int[pos.size()]; int k = 0; for (var p : pos) { int i = p[0], j = p[1]; mx[k] = Math.max(rowMax[i], colMax[j]) + 1; ans = Math.max(ans, mx[k++]); } for (k = 0; k < mx.length; ++k) { int i = pos.get(k)[0], j = pos.get(k)[1]; rowMax[i] = Math.max(rowMax[i], mx[k]); colMax[j] = Math.max(colMax[j], mx[k]); } } return ans; } }
2,713
Maximum Strictly Increasing Cells in a Matrix
Hard
<p>Given a <strong>1-indexed</strong>&nbsp;<code>m x n</code> integer matrix <code>mat</code>, you can select any cell in the matrix as your <strong>starting cell</strong>.</p> <p>From the starting cell, you can move to any other cell <strong>in the</strong> <strong>same row or column</strong>, but only if the value of the destination cell is <strong>strictly greater</strong> than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.</p> <p>Your task is to find the <strong>maximum number of cells</strong> that you can visit in the matrix by starting from some cell.</p> <p>Return <em>an integer denoting the maximum number of cells that can be visited.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag1drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag3drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[1,1],[1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> Since the cells must be strictly increasing, we can only visit one cell in this example. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag4drawio.png" style="width: 350px; height: 250px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1,6],[-9,5,7]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length&nbsp;</code></li> <li><code>n == mat[i].length&nbsp;</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Memoization; Array; Hash Table; Binary Search; Dynamic Programming; Matrix; Ordered Set; Sorting
Python
class Solution: def maxIncreasingCells(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) g = defaultdict(list) for i in range(m): for j in range(n): g[mat[i][j]].append((i, j)) rowMax = [0] * m colMax = [0] * n ans = 0 for _, pos in sorted(g.items()): mx = [] for i, j in pos: mx.append(1 + max(rowMax[i], colMax[j])) ans = max(ans, mx[-1]) for k, (i, j) in enumerate(pos): rowMax[i] = max(rowMax[i], mx[k]) colMax[j] = max(colMax[j], mx[k]) return ans
2,713
Maximum Strictly Increasing Cells in a Matrix
Hard
<p>Given a <strong>1-indexed</strong>&nbsp;<code>m x n</code> integer matrix <code>mat</code>, you can select any cell in the matrix as your <strong>starting cell</strong>.</p> <p>From the starting cell, you can move to any other cell <strong>in the</strong> <strong>same row or column</strong>, but only if the value of the destination cell is <strong>strictly greater</strong> than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.</p> <p>Your task is to find the <strong>maximum number of cells</strong> that you can visit in the matrix by starting from some cell.</p> <p>Return <em>an integer denoting the maximum number of cells that can be visited.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag1drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1],[3,4]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag3drawio.png" style="width: 200px; height: 176px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[1,1],[1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> Since the cells must be strictly increasing, we can only visit one cell in this example. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2713.Maximum%20Strictly%20Increasing%20Cells%20in%20a%20Matrix/images/diag4drawio.png" style="width: 350px; height: 250px;" /></strong></p> <pre> <strong>Input:</strong> mat = [[3,1,6],[-9,5,7]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length&nbsp;</code></li> <li><code>n == mat[i].length&nbsp;</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup>&nbsp;&lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Memoization; Array; Hash Table; Binary Search; Dynamic Programming; Matrix; Ordered Set; Sorting
TypeScript
function maxIncreasingCells(mat: number[][]): number { const m = mat.length; const n = mat[0].length; const g: { [key: number]: [number, number][] } = {}; for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (!g[mat[i][j]]) { g[mat[i][j]] = []; } g[mat[i][j]].push([i, j]); } } const rowMax = Array(m).fill(0); const colMax = Array(n).fill(0); let ans = 0; const sortedKeys = Object.keys(g) .map(Number) .sort((a, b) => a - b); for (const key of sortedKeys) { const pos = g[key]; const mx: number[] = []; for (const [i, j] of pos) { mx.push(1 + Math.max(rowMax[i], colMax[j])); ans = Math.max(ans, mx[mx.length - 1]); } for (let k = 0; k < pos.length; k++) { const [i, j] = pos[k]; rowMax[i] = Math.max(rowMax[i], mx[k]); colMax[j] = Math.max(colMax[j], mx[k]); } } return ans; }
2,714
Find Shortest Path with K Hops
Hard
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed undirected weighted connected</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p> <p>You are also given two&nbsp;nodes <code>s</code> and <code>d</code>, and a positive integer <code>k</code>, your task is to find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>, but you can hop over <strong>at most</strong> <code>k</code> edges. In other words,&nbsp;make the weight of <strong>at most</strong> <code>k</code> edges <code>0</code> and then find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> path from </em><code>s</code><em> to </em><code>d</code><em> with the given condition</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[0,1,4],[0,2,2],[2,3,6]], s = 1, d = 3, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example there is only one path from node 1 (the green node) to node 3 (the red node), which is (1-&gt;0-&gt;2-&gt;3) and the length of it is 4 + 2 + 6 = 12. Now we can make weight of two edges 0, we make weight of the blue edges 0, then we have 0 + 2 + 0 = 2. It can be shown that 2 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/1.jpg" style="width: 170px; height: 171px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7, edges = [[3,1,9],[3,2,4],[4,0,9],[0,5,6],[3,6,2],[6,0,4],[1,2,4]], s = 4, d = 1, k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example there are 2 paths from node 4 (the green node) to node 1 (the red node), which are (4-&gt;0-&gt;6-&gt;3-&gt;2-&gt;1) and (4-&gt;0-&gt;6-&gt;3-&gt;1). The first one has the length 9 + 4 + 2 + 4 + 4 = 23, and the second one has the length 9 + 4 + 2 + 9 = 24. Now if we make weight of the blue edges 0, we get the shortest path with the length 0 + 4 + 2 + 0 = 6. It can be shown that 6 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/2.jpg" style="width: 400px; height: 171px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[0,4,2],[0,1,3],[0,2,1],[2,1,4],[1,3,4],[3,4,7]], s = 2, d = 3, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example there are 4 paths from node 2 (the green node) to node 3 (the red node), which are (2-&gt;1-&gt;3), (2-&gt;0-&gt;1-&gt;3), (2-&gt;1-&gt;0-&gt;4-&gt;3) and (2-&gt;0-&gt;4-&gt;3). The first two have the length 4 + 4 = 1 + 3 + 4 = 8, the third one has the length 4 + 3 + 2 + 7 = 16 and the last one has the length 1 + 2 + 7 = 10. Now if we make weight of the blue edge 0, we get the shortest path with the length 1 + 2 + 0 = 3. It can be shown that 3 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/3.jpg" style="width: 300px; height: 296px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 500</code></li> <li><code>n - 1 &lt;= edges.length &lt;= min(10<sup>4</sup>, n * (n - 1) / 2)</code></li> <li><code>edges[i].length = 3</code></li> <li><code>0 &lt;= edges[i][0], edges[i][1] &lt;= n - 1</code></li> <li><code>1 &lt;= edges[i][2] &lt;=&nbsp;10<sup>6</sup></code></li> <li><code>0 &lt;= s, d, k&nbsp;&lt;= n - 1</code></li> <li><code>s != d</code></li> <li>The input is generated such that the graph is <strong>connected</strong> and has <strong>no</strong>&nbsp;<strong>repeated edges</strong>&nbsp;or&nbsp;<strong>self-loops</strong></li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int shortestPathWithHops(int n, vector<vector<int>>& edges, int s, int d, int k) { vector<pair<int, int>> g[n]; for (auto& e : edges) { int u = e[0], v = e[1], w = e[2]; g[u].emplace_back(v, w); g[v].emplace_back(u, w); } priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; pq.emplace(0, s, 0); int dist[n][k + 1]; memset(dist, 0x3f, sizeof(dist)); dist[s][0] = 0; while (!pq.empty()) { auto [dis, u, t] = pq.top(); pq.pop(); for (auto [v, w] : g[u]) { if (t + 1 <= k && dist[v][t + 1] > dis) { dist[v][t + 1] = dis; pq.emplace(dis, v, t + 1); } if (dist[v][t] > dis + w) { dist[v][t] = dis + w; pq.emplace(dis + w, v, t); } } } return *min_element(dist[d], dist[d] + k + 1); } };
2,714
Find Shortest Path with K Hops
Hard
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed undirected weighted connected</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p> <p>You are also given two&nbsp;nodes <code>s</code> and <code>d</code>, and a positive integer <code>k</code>, your task is to find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>, but you can hop over <strong>at most</strong> <code>k</code> edges. In other words,&nbsp;make the weight of <strong>at most</strong> <code>k</code> edges <code>0</code> and then find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> path from </em><code>s</code><em> to </em><code>d</code><em> with the given condition</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[0,1,4],[0,2,2],[2,3,6]], s = 1, d = 3, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example there is only one path from node 1 (the green node) to node 3 (the red node), which is (1-&gt;0-&gt;2-&gt;3) and the length of it is 4 + 2 + 6 = 12. Now we can make weight of two edges 0, we make weight of the blue edges 0, then we have 0 + 2 + 0 = 2. It can be shown that 2 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/1.jpg" style="width: 170px; height: 171px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7, edges = [[3,1,9],[3,2,4],[4,0,9],[0,5,6],[3,6,2],[6,0,4],[1,2,4]], s = 4, d = 1, k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example there are 2 paths from node 4 (the green node) to node 1 (the red node), which are (4-&gt;0-&gt;6-&gt;3-&gt;2-&gt;1) and (4-&gt;0-&gt;6-&gt;3-&gt;1). The first one has the length 9 + 4 + 2 + 4 + 4 = 23, and the second one has the length 9 + 4 + 2 + 9 = 24. Now if we make weight of the blue edges 0, we get the shortest path with the length 0 + 4 + 2 + 0 = 6. It can be shown that 6 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/2.jpg" style="width: 400px; height: 171px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[0,4,2],[0,1,3],[0,2,1],[2,1,4],[1,3,4],[3,4,7]], s = 2, d = 3, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example there are 4 paths from node 2 (the green node) to node 3 (the red node), which are (2-&gt;1-&gt;3), (2-&gt;0-&gt;1-&gt;3), (2-&gt;1-&gt;0-&gt;4-&gt;3) and (2-&gt;0-&gt;4-&gt;3). The first two have the length 4 + 4 = 1 + 3 + 4 = 8, the third one has the length 4 + 3 + 2 + 7 = 16 and the last one has the length 1 + 2 + 7 = 10. Now if we make weight of the blue edge 0, we get the shortest path with the length 1 + 2 + 0 = 3. It can be shown that 3 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/3.jpg" style="width: 300px; height: 296px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 500</code></li> <li><code>n - 1 &lt;= edges.length &lt;= min(10<sup>4</sup>, n * (n - 1) / 2)</code></li> <li><code>edges[i].length = 3</code></li> <li><code>0 &lt;= edges[i][0], edges[i][1] &lt;= n - 1</code></li> <li><code>1 &lt;= edges[i][2] &lt;=&nbsp;10<sup>6</sup></code></li> <li><code>0 &lt;= s, d, k&nbsp;&lt;= n - 1</code></li> <li><code>s != d</code></li> <li>The input is generated such that the graph is <strong>connected</strong> and has <strong>no</strong>&nbsp;<strong>repeated edges</strong>&nbsp;or&nbsp;<strong>self-loops</strong></li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Go
func shortestPathWithHops(n int, edges [][]int, s int, d int, k int) int { g := make([][][2]int, n) for _, e := range edges { u, v, w := e[0], e[1], e[2] g[u] = append(g[u], [2]int{v, w}) g[v] = append(g[v], [2]int{u, w}) } pq := hp{{0, s, 0}} dist := make([][]int, n) for i := range dist { dist[i] = make([]int, k+1) for j := range dist[i] { dist[i][j] = math.MaxInt32 } } dist[s][0] = 0 for len(pq) > 0 { p := heap.Pop(&pq).(tuple) dis, u, t := p.dis, p.u, p.t for _, e := range g[u] { v, w := e[0], e[1] if t+1 <= k && dist[v][t+1] > dis { dist[v][t+1] = dis heap.Push(&pq, tuple{dis, v, t + 1}) } if dist[v][t] > dis+w { dist[v][t] = dis + w heap.Push(&pq, tuple{dis + w, v, t}) } } } return slices.Min(dist[d]) } type tuple struct{ dis, u, t int } type hp []tuple func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].dis < h[j].dis } 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,714
Find Shortest Path with K Hops
Hard
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed undirected weighted connected</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p> <p>You are also given two&nbsp;nodes <code>s</code> and <code>d</code>, and a positive integer <code>k</code>, your task is to find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>, but you can hop over <strong>at most</strong> <code>k</code> edges. In other words,&nbsp;make the weight of <strong>at most</strong> <code>k</code> edges <code>0</code> and then find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> path from </em><code>s</code><em> to </em><code>d</code><em> with the given condition</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[0,1,4],[0,2,2],[2,3,6]], s = 1, d = 3, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example there is only one path from node 1 (the green node) to node 3 (the red node), which is (1-&gt;0-&gt;2-&gt;3) and the length of it is 4 + 2 + 6 = 12. Now we can make weight of two edges 0, we make weight of the blue edges 0, then we have 0 + 2 + 0 = 2. It can be shown that 2 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/1.jpg" style="width: 170px; height: 171px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7, edges = [[3,1,9],[3,2,4],[4,0,9],[0,5,6],[3,6,2],[6,0,4],[1,2,4]], s = 4, d = 1, k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example there are 2 paths from node 4 (the green node) to node 1 (the red node), which are (4-&gt;0-&gt;6-&gt;3-&gt;2-&gt;1) and (4-&gt;0-&gt;6-&gt;3-&gt;1). The first one has the length 9 + 4 + 2 + 4 + 4 = 23, and the second one has the length 9 + 4 + 2 + 9 = 24. Now if we make weight of the blue edges 0, we get the shortest path with the length 0 + 4 + 2 + 0 = 6. It can be shown that 6 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/2.jpg" style="width: 400px; height: 171px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[0,4,2],[0,1,3],[0,2,1],[2,1,4],[1,3,4],[3,4,7]], s = 2, d = 3, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example there are 4 paths from node 2 (the green node) to node 3 (the red node), which are (2-&gt;1-&gt;3), (2-&gt;0-&gt;1-&gt;3), (2-&gt;1-&gt;0-&gt;4-&gt;3) and (2-&gt;0-&gt;4-&gt;3). The first two have the length 4 + 4 = 1 + 3 + 4 = 8, the third one has the length 4 + 3 + 2 + 7 = 16 and the last one has the length 1 + 2 + 7 = 10. Now if we make weight of the blue edge 0, we get the shortest path with the length 1 + 2 + 0 = 3. It can be shown that 3 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/3.jpg" style="width: 300px; height: 296px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 500</code></li> <li><code>n - 1 &lt;= edges.length &lt;= min(10<sup>4</sup>, n * (n - 1) / 2)</code></li> <li><code>edges[i].length = 3</code></li> <li><code>0 &lt;= edges[i][0], edges[i][1] &lt;= n - 1</code></li> <li><code>1 &lt;= edges[i][2] &lt;=&nbsp;10<sup>6</sup></code></li> <li><code>0 &lt;= s, d, k&nbsp;&lt;= n - 1</code></li> <li><code>s != d</code></li> <li>The input is generated such that the graph is <strong>connected</strong> and has <strong>no</strong>&nbsp;<strong>repeated edges</strong>&nbsp;or&nbsp;<strong>self-loops</strong></li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int shortestPathWithHops(int n, int[][] edges, int s, int d, int k) { List<int[]>[] g = new List[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (int[] e : edges) { int u = e[0], v = e[1], w = e[2]; g[u].add(new int[] {v, w}); g[v].add(new int[] {u, w}); } PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); pq.offer(new int[] {0, s, 0}); int[][] dist = new int[n][k + 1]; final int inf = 1 << 30; for (int[] e : dist) { Arrays.fill(e, inf); } dist[s][0] = 0; while (!pq.isEmpty()) { int[] p = pq.poll(); int dis = p[0], u = p[1], t = p[2]; for (int[] e : g[u]) { int v = e[0], w = e[1]; if (t + 1 <= k && dist[v][t + 1] > dis) { dist[v][t + 1] = dis; pq.offer(new int[] {dis, v, t + 1}); } if (dist[v][t] > dis + w) { dist[v][t] = dis + w; pq.offer(new int[] {dis + w, v, t}); } } } int ans = inf; for (int i = 0; i <= k; ++i) { ans = Math.min(ans, dist[d][i]); } return ans; } }
2,714
Find Shortest Path with K Hops
Hard
<p>You are given a positive integer <code>n</code> which is the number of nodes of a <strong>0-indexed undirected weighted connected</strong> graph and a <strong>0-indexed</strong> <strong>2D array</strong> <code>edges</code> where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.</p> <p>You are also given two&nbsp;nodes <code>s</code> and <code>d</code>, and a positive integer <code>k</code>, your task is to find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>, but you can hop over <strong>at most</strong> <code>k</code> edges. In other words,&nbsp;make the weight of <strong>at most</strong> <code>k</code> edges <code>0</code> and then find the <strong>shortest</strong> path from <code>s</code> to <code>d</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> path from </em><code>s</code><em> to </em><code>d</code><em> with the given condition</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[0,1,4],[0,2,2],[2,3,6]], s = 1, d = 3, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example there is only one path from node 1 (the green node) to node 3 (the red node), which is (1-&gt;0-&gt;2-&gt;3) and the length of it is 4 + 2 + 6 = 12. Now we can make weight of two edges 0, we make weight of the blue edges 0, then we have 0 + 2 + 0 = 2. It can be shown that 2 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/1.jpg" style="width: 170px; height: 171px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7, edges = [[3,1,9],[3,2,4],[4,0,9],[0,5,6],[3,6,2],[6,0,4],[1,2,4]], s = 4, d = 1, k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example there are 2 paths from node 4 (the green node) to node 1 (the red node), which are (4-&gt;0-&gt;6-&gt;3-&gt;2-&gt;1) and (4-&gt;0-&gt;6-&gt;3-&gt;1). The first one has the length 9 + 4 + 2 + 4 + 4 = 23, and the second one has the length 9 + 4 + 2 + 9 = 24. Now if we make weight of the blue edges 0, we get the shortest path with the length 0 + 4 + 2 + 0 = 6. It can be shown that 6 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/2.jpg" style="width: 400px; height: 171px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[0,4,2],[0,1,3],[0,2,1],[2,1,4],[1,3,4],[3,4,7]], s = 2, d = 3, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example there are 4 paths from node 2 (the green node) to node 3 (the red node), which are (2-&gt;1-&gt;3), (2-&gt;0-&gt;1-&gt;3), (2-&gt;1-&gt;0-&gt;4-&gt;3) and (2-&gt;0-&gt;4-&gt;3). The first two have the length 4 + 4 = 1 + 3 + 4 = 8, the third one has the length 4 + 3 + 2 + 7 = 16 and the last one has the length 1 + 2 + 7 = 10. Now if we make weight of the blue edge 0, we get the shortest path with the length 1 + 2 + 0 = 3. It can be shown that 3 is the minimum length of a path we can achieve with the given condition. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2714.Find%20Shortest%20Path%20with%20K%20Hops/images/3.jpg" style="width: 300px; height: 296px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 500</code></li> <li><code>n - 1 &lt;= edges.length &lt;= min(10<sup>4</sup>, n * (n - 1) / 2)</code></li> <li><code>edges[i].length = 3</code></li> <li><code>0 &lt;= edges[i][0], edges[i][1] &lt;= n - 1</code></li> <li><code>1 &lt;= edges[i][2] &lt;=&nbsp;10<sup>6</sup></code></li> <li><code>0 &lt;= s, d, k&nbsp;&lt;= n - 1</code></li> <li><code>s != d</code></li> <li>The input is generated such that the graph is <strong>connected</strong> and has <strong>no</strong>&nbsp;<strong>repeated edges</strong>&nbsp;or&nbsp;<strong>self-loops</strong></li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Python
class Solution: def shortestPathWithHops( self, n: int, edges: List[List[int]], s: int, d: int, k: int ) -> int: g = [[] for _ in range(n)] for u, v, w in edges: g[u].append((v, w)) g[v].append((u, w)) dist = [[inf] * (k + 1) for _ in range(n)] dist[s][0] = 0 pq = [(0, s, 0)] while pq: dis, u, t = heappop(pq) for v, w in g[u]: if t + 1 <= k and dist[v][t + 1] > dis: dist[v][t + 1] = dis heappush(pq, (dis, v, t + 1)) if dist[v][t] > dis + w: dist[v][t] = dis + w heappush(pq, (dis + w, v, t)) return int(min(dist[d]))
2,715
Timeout Cancellation
Easy
<p>Given a function <code>fn</code>, an array of&nbsp;arguments&nbsp;<code>args</code>, and a timeout&nbsp;<code>t</code>&nbsp;in milliseconds, return a cancel function <code>cancelFn</code>.</p> <p>After a delay of <code>cancelTimeMs</code>, the returned cancel function <code>cancelFn</code> will be invoked.</p> <pre> setTimeout(cancelFn, cancelTimeMs) </pre> <p>Initially, the execution of the function <code>fn</code> should be delayed by <code>t</code> milliseconds.</p> <p>If, before the delay of <code>t</code> milliseconds, the function <code>cancelFn</code> is invoked, it should cancel the delayed execution of <code>fn</code>. Otherwise, if <code>cancelFn</code> is not invoked within the specified delay <code>t</code>, <code>fn</code> should be executed with the provided <code>args</code> as arguments.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (x) =&gt; x * 5, args = [2], t = 20 <strong>Output:</strong> [{&quot;time&quot;: 20, &quot;returned&quot;: 10}] <strong>Explanation:</strong> const cancelTimeMs = 50; const cancelFn = cancellable((x) =&gt; x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (x) =&gt; x**2, args = [2], t = 100 <strong>Output:</strong> [] <strong>Explanation:</strong> const cancelTimeMs = 50; const cancelFn = cancellable((x) =&gt; x**2, [2], 100); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> fn = (x1, x2) =&gt; x1 * x2, args = [2,4], t = 30 <strong>Output:</strong> [{&quot;time&quot;: 30, &quot;returned&quot;: 8}] <strong>Explanation: </strong>const cancelTimeMs = 100; const cancelFn = cancellable((x1, x2) =&gt; x1 * x2, [2,4], 30); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), which happened after the execution of fn(2,4) at 30ms. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>fn</code> is a function</li> <li><code>args</code> is a valid JSON array</li> <li><code>1 &lt;= args.length &lt;= 10</code></li> <li><code><font face="monospace">20 &lt;= t &lt;= 1000</font></code></li> <li><code><font face="monospace">10 &lt;= cancelTimeMs &lt;= 1000</font></code></li> </ul>
JavaScript
JavaScript
/** * @param {Function} fn * @param {Array} args * @param {number} t * @return {Function} */ var cancellable = function (fn, args, t) { const timer = setTimeout(() => fn(...args), t); return () => { clearTimeout(timer); }; }; /** * const result = [] * * const fn = (x) => x * 5 * const args = [2], t = 20, cancelT = 50 * * const start = performance.now() * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)) * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelT) * * setTimeout(() => { * cancel() * }, cancelT) * * setTimeout(() => { * console.log(result) // [{"time":20,"returned":10}] * }, maxT + 15) */
2,715
Timeout Cancellation
Easy
<p>Given a function <code>fn</code>, an array of&nbsp;arguments&nbsp;<code>args</code>, and a timeout&nbsp;<code>t</code>&nbsp;in milliseconds, return a cancel function <code>cancelFn</code>.</p> <p>After a delay of <code>cancelTimeMs</code>, the returned cancel function <code>cancelFn</code> will be invoked.</p> <pre> setTimeout(cancelFn, cancelTimeMs) </pre> <p>Initially, the execution of the function <code>fn</code> should be delayed by <code>t</code> milliseconds.</p> <p>If, before the delay of <code>t</code> milliseconds, the function <code>cancelFn</code> is invoked, it should cancel the delayed execution of <code>fn</code>. Otherwise, if <code>cancelFn</code> is not invoked within the specified delay <code>t</code>, <code>fn</code> should be executed with the provided <code>args</code> as arguments.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (x) =&gt; x * 5, args = [2], t = 20 <strong>Output:</strong> [{&quot;time&quot;: 20, &quot;returned&quot;: 10}] <strong>Explanation:</strong> const cancelTimeMs = 50; const cancelFn = cancellable((x) =&gt; x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (x) =&gt; x**2, args = [2], t = 100 <strong>Output:</strong> [] <strong>Explanation:</strong> const cancelTimeMs = 50; const cancelFn = cancellable((x) =&gt; x**2, [2], 100); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> fn = (x1, x2) =&gt; x1 * x2, args = [2,4], t = 30 <strong>Output:</strong> [{&quot;time&quot;: 30, &quot;returned&quot;: 8}] <strong>Explanation: </strong>const cancelTimeMs = 100; const cancelFn = cancellable((x1, x2) =&gt; x1 * x2, [2,4], 30); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), which happened after the execution of fn(2,4) at 30ms. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>fn</code> is a function</li> <li><code>args</code> is a valid JSON array</li> <li><code>1 &lt;= args.length &lt;= 10</code></li> <li><code><font face="monospace">20 &lt;= t &lt;= 1000</font></code></li> <li><code><font face="monospace">10 &lt;= cancelTimeMs &lt;= 1000</font></code></li> </ul>
JavaScript
TypeScript
function cancellable(fn: Function, args: any[], t: number): Function { const timer = setTimeout(() => fn(...args), t); return () => { clearTimeout(timer); }; } /** * const result = [] * * const fn = (x) => x * 5 * const args = [2], t = 20, cancelT = 50 * * const start = performance.now() * * const log = (...argsArr) => { * const diff = Math.floor(performance.now() - start); * result.push({"time": diff, "returned": fn(...argsArr)) * } * * const cancel = cancellable(log, args, t); * * const maxT = Math.max(t, cancelT) * * setTimeout(() => { * cancel() * }, cancelT) * * setTimeout(() => { * console.log(result) // [{"time":20,"returned":10}] * }, maxT + 15) */
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
C++
class Solution { public: int minimizedStringLength(string s) { return unordered_set<char>(s.begin(), s.end()).size(); } };
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
C#
public class Solution { public int MinimizedStringLength(string s) { return new HashSet<char>(s).Count; } }
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
Go
func minimizedStringLength(s string) int { ss := map[rune]struct{}{} for _, c := range s { ss[c] = struct{}{} } return len(ss) }
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
Java
class Solution { public int minimizedStringLength(String s) { Set<Character> ss = new HashSet<>(); for (int i = 0; i < s.length(); ++i) { ss.add(s.charAt(i)); } return ss.size(); } }
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
Python
class Solution: def minimizedStringLength(self, s: str) -> int: return len(set(s))
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
Rust
use std::collections::HashSet; impl Solution { pub fn minimized_string_length(s: String) -> i32 { let ss: HashSet<char> = s.chars().collect(); ss.len() as i32 } }
2,716
Minimize String Length
Easy
<p>Given a string <code>s</code>, you have two types of operation:</p> <ol> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>left</strong> of <code>i</code> (if exists).</li> <li>Choose an index <code>i</code> in the string, and let <code>c</code> be the character in position <code>i</code>. <strong>Delete</strong> the <strong>closest occurrence</strong> of <code>c</code> to the <strong>right</strong> of <code>i</code> (if exists).</li> </ol> <p>Your task is to <strong>minimize</strong> the length of <code>s</code> by performing the above operations zero or more times.</p> <p>Return an integer denoting the length of the <strong>minimized</strong> string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 2: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the right of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;aabc&quot; after this.</li> <li>Operation 1: we choose <code>i = 1</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[0]</code> as it is closest &#39;a&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;abc&quot; after this.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbbd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 2</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[1]</code> as it is closest &#39;b&#39; character to the left of <code>s[1]</code>.<br /> <code>s</code> becomes &quot;cbd&quot; after this.</li> </ol> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;baadccab&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <ol> <li>Operation 1: we choose <code>i = 6</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[2]</code> as it is closest &#39;a&#39; character to the left of <code>s[6]</code>.<br /> <code>s</code> becomes &quot;badccab&quot; after this.</li> <li>Operation 2: we choose <code>i = 0</code> so <code>c</code> is &#39;b&#39;, then we remove <code>s[6]</code> as it is closest &#39;b&#39; character to the right of <code>s[0]</code>.<br /> <code>s</code> becomes &quot;badcca&quot; fter this.</li> <li>Operation 2: we choose <code>i = 3</code> so <code>c</code> is &#39;c&#39;, then we remove <code>s[4]</code> as it is closest &#39;c&#39; character to the right of <code>s[3]</code>.<br /> <code>s</code> becomes &quot;badca&quot; after this.</li> <li>Operation 1: we choose <code>i = 4</code> so <code>c</code> is &#39;a&#39;, then we remove <code>s[1]</code> as it is closest &#39;a&#39; character to the left of <code>s[4]</code>.<br /> <code>s</code> becomes &quot;bdca&quot; after this.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> contains only lowercase English letters</li> </ul>
Hash Table; String
TypeScript
function minimizedStringLength(s: string): number { return new Set(s.split('')).size; }
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
C++
class Solution { public: int semiOrderedPermutation(vector<int>& nums) { int n = nums.size(); int i = find(nums.begin(), nums.end(), 1) - nums.begin(); int j = find(nums.begin(), nums.end(), n) - nums.begin(); int k = i < j ? 1 : 2; return i + n - j - k; } };
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
Go
func semiOrderedPermutation(nums []int) int { n := len(nums) var i, j int for k, x := range nums { if x == 1 { i = k } if x == n { j = k } } k := 1 if i > j { k = 2 } return i + n - j - k }
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
Java
class Solution { public int semiOrderedPermutation(int[] nums) { int n = nums.length; int i = 0, j = 0; for (int k = 0; k < n; ++k) { if (nums[k] == 1) { i = k; } if (nums[k] == n) { j = k; } } int k = i < j ? 1 : 2; return i + n - j - k; } }
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
Python
class Solution: def semiOrderedPermutation(self, nums: List[int]) -> int: n = len(nums) i = nums.index(1) j = nums.index(n) k = 1 if i < j else 2 return i + n - j - k
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
Rust
impl Solution { pub fn semi_ordered_permutation(nums: Vec<i32>) -> i32 { let n = nums.len(); let (mut i, mut j) = (0, 0); for k in 0..n { if nums[k] == 1 { i = k; } if nums[k] == (n as i32) { j = k; } } let k = if i < j { 1 } else { 2 }; (i + n - j - k) as i32 } }
2,717
Semi-Ordered Permutation
Easy
<p>You are given a <strong>0-indexed</strong> permutation of <code>n</code> integers <code>nums</code>.</p> <p>A permutation is called <strong>semi-ordered</strong> if the first number equals <code>1</code> and the last number equals <code>n</code>. You can perform the below operation as many times as you want until you make <code>nums</code> a <strong>semi-ordered</strong> permutation:</p> <ul> <li>Pick two adjacent elements in <code>nums</code>, then swap them.</li> </ul> <p>Return <em>the minimum number of operations to make </em><code>nums</code><em> a <strong>semi-ordered permutation</strong></em>.</p> <p>A <strong>permutation</strong> is a sequence of integers from <code>1</code> to <code>n</code> of length <code>n</code> containing each number exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,1,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can make the permutation semi-ordered using these sequence of operations: 1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. 2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. 3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> The permutation is already a semi-ordered permutation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length == n &lt;= 50</code></li> <li><code>1 &lt;= nums[i]&nbsp;&lt;= 50</code></li> <li><code>nums is a permutation.</code></li> </ul>
Array; Simulation
TypeScript
function semiOrderedPermutation(nums: number[]): number { const n = nums.length; const i = nums.indexOf(1); const j = nums.indexOf(n); const k = i < j ? 1 : 2; return i + n - j - k; }
2,718
Sum of Matrix After Queries
Medium
<p>You are given an integer <code>n</code> and a <strong>0-indexed</strong>&nbsp;<strong>2D array</strong> <code>queries</code> where <code>queries[i] = [type<sub>i</sub>, index<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Initially, there is a <strong>0-indexed</strong> <code>n x n</code> matrix filled with <code>0</code>&#39;s. For each query, you must apply one of the following changes:</p> <ul> <li>if <code>type<sub>i</sub> == 0</code>, set the values in the row with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> <li>if <code>type<sub>i</sub> == 1</code>, set the values in the column with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> </ul> <p>Return <em>the sum of integers in the matrix after all queries are applied</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm1.png" style="width: 681px; height: 161px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm2.png" style="width: 681px; height: 331px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= type<sub>i</sub> &lt;= 1</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt; n</code></li> <li><code>0 &lt;= val<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
C++
class Solution { public: long long matrixSumQueries(int n, vector<vector<int>>& queries) { unordered_set<int> row, col; reverse(queries.begin(), queries.end()); long long ans = 0; for (auto& q : queries) { int t = q[0], i = q[1], v = q[2]; if (t == 0) { if (!row.count(i)) { ans += 1LL * (n - col.size()) * v; row.insert(i); } } else { if (!col.count(i)) { ans += 1LL * (n - row.size()) * v; col.insert(i); } } } return ans; } };
2,718
Sum of Matrix After Queries
Medium
<p>You are given an integer <code>n</code> and a <strong>0-indexed</strong>&nbsp;<strong>2D array</strong> <code>queries</code> where <code>queries[i] = [type<sub>i</sub>, index<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Initially, there is a <strong>0-indexed</strong> <code>n x n</code> matrix filled with <code>0</code>&#39;s. For each query, you must apply one of the following changes:</p> <ul> <li>if <code>type<sub>i</sub> == 0</code>, set the values in the row with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> <li>if <code>type<sub>i</sub> == 1</code>, set the values in the column with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> </ul> <p>Return <em>the sum of integers in the matrix after all queries are applied</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm1.png" style="width: 681px; height: 161px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm2.png" style="width: 681px; height: 331px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= type<sub>i</sub> &lt;= 1</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt; n</code></li> <li><code>0 &lt;= val<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Go
func matrixSumQueries(n int, queries [][]int) (ans int64) { row, col := map[int]bool{}, map[int]bool{} m := len(queries) for k := m - 1; k >= 0; k-- { t, i, v := queries[k][0], queries[k][1], queries[k][2] if t == 0 { if !row[i] { ans += int64(v * (n - len(col))) row[i] = true } } else { if !col[i] { ans += int64(v * (n - len(row))) col[i] = true } } } return }
2,718
Sum of Matrix After Queries
Medium
<p>You are given an integer <code>n</code> and a <strong>0-indexed</strong>&nbsp;<strong>2D array</strong> <code>queries</code> where <code>queries[i] = [type<sub>i</sub>, index<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Initially, there is a <strong>0-indexed</strong> <code>n x n</code> matrix filled with <code>0</code>&#39;s. For each query, you must apply one of the following changes:</p> <ul> <li>if <code>type<sub>i</sub> == 0</code>, set the values in the row with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> <li>if <code>type<sub>i</sub> == 1</code>, set the values in the column with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> </ul> <p>Return <em>the sum of integers in the matrix after all queries are applied</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm1.png" style="width: 681px; height: 161px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm2.png" style="width: 681px; height: 331px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= type<sub>i</sub> &lt;= 1</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt; n</code></li> <li><code>0 &lt;= val<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Java
class Solution { public long matrixSumQueries(int n, int[][] queries) { Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int m = queries.length; long ans = 0; for (int k = m - 1; k >= 0; --k) { var q = queries[k]; int t = q[0], i = q[1], v = q[2]; if (t == 0) { if (row.add(i)) { ans += 1L * (n - col.size()) * v; } } else { if (col.add(i)) { ans += 1L * (n - row.size()) * v; } } } return ans; } }
2,718
Sum of Matrix After Queries
Medium
<p>You are given an integer <code>n</code> and a <strong>0-indexed</strong>&nbsp;<strong>2D array</strong> <code>queries</code> where <code>queries[i] = [type<sub>i</sub>, index<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Initially, there is a <strong>0-indexed</strong> <code>n x n</code> matrix filled with <code>0</code>&#39;s. For each query, you must apply one of the following changes:</p> <ul> <li>if <code>type<sub>i</sub> == 0</code>, set the values in the row with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> <li>if <code>type<sub>i</sub> == 1</code>, set the values in the column with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> </ul> <p>Return <em>the sum of integers in the matrix after all queries are applied</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm1.png" style="width: 681px; height: 161px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm2.png" style="width: 681px; height: 331px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= type<sub>i</sub> &lt;= 1</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt; n</code></li> <li><code>0 &lt;= val<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Python
class Solution: def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int: row = set() col = set() ans = 0 for t, i, v in queries[::-1]: if t == 0: if i not in row: ans += v * (n - len(col)) row.add(i) else: if i not in col: ans += v * (n - len(row)) col.add(i) return ans
2,718
Sum of Matrix After Queries
Medium
<p>You are given an integer <code>n</code> and a <strong>0-indexed</strong>&nbsp;<strong>2D array</strong> <code>queries</code> where <code>queries[i] = [type<sub>i</sub>, index<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Initially, there is a <strong>0-indexed</strong> <code>n x n</code> matrix filled with <code>0</code>&#39;s. For each query, you must apply one of the following changes:</p> <ul> <li>if <code>type<sub>i</sub> == 0</code>, set the values in the row with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> <li>if <code>type<sub>i</sub> == 1</code>, set the values in the column with <code>index<sub>i</sub></code> to <code>val<sub>i</sub></code>, overwriting any previous values.</li> </ul> <p>Return <em>the sum of integers in the matrix after all queries are applied</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm1.png" style="width: 681px; height: 161px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] <strong>Output:</strong> 23 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2700-2799/2718.Sum%20of%20Matrix%20After%20Queries/images/exm2.png" style="width: 681px; height: 331px;" /> <pre> <strong>Input:</strong> n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= type<sub>i</sub> &lt;= 1</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt; n</code></li> <li><code>0 &lt;= val<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
TypeScript
function matrixSumQueries(n: number, queries: number[][]): number { const row: Set<number> = new Set(); const col: Set<number> = new Set(); let ans = 0; queries.reverse(); for (const [t, i, v] of queries) { if (t === 0) { if (!row.has(i)) { ans += v * (n - col.size); row.add(i); } } else { if (!col.has(i)) { ans += v * (n - row.size); col.add(i); } } } return ans; }
2,719
Count of Integers
Hard
<p>You are given two numeric strings <code>num1</code> and <code>num2</code> and two integers <code>max_sum</code> and <code>min_sum</code>. We denote an integer <code>x</code> to be <em>good</em> if:</p> <ul> <li><code>num1 &lt;= x &lt;= num2</code></li> <li><code>min_sum &lt;= digit_sum(x) &lt;= max_sum</code>.</li> </ul> <p>Return <em>the number of good integers</em>. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>Note that <code>digit_sum(x)</code> denotes the sum of the digits of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;12&quot;, <code>min_sum</code> = 1, max_sum = 8 <strong>Output:</strong> 11 <strong>Explanation:</strong> There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;5&quot;, <code>min_sum</code> = 1, max_sum = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1 &lt;= num2 &lt;= 10<sup>22</sup></code></li> <li><code>1 &lt;= min_sum &lt;= max_sum &lt;= 400</code></li> </ul>
Math; String; Dynamic Programming
C++
class Solution { public: int count(string num1, string num2, int min_sum, int max_sum) { const int mod = 1e9 + 7; int f[23][220]; memset(f, -1, sizeof(f)); string num = num2; function<int(int, int, bool)> dfs = [&](int pos, int s, bool limit) -> int { if (pos >= num.size()) { return s >= min_sum && s <= max_sum ? 1 : 0; } if (!limit && f[pos][s] != -1) { return f[pos][s]; } int up = limit ? num[pos] - '0' : 9; int ans = 0; for (int i = 0; i <= up; ++i) { ans += dfs(pos + 1, s + i, limit && i == up); ans %= mod; } if (!limit) { f[pos][s] = ans; } return ans; }; int a = dfs(0, 0, true); for (int i = num1.size() - 1; ~i; --i) { if (num1[i] == '0') { num1[i] = '9'; } else { num1[i] -= 1; break; } } num = num1; memset(f, -1, sizeof(f)); int b = dfs(0, 0, true); return (a - b + mod) % mod; } };
2,719
Count of Integers
Hard
<p>You are given two numeric strings <code>num1</code> and <code>num2</code> and two integers <code>max_sum</code> and <code>min_sum</code>. We denote an integer <code>x</code> to be <em>good</em> if:</p> <ul> <li><code>num1 &lt;= x &lt;= num2</code></li> <li><code>min_sum &lt;= digit_sum(x) &lt;= max_sum</code>.</li> </ul> <p>Return <em>the number of good integers</em>. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>Note that <code>digit_sum(x)</code> denotes the sum of the digits of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;12&quot;, <code>min_sum</code> = 1, max_sum = 8 <strong>Output:</strong> 11 <strong>Explanation:</strong> There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;5&quot;, <code>min_sum</code> = 1, max_sum = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1 &lt;= num2 &lt;= 10<sup>22</sup></code></li> <li><code>1 &lt;= min_sum &lt;= max_sum &lt;= 400</code></li> </ul>
Math; String; Dynamic Programming
Go
func count(num1 string, num2 string, min_sum int, max_sum int) int { const mod = 1e9 + 7 f := [23][220]int{} for i := range f { for j := range f[i] { f[i][j] = -1 } } num := num2 var dfs func(int, int, bool) int dfs = func(pos, s int, limit bool) int { if pos >= len(num) { if s >= min_sum && s <= max_sum { return 1 } return 0 } if !limit && f[pos][s] != -1 { return f[pos][s] } var ans int up := 9 if limit { up = int(num[pos] - '0') } for i := 0; i <= up; i++ { ans = (ans + dfs(pos+1, s+i, limit && i == up)) % mod } if !limit { f[pos][s] = ans } return ans } a := dfs(0, 0, true) t := []byte(num1) for i := len(t) - 1; i >= 0; i-- { if t[i] != '0' { t[i]-- break } t[i] = '9' } num = string(t) f = [23][220]int{} for i := range f { for j := range f[i] { f[i][j] = -1 } } b := dfs(0, 0, true) return (a - b + mod) % mod }
2,719
Count of Integers
Hard
<p>You are given two numeric strings <code>num1</code> and <code>num2</code> and two integers <code>max_sum</code> and <code>min_sum</code>. We denote an integer <code>x</code> to be <em>good</em> if:</p> <ul> <li><code>num1 &lt;= x &lt;= num2</code></li> <li><code>min_sum &lt;= digit_sum(x) &lt;= max_sum</code>.</li> </ul> <p>Return <em>the number of good integers</em>. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>Note that <code>digit_sum(x)</code> denotes the sum of the digits of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;12&quot;, <code>min_sum</code> = 1, max_sum = 8 <strong>Output:</strong> 11 <strong>Explanation:</strong> There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;5&quot;, <code>min_sum</code> = 1, max_sum = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1 &lt;= num2 &lt;= 10<sup>22</sup></code></li> <li><code>1 &lt;= min_sum &lt;= max_sum &lt;= 400</code></li> </ul>
Math; String; Dynamic Programming
Java
import java.math.BigInteger; class Solution { private final int mod = (int) 1e9 + 7; private Integer[][] f; private String num; private int min; private int max; public int count(String num1, String num2, int min_sum, int max_sum) { min = min_sum; max = max_sum; num = num2; f = new Integer[23][220]; int a = dfs(0, 0, true); num = new BigInteger(num1).subtract(BigInteger.ONE).toString(); f = new Integer[23][220]; int b = dfs(0, 0, true); return (a - b + mod) % mod; } private int dfs(int pos, int s, boolean limit) { if (pos >= num.length()) { return s >= min && s <= max ? 1 : 0; } if (!limit && f[pos][s] != null) { return f[pos][s]; } int ans = 0; int up = limit ? num.charAt(pos) - '0' : 9; for (int i = 0; i <= up; ++i) { ans = (ans + dfs(pos + 1, s + i, limit && i == up)) % mod; } if (!limit) { f[pos][s] = ans; } return ans; } }
2,719
Count of Integers
Hard
<p>You are given two numeric strings <code>num1</code> and <code>num2</code> and two integers <code>max_sum</code> and <code>min_sum</code>. We denote an integer <code>x</code> to be <em>good</em> if:</p> <ul> <li><code>num1 &lt;= x &lt;= num2</code></li> <li><code>min_sum &lt;= digit_sum(x) &lt;= max_sum</code>.</li> </ul> <p>Return <em>the number of good integers</em>. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>Note that <code>digit_sum(x)</code> denotes the sum of the digits of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;12&quot;, <code>min_sum</code> = 1, max_sum = 8 <strong>Output:</strong> 11 <strong>Explanation:</strong> There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;5&quot;, <code>min_sum</code> = 1, max_sum = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1 &lt;= num2 &lt;= 10<sup>22</sup></code></li> <li><code>1 &lt;= min_sum &lt;= max_sum &lt;= 400</code></li> </ul>
Math; String; Dynamic Programming
Python
class Solution: def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int: @cache def dfs(pos: int, s: int, limit: bool) -> int: if pos >= len(num): return int(min_sum <= s <= max_sum) up = int(num[pos]) if limit else 9 return ( sum(dfs(pos + 1, s + i, limit and i == up) for i in range(up + 1)) % mod ) mod = 10**9 + 7 num = num2 a = dfs(0, 0, True) dfs.cache_clear() num = str(int(num1) - 1) b = dfs(0, 0, True) return (a - b) % mod
2,719
Count of Integers
Hard
<p>You are given two numeric strings <code>num1</code> and <code>num2</code> and two integers <code>max_sum</code> and <code>min_sum</code>. We denote an integer <code>x</code> to be <em>good</em> if:</p> <ul> <li><code>num1 &lt;= x &lt;= num2</code></li> <li><code>min_sum &lt;= digit_sum(x) &lt;= max_sum</code>.</li> </ul> <p>Return <em>the number of good integers</em>. Since the answer may be large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>Note that <code>digit_sum(x)</code> denotes the sum of the digits of <code>x</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;12&quot;, <code>min_sum</code> = 1, max_sum = 8 <strong>Output:</strong> 11 <strong>Explanation:</strong> There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1&quot;, num2 = &quot;5&quot;, <code>min_sum</code> = 1, max_sum = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1 &lt;= num2 &lt;= 10<sup>22</sup></code></li> <li><code>1 &lt;= min_sum &lt;= max_sum &lt;= 400</code></li> </ul>
Math; String; Dynamic Programming
TypeScript
function count(num1: string, num2: string, min_sum: number, max_sum: number): number { const mod = 1e9 + 7; const f: number[][] = Array.from({ length: 23 }, () => Array(220).fill(-1)); let num = num2; const dfs = (pos: number, s: number, limit: boolean): number => { if (pos >= num.length) { return s >= min_sum && s <= max_sum ? 1 : 0; } if (!limit && f[pos][s] !== -1) { return f[pos][s]; } let ans = 0; const up = limit ? +num[pos] : 9; for (let i = 0; i <= up; i++) { ans = (ans + dfs(pos + 1, s + i, limit && i === up)) % mod; } if (!limit) { f[pos][s] = ans; } return ans; }; const a = dfs(0, 0, true); num = (BigInt(num1) - 1n).toString(); f.forEach(v => v.fill(-1)); const b = dfs(0, 0, true); return (a - b + mod) % mod; }
2,720
Popularity Percentage
Hard
<p>Table: <code>Friends</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | user1 | int | | user2 | int | +-------------+------+ (user1, user2) is the primary key (combination of unique values) of this table. Each row contains information about friendship where user1 and user2 are friends. </pre> <p>Write a solution to find the popularity percentage for each user on Meta/Facebook. The popularity percentage is defined as the total number of friends the user has divided by the total number of users on the platform, then converted into a percentage by multiplying by 100, <strong>rounded to 2 decimal places</strong>.</p> <p>Return <em>the result table ordered by</em> <code>user1</code> <em>in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong>&nbsp; Friends table: +-------+-------+ | user1 | user2 | +-------+-------+ | 2 &nbsp; &nbsp; | 1 &nbsp; &nbsp; | | 1 &nbsp; &nbsp; | 3 &nbsp; &nbsp; | | 4 &nbsp; &nbsp; | 1 &nbsp; &nbsp; | | 1 &nbsp; &nbsp; | 5 &nbsp; &nbsp; | | 1 &nbsp; &nbsp; | 6 &nbsp; &nbsp; | | 2 &nbsp; &nbsp; | 6 &nbsp; &nbsp; | | 7 &nbsp; &nbsp; | 2 &nbsp; &nbsp; | | 8 &nbsp; &nbsp; | 3&nbsp; &nbsp; &nbsp;| | 3 &nbsp; &nbsp; | 9 &nbsp; &nbsp; | +-------+-------+ <strong>Output:</strong>&nbsp; +-------+-----------------------+ | user1 | percentage_popularity | +-------+-----------------------+ | 1 | 55.56 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| | 2 | 33.33 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| | 3 | 33.33 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 4 | 11.11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 5 | 11.11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 6 | 22.22 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 7 | 11.11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 8 | 11.11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 9 | 11.11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | +-------+-----------------------+ <strong>Explanation:</strong>&nbsp; There are total 9 users on the platform. - User &quot;1&quot; has friendships with 2, 3, 4, 5 and 6. Therefore, the percentage popularity for user 1 would be calculated as (5/9) * 100 = 55.56. - User &quot;2&quot; has friendships with 1, 6 and 7. Therefore, the percentage popularity for user 2 would be calculated as (3/9) * 100 = 33.33. - User &quot;3&quot; has friendships with 1, 8 and 9. Therefore, the percentage popularity for user 3 would be calculated as (3/9) * 100 = 33.33. - User &quot;4&quot; has friendships with 1. Therefore, the percentage popularity for user 4 would be calculated as (1/9) * 100 = 11.11. - User &quot;5&quot; has friendships with 1. Therefore, the percentage popularity for user 5 would be calculated as (1/9) * 100 = 11.11. - User &quot;6&quot; has friendships with 1 and 2. Therefore, the percentage popularity for user 6 would be calculated as (2/9) * 100 = 22.22. - User &quot;7&quot; has friendships with 2. Therefore, the percentage popularity for user 7 would be calculated as (1/9) * 100 = 11.11. - User &quot;8&quot; has friendships with 3. Therefore, the percentage popularity for user 8 would be calculated as (1/9) * 100 = 11.11. - User &quot;9&quot; has friendships with 3. Therefore, the percentage popularity for user 9 would be calculated as (1/9) * 100 = 11.11. user1 is sorted in ascending order. </pre>
Database
SQL
# Write your MySQL query statement below WITH F AS ( SELECT * FROM Friends UNION SELECT user2, user1 FROM Friends ), T AS (SELECT COUNT(DISTINCT user1) AS cnt FROM F) SELECT DISTINCT user1, ROUND( (COUNT(1) OVER (PARTITION BY user1)) * 100 / (SELECT cnt FROM T), 2 ) AS percentage_popularity FROM F ORDER BY 1;
2,721
Execute Asynchronous Functions in Parallel
Medium
<p>Given an array of&nbsp;asynchronous functions&nbsp;<code>functions</code>, return a new promise <code>promise</code>. Each function in the array accepts no arguments&nbsp;and returns a promise. All the promises should be executed in parallel.</p> <p><code>promise</code> resolves:</p> <ul> <li>When all the promises returned from&nbsp;<code>functions</code>&nbsp;were resolved successfully in parallel.&nbsp;The resolved&nbsp;value of&nbsp;<code>promise</code> should be an array of all the resolved values of promises in the same order as they were in the&nbsp;<code>functions</code>. The <code>promise</code> should resolve when all the asynchronous functions in the array have completed execution in parallel.</li> </ul> <p><code>promise</code> rejects:</p> <ul> <li>When any&nbsp;of the promises&nbsp;returned from&nbsp;<code>functions</code>&nbsp;were rejected.&nbsp;<code>promise</code> should also&nbsp;reject&nbsp;with the reason of the first rejection.</li> </ul> <p>Please solve it without using the built-in&nbsp;<code>Promise.all</code>&nbsp;function.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> functions = [ &nbsp; () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(5), 200)) ] <strong>Output:</strong> {&quot;t&quot;: 200, &quot;resolved&quot;: [5]} <strong>Explanation:</strong> promiseAll(functions).then(console.log); // [5] The single function was resolved at 200ms with a value of 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> functions = [ () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(1), 200)), () =&gt; new Promise((resolve, reject) =&gt; setTimeout(() =&gt; reject(&quot;Error&quot;), 100)) ] <strong>Output:</strong> {&quot;t&quot;: 100, &quot;rejected&quot;: &quot;Error&quot;} <strong>Explanation:</strong> Since one of the promises rejected, the returned promise also rejected with the same error at the same time. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> functions = [ () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(4), 50)), () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(10), 150)), () =&gt; new Promise(resolve =&gt; setTimeout(() =&gt; resolve(16), 100)) ] <strong>Output:</strong> {&quot;t&quot;: 150, &quot;resolved&quot;: [4, 10, 16]} <strong>Explanation:</strong> All the promises resolved with a value. The returned promise resolved when the last promise resolved. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>functions</code>&nbsp;is an array of functions that returns promises</li> <li><code>1 &lt;= functions.length &lt;= 10</code></li> </ul>
JavaScript
TypeScript
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> { return new Promise<T[]>((resolve, reject) => { let cnt = 0; const ans = new Array(functions.length); for (let i = 0; i < functions.length; ++i) { const f = functions[i]; f() .then(res => { ans[i] = res; cnt++; if (cnt === functions.length) { resolve(ans); } }) .catch(err => { reject(err); }); } }); } /** * const promise = promiseAll([() => new Promise(res => res(42))]) * promise.then(console.log); // [42] */
2,722
Join Two Arrays by ID
Medium
<p>Given two arrays <code>arr1</code> and <code>arr2</code>, return a new&nbsp;array <code>joinedArray</code>. All the objects in each&nbsp;of the two inputs arrays will contain an&nbsp;<code>id</code>&nbsp;field that has an integer value.&nbsp;</p> <p><code>joinedArray</code>&nbsp;is an array formed by merging&nbsp;<code>arr1</code> and <code>arr2</code> based on&nbsp;their <code>id</code>&nbsp;key. The length of&nbsp;<code>joinedArray</code> should be the length of unique values of <code>id</code>. The returned array should be sorted in&nbsp;<strong>ascending</strong>&nbsp;order based on the <code>id</code>&nbsp;key.</p> <p>If a given&nbsp;<code>id</code>&nbsp;exists in one array but not the other, the single object with that&nbsp;<code>id</code> should be included in the result array without modification.</p> <p>If two objects share an <code>id</code>, their properties should be merged into a single&nbsp;object:</p> <ul> <li>If a key only exists in one object, that single key-value pair should be included in the object.</li> <li>If a key is included in both objects, the value in the object from <code>arr2</code>&nbsp;should override the value from <code>arr1</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [ &nbsp; {&quot;id&quot;: 1, &quot;x&quot;: 1}, &nbsp; {&quot;id&quot;: 2, &quot;x&quot;: 9} ], arr2 = [ {&quot;id&quot;: 3, &quot;x&quot;: 5} ] <strong>Output:</strong> [ &nbsp; {&quot;id&quot;: 1, &quot;x&quot;: 1}, &nbsp; {&quot;id&quot;: 2, &quot;x&quot;: 9}, {&quot;id&quot;: 3, &quot;x&quot;: 5} ] <strong>Explanation:</strong> There are no duplicate ids so arr1 is simply concatenated with arr2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [ {&quot;id&quot;: 1, &quot;x&quot;: 2, &quot;y&quot;: 3}, {&quot;id&quot;: 2, &quot;x&quot;: 3, &quot;y&quot;: 6} ], arr2 = [ {&quot;id&quot;: 2, &quot;x&quot;: 10, &quot;y&quot;: 20}, {&quot;id&quot;: 3, &quot;x&quot;: 0, &quot;y&quot;: 0} ] <strong>Output:</strong> [ {&quot;id&quot;: 1, &quot;x&quot;: 2, &quot;y&quot;: 3}, {&quot;id&quot;: 2, &quot;x&quot;: 10, &quot;y&quot;: 20}, &nbsp; {&quot;id&quot;: 3, &quot;x&quot;: 0, &quot;y&quot;: 0} ] <strong>Explanation:</strong> The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr1 = [ {&quot;id&quot;: 1, &quot;b&quot;: {&quot;b&quot;: 94},&quot;v&quot;: [4, 3], &quot;y&quot;: 48} ] arr2 = [ {&quot;id&quot;: 1, &quot;b&quot;: {&quot;c&quot;: 84}, &quot;v&quot;: [1, 3]} ] <strong>Output:</strong> [ {&quot;id&quot;: 1, &quot;b&quot;: {&quot;c&quot;: 84}, &quot;v&quot;: [1, 3], &quot;y&quot;: 48} ] <strong>Explanation:</strong> The two objects with id=1 are merged together. For the keys &quot;b&quot; and &quot;v&quot; the values from arr2 are used. Since the key &quot;y&quot; only exists in arr1, that value is taken form arr1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr1</code> and <code>arr2</code> are valid JSON arrays</li> <li>Each object in <code>arr1</code> and <code>arr2</code> has a unique&nbsp;integer <code>id</code> key</li> <li><code>2 &lt;= JSON.stringify(arr1).length &lt;= 10<sup>6</sup></code></li> <li><code>2 &lt;= JSON.stringify(arr2).length &lt;= 10<sup>6</sup></code></li> </ul>
JavaScript
TypeScript
function join(arr1: ArrayType[], arr2: ArrayType[]): ArrayType[] { const r = (acc: Obj, x: ArrayType): Obj => ((acc[x.id] = x), acc); const d = arr1.reduce(r, {}); arr2.forEach(x => { if (d[x.id]) { Object.assign(d[x.id], x); } else { d[x.id] = x; } }); return Object.values(d); } type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type ArrayType = { id: number } & Record<string, JSONValue>; type Obj = Record<number, ArrayType>;
2,723
Add Two Promises
Easy
Given two promises <code>promise1</code> and <code>promise2</code>, return a new promise. <code>promise1</code> and <code>promise2</code>&nbsp;will both resolve with a number. The returned promise should resolve with the sum of the two numbers. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> promise1 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(2), 20)), promise2 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(5), 60)) <strong>Output:</strong> 7 <strong>Explanation:</strong> The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> promise1 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(10), 50)), promise2 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(-12), 30)) <strong>Output:</strong> -2 <strong>Explanation:</strong> The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>promise1</code> and <code>promise2</code> are&nbsp;promises that resolve&nbsp;with a number</li> </ul>
JavaScript
JavaScript
var addTwoPromises = async function (promise1, promise2) { return (await promise1) + (await promise2); };
2,723
Add Two Promises
Easy
Given two promises <code>promise1</code> and <code>promise2</code>, return a new promise. <code>promise1</code> and <code>promise2</code>&nbsp;will both resolve with a number. The returned promise should resolve with the sum of the two numbers. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> promise1 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(2), 20)), promise2 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(5), 60)) <strong>Output:</strong> 7 <strong>Explanation:</strong> The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> promise1 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(10), 50)), promise2 = new Promise(resolve =&gt; setTimeout(() =&gt; resolve(-12), 30)) <strong>Output:</strong> -2 <strong>Explanation:</strong> The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>promise1</code> and <code>promise2</code> are&nbsp;promises that resolve&nbsp;with a number</li> </ul>
JavaScript
TypeScript
async function addTwoPromises( promise1: Promise<number>, promise2: Promise<number>, ): Promise<number> { return (await promise1) + (await promise2); } /** * addTwoPromises(Promise.resolve(2), Promise.resolve(2)) * .then(console.log); // 4 */
2,724
Sort By
Easy
<p>Given an array <code>arr</code> and a function <code>fn</code>, return a sorted array <code>sortedArr</code>. You can assume&nbsp;<code>fn</code>&nbsp;only returns numbers and those numbers determine the sort order of&nbsp;<code>sortedArr</code>. <code>sortedArr</code> must be sorted in <strong>ascending order</strong> by <code>fn</code> output.</p> <p>You may assume that <code>fn</code> will never duplicate numbers for a given array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [5, 4, 1, 2, 3], fn = (x) =&gt; x <strong>Output:</strong> [1, 2, 3, 4, 5] <strong>Explanation:</strong> fn simply returns the number passed to it so the array is sorted in ascending order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [{&quot;x&quot;: 1}, {&quot;x&quot;: 0}, {&quot;x&quot;: -1}], fn = (d) =&gt; d.x <strong>Output:</strong> [{&quot;x&quot;: -1}, {&quot;x&quot;: 0}, {&quot;x&quot;: 1}] <strong>Explanation:</strong> fn returns the value for the &quot;x&quot; key. So the array is sorted based on that value. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [[3, 4], [5, 2], [10, 1]], fn = (x) =&gt; x[1] <strong>Output:</strong> [[10, 1], [5, 2], [3, 4]] <strong>Explanation:</strong> arr is sorted in ascending order by number at index=1.&nbsp; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr</code> is a valid JSON array</li> <li><code>fn</code> is a function that returns a number</li> <li><code>1 &lt;=&nbsp;arr.length &lt;= 5 * 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
function sortBy(arr: any[], fn: Function): any[] { return arr.sort((a, b) => fn(a) - fn(b)); }
2,725
Interval Cancellation
Easy
<p>Given a function <code>fn</code>, an array of arguments&nbsp;<code>args</code>, and&nbsp;an interval time <code>t</code>, return a cancel function <code>cancelFn</code>.</p> <p>After a delay of&nbsp;<code>cancelTimeMs</code>, the returned cancel function&nbsp;<code>cancelFn</code>&nbsp;will be invoked.</p> <pre> setTimeout(cancelFn, cancelTimeMs) </pre> <p>The function <code>fn</code> should be called with <code>args</code> immediately and then called again every&nbsp;<code>t</code> milliseconds&nbsp;until&nbsp;<code>cancelFn</code>&nbsp;is called at <code>cancelTimeMs</code> ms.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (x) =&gt; x * 2, args = [4], t = 35 <strong>Output:</strong> [ {&quot;time&quot;: 0, &quot;returned&quot;: 8}, {&quot;time&quot;: 35, &quot;returned&quot;: 8}, {&quot;time&quot;: 70, &quot;returned&quot;: 8}, {&quot;time&quot;: 105, &quot;returned&quot;: 8}, {&quot;time&quot;: 140, &quot;returned&quot;: 8}, {&quot;time&quot;: 175, &quot;returned&quot;: 8} ] <strong>Explanation:</strong> const cancelTimeMs = 190; const cancelFn = cancellable((x) =&gt; x * 2, [4], 35); setTimeout(cancelFn, cancelTimeMs); Every 35ms, fn(4) is called. Until t=190ms, then it is cancelled. 1st fn call is at 0ms. fn(4) returns 8. 2nd fn call is at 35ms. fn(4) returns 8. 3rd fn call is at 70ms. fn(4) returns 8. 4th fn call is at&nbsp;105ms. fn(4) returns 8. 5th fn call is at 140ms. fn(4) returns 8. 6th fn call is at 175ms. fn(4) returns 8. Cancelled at 190ms </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (x1, x2) =&gt; (x1 * x2), args = [2, 5], t = 30 <strong>Output:</strong> [ {&quot;time&quot;: 0, &quot;returned&quot;: 10}, {&quot;time&quot;: 30, &quot;returned&quot;: 10}, {&quot;time&quot;: 60, &quot;returned&quot;: 10}, {&quot;time&quot;: 90, &quot;returned&quot;: 10}, {&quot;time&quot;: 120, &quot;returned&quot;: 10}, {&quot;time&quot;: 150, &quot;returned&quot;: 10} ] <strong>Explanation:</strong> const cancelTimeMs = 165; const cancelFn = cancellable((x1, x2) =&gt; (x1 * x2), [2, 5], 30) setTimeout(cancelFn, cancelTimeMs) Every 30ms, fn(2, 5) is called. Until t=165ms, then it is cancelled. 1st fn call is at 0ms&nbsp; 2nd fn call is at 30ms&nbsp; 3rd fn call is at 60ms&nbsp; 4th fn call is at&nbsp;90ms&nbsp; 5th fn call is at 120ms&nbsp; 6th fn call is at 150ms Cancelled at 165ms </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> fn = (x1, x2, x3) =&gt; (x1 + x2 + x3), args = [5, 1, 3], t = 50 <strong>Output:</strong> [ {&quot;time&quot;: 0, &quot;returned&quot;: 9}, {&quot;time&quot;: 50, &quot;returned&quot;: 9}, {&quot;time&quot;: 100, &quot;returned&quot;: 9}, {&quot;time&quot;: 150, &quot;returned&quot;: 9} ] <strong>Explanation:</strong> const cancelTimeMs = 180; const cancelFn = cancellable((x1, x2, x3) =&gt; (x1 + x2 + x3), [5, 1, 3], 50) setTimeout(cancelFn, cancelTimeMs) Every 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled. 1st fn call is at 0ms 2nd fn call is at 50ms 3rd fn call is at 100ms 4th fn call is at&nbsp;150ms Cancelled at 180ms </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>fn</code> is a function</li> <li><code>args</code> is a valid JSON array</li> <li><code>1 &lt;= args.length &lt;= 10</code></li> <li><code><font face="monospace">30 &lt;= t &lt;= 100</font></code></li> <li><code><font face="monospace">10 &lt;= </font>cancelTimeMs<font face="monospace"> &lt;= 500</font></code></li> </ul>
JavaScript
TypeScript
function cancellable(fn: Function, args: any[], t: number): Function { fn(...args); const time = setInterval(() => fn(...args), t); return () => clearInterval(time); } /** * const result = [] * * const fn = (x) => x * 2 * const args = [4], t = 20, cancelT = 110 * * const log = (...argsArr) => { * result.push(fn(...argsArr)) * } * * const cancel = cancellable(fn, args, t); * * setTimeout(() => { * cancel() * console.log(result) // [ * // {"time":0,"returned":8}, * // {"time":20,"returned":8}, * // {"time":40,"returned":8}, * // {"time":60,"returned":8}, * // {"time":80,"returned":8}, * // {"time":100,"returned":8} * // ] * }, cancelT) */
2,726
Calculator with Method Chaining
Easy
<p>Design a <code>Calculator</code> class. The class should provide the&nbsp;mathematical operations of&nbsp;addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining.&nbsp;The <code>Calculator</code> class constructor should accept a number&nbsp;which serves as the&nbsp;initial value of <code>result</code>.</p> <p>Your <font face="monospace"><code>Calculator</code>&nbsp;</font>class should have the following methods:</p> <ul> <li><code>add</code> - This method adds the given number <code>value</code> to the&nbsp;<code>result</code> and returns the updated <code>Calculator</code>.</li> <li><code>subtract</code> -&nbsp;This method subtracts the given number <code>value</code>&nbsp;from the&nbsp;<code>result</code> and returns the updated <code>Calculator</code>.</li> <li><code>multiply</code> -&nbsp;This method multiplies the <code>result</code>&nbsp; by the given number <code>value</code> and returns the updated <code>Calculator</code>.</li> <li><code>divide</code> -&nbsp;This method divides the <code>result</code> by the given number <code>value</code> and returns the updated <code>Calculator</code>. If the passed value is <code>0</code>, an error <code>&quot;Division by zero is not allowed&quot;</code> should be thrown.</li> <li><code>power</code> -&nbsp;This method raises the&nbsp;<code>result</code> to the power of the given number <code>value</code> and returns the updated <code>Calculator</code>.</li> <li><code>getResult</code> -&nbsp;This method returns the <code>result</code>.</li> </ul> <p>Solutions within&nbsp;<code>10<sup>-5</sup></code>&nbsp;of the actual result are considered correct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;Calculator&quot;, &quot;add&quot;, &quot;subtract&quot;, &quot;getResult&quot;], values = [10, 5, 7] <strong>Output:</strong> 8 <strong>Explanation:</strong> new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;Calculator&quot;, &quot;multiply&quot;, &quot;power&quot;, &quot;getResult&quot;], values = [2, 5, 2] <strong>Output:</strong> 100 <strong>Explanation:</strong> new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;Calculator&quot;, &quot;divide&quot;, &quot;getResult&quot;], values = [20, 0] <strong>Output:</strong> &quot;Division by zero is not allowed&quot; <strong>Explanation:</strong> new Calculator(20).divide(0).getResult() // 20 / 0 The error should be thrown because we cannot divide by zero. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>actions</code> is a valid JSON array of strings</li> <li><code>values</code>&nbsp;is a valid JSON array of numbers</li> <li><code>2 &lt;= actions.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= values.length &lt;= 2 * 10<sup>4</sup>&nbsp;- 1</code></li> <li><code>actions[i]</code> is one of &quot;Calculator&quot;, &quot;add&quot;, &quot;subtract&quot;, &quot;multiply&quot;, &quot;divide&quot;, &quot;power&quot;, and&nbsp;&quot;getResult&quot;</li> <li>First action is always &quot;Calculator&quot;</li> <li>Last action is always &quot;getResult&quot;</li> </ul>
JavaScript
TypeScript
class Calculator { private x: number; constructor(value: number) { this.x = value; } add(value: number): Calculator { this.x += value; return this; } subtract(value: number): Calculator { this.x -= value; return this; } multiply(value: number): Calculator { this.x *= value; return this; } divide(value: number): Calculator { if (value === 0) { throw new Error('Division by zero is not allowed'); } this.x /= value; return this; } power(value: number): Calculator { this.x **= value; return this; } getResult(): number { return this.x; } }
2,727
Is Object Empty
Easy
<p>Given an object or an array, return if it is empty.</p> <ul> <li>An empty object contains no key-value pairs.</li> <li>An empty array contains no elements.</li> </ul> <p>You may assume the object or array is the output of&nbsp;<code>JSON.parse</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;x&quot;: 5, &quot;y&quot;: 42} <strong>Output:</strong> false <strong>Explanation:</strong> The object has 2 key-value pairs so it is not empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = {} <strong>Output:</strong> true <strong>Explanation:</strong> The object doesn&#39;t have any key-value pairs so it is empty. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj = [null, false, 0] <strong>Output:</strong> false <strong>Explanation:</strong> The array has 3 elements so it is not empty. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a valid JSON object or array</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Can you solve it in O(1) time?</strong>
JavaScript
JavaScript
/** * @param {Object | Array} obj * @return {boolean} */ var isEmpty = function (obj) { for (const x in obj) { return false; } return true; };
2,727
Is Object Empty
Easy
<p>Given an object or an array, return if it is empty.</p> <ul> <li>An empty object contains no key-value pairs.</li> <li>An empty array contains no elements.</li> </ul> <p>You may assume the object or array is the output of&nbsp;<code>JSON.parse</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;x&quot;: 5, &quot;y&quot;: 42} <strong>Output:</strong> false <strong>Explanation:</strong> The object has 2 key-value pairs so it is not empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = {} <strong>Output:</strong> true <strong>Explanation:</strong> The object doesn&#39;t have any key-value pairs so it is empty. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj = [null, false, 0] <strong>Output:</strong> false <strong>Explanation:</strong> The array has 3 elements so it is not empty. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a valid JSON object or array</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <strong>Can you solve it in O(1) time?</strong>
JavaScript
TypeScript
function isEmpty(obj: Record<string, any> | any[]): boolean { for (const x in obj) { return false; } return true; }
2,728
Count Houses in a Circular Street
Easy
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a circular street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses&#39; doors could be open or closed initially.</p> <p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p> <p>The class <code>Street</code> contains the following functions which may help you:</p> <ul> <li><code>void openDoor()</code>: Open the door of the house you are in front of.</li> <li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li> <li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li> <li><code>void moveRight()</code>: Move to the right house.</li> <li><code>void moveLeft()</code>: Move to the left house.</li> </ul> <p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> street = [0,0,0,0], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 houses, and all their doors are closed. The number of houses is less than k, which is 10.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> street = [1,0,1,1,0], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed. The number of houses is equal to k, which is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of houses</code></li> <li><code>1 &lt;= n &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Interactive
C++
/** * Definition for a street. * class Street { * public: * Street(vector<int> doors); * void openDoor(); * void closeDoor(); * bool isDoorOpen(); * void moveRight(); * void moveLeft(); * }; */ class Solution { public: int houseCount(Street* street, int k) { while (k--) { street->openDoor(); street->moveLeft(); } int ans = 0; while (street->isDoorOpen()) { ans++; street->closeDoor(); street->moveLeft(); } return ans; } };
2,728
Count Houses in a Circular Street
Easy
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a circular street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses&#39; doors could be open or closed initially.</p> <p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p> <p>The class <code>Street</code> contains the following functions which may help you:</p> <ul> <li><code>void openDoor()</code>: Open the door of the house you are in front of.</li> <li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li> <li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li> <li><code>void moveRight()</code>: Move to the right house.</li> <li><code>void moveLeft()</code>: Move to the left house.</li> </ul> <p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> street = [0,0,0,0], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 houses, and all their doors are closed. The number of houses is less than k, which is 10.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> street = [1,0,1,1,0], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed. The number of houses is equal to k, which is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of houses</code></li> <li><code>1 &lt;= n &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Interactive
Go
/** * Definition for a street. * type Street interface { * OpenDoor() * CloseDoor() * IsDoorOpen() bool * MoveRight() * MoveLeft() * } */ func houseCount(street Street, k int) (ans int) { for ; k > 0; k-- { street.OpenDoor() street.MoveLeft() } for ; street.IsDoorOpen(); street.MoveLeft() { ans++ street.CloseDoor() } return }
2,728
Count Houses in a Circular Street
Easy
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a circular street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses&#39; doors could be open or closed initially.</p> <p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p> <p>The class <code>Street</code> contains the following functions which may help you:</p> <ul> <li><code>void openDoor()</code>: Open the door of the house you are in front of.</li> <li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li> <li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li> <li><code>void moveRight()</code>: Move to the right house.</li> <li><code>void moveLeft()</code>: Move to the left house.</li> </ul> <p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> street = [0,0,0,0], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 houses, and all their doors are closed. The number of houses is less than k, which is 10.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> street = [1,0,1,1,0], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed. The number of houses is equal to k, which is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of houses</code></li> <li><code>1 &lt;= n &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Interactive
Java
/** * Definition for a street. * class Street { * public Street(int[] doors); * public void openDoor(); * public void closeDoor(); * public boolean isDoorOpen(); * public void moveRight(); * public void moveLeft(); * } */ class Solution { public int houseCount(Street street, int k) { while (k-- > 0) { street.openDoor(); street.moveLeft(); } int ans = 0; while (street.isDoorOpen()) { ++ans; street.closeDoor(); street.moveLeft(); } return ans; } }
2,728
Count Houses in a Circular Street
Easy
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a circular street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses&#39; doors could be open or closed initially.</p> <p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p> <p>The class <code>Street</code> contains the following functions which may help you:</p> <ul> <li><code>void openDoor()</code>: Open the door of the house you are in front of.</li> <li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li> <li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li> <li><code>void moveRight()</code>: Move to the right house.</li> <li><code>void moveLeft()</code>: Move to the left house.</li> </ul> <p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> street = [0,0,0,0], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 houses, and all their doors are closed. The number of houses is less than k, which is 10.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> street = [1,0,1,1,0], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed. The number of houses is equal to k, which is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of houses</code></li> <li><code>1 &lt;= n &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Interactive
Python
# Definition for a street. # class Street: # def openDoor(self): # pass # def closeDoor(self): # pass # def isDoorOpen(self): # pass # def moveRight(self): # pass # def moveLeft(self): # pass class Solution: def houseCount(self, street: Optional["Street"], k: int) -> int: for _ in range(k): street.openDoor() street.moveLeft() ans = 0 while street.isDoorOpen(): street.closeDoor() street.moveLeft() ans += 1 return ans
2,728
Count Houses in a Circular Street
Easy
<p>You are given an object <code>street</code> of class <code>Street</code> that represents a circular street and a positive integer <code>k</code> which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to <code>k</code>). Houses&#39; doors could be open or closed initially.</p> <p>Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.</p> <p>The class <code>Street</code> contains the following functions which may help you:</p> <ul> <li><code>void openDoor()</code>: Open the door of the house you are in front of.</li> <li><code>void closeDoor()</code>: Close the door of the house you are in front of.</li> <li><code>boolean isDoorOpen()</code>: Returns <code>true</code> if the door of the current house is open and <code>false</code> otherwise.</li> <li><code>void moveRight()</code>: Move to the right house.</li> <li><code>void moveLeft()</code>: Move to the left house.</li> </ul> <p>Return <code>ans</code> <em>which represents the number of houses on this street.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> street = [0,0,0,0], k = 10 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 houses, and all their doors are closed. The number of houses is less than k, which is 10.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> street = [1,0,1,1,0], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed. The number of houses is equal to k, which is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == number of houses</code></li> <li><code>1 &lt;= n &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Interactive
TypeScript
/** * Definition for a street. * class Street { * constructor(doors: number[]); * public openDoor(): void; * public closeDoor(): void; * public isDoorOpen(): boolean; * public moveRight(): void; * public moveLeft(): void; * } */ function houseCount(street: Street | null, k: number): number { while (k-- > 0) { street.openDoor(); street.moveLeft(); } let ans = 0; while (street.isDoorOpen()) { ++ans; street.closeDoor(); street.moveLeft(); } return ans; }
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
C++
class Solution { public: bool isFascinating(int n) { string s = to_string(n) + to_string(n * 2) + to_string(n * 3); sort(s.begin(), s.end()); return s == "123456789"; } };
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
Go
func isFascinating(n int) bool { s := strconv.Itoa(n) + strconv.Itoa(n*2) + strconv.Itoa(n*3) cnt := [10]int{} for _, c := range s { cnt[c-'0']++ if cnt[c-'0'] > 1 { return false } } return cnt[0] == 0 && len(s) == 9 }
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
Java
class Solution { public boolean isFascinating(int n) { String s = "" + n + (2 * n) + (3 * n); int[] cnt = new int[10]; for (char c : s.toCharArray()) { if (++cnt[c - '0'] > 1) { return false; } } return cnt[0] == 0 && s.length() == 9; } }
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
Python
class Solution: def isFascinating(self, n: int) -> bool: s = str(n) + str(2 * n) + str(3 * n) return "".join(sorted(s)) == "123456789"
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
Rust
impl Solution { pub fn is_fascinating(n: i32) -> bool { let s = format!("{}{}{}", n, n * 2, n * 3); let mut cnt = vec![0; 10]; for c in s.chars() { let t = (c as usize) - ('0' as usize); cnt[t] += 1; if cnt[t] > 1 { return false; } } cnt[0] == 0 && s.len() == 9 } }
2,729
Check if The Number is Fascinating
Easy
<p>You are given an integer <code>n</code> that consists of exactly <code>3</code> digits.</p> <p>We call the number <code>n</code> <strong>fascinating</strong> if, after the following modification, the resulting number contains all the digits from <code>1</code> to <code>9</code> <strong>exactly</strong> once and does not contain any <code>0</code>&#39;s:</p> <ul> <li><strong>Concatenate</strong> <code>n</code> with the numbers <code>2 * n</code> and <code>3 * n</code>.</li> </ul> <p>Return <code>true</code><em> if </em><code>n</code><em> is fascinating, or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Concatenating</strong> two numbers means joining them together. For example, the concatenation of <code>121</code> and <code>371</code> is <code>121371</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 192 <strong>Output:</strong> true <strong>Explanation:</strong> We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 100 <strong>Output:</strong> false <strong>Explanation:</strong> We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>100 &lt;= n &lt;= 999</code></li> </ul>
Hash Table; Math
TypeScript
function isFascinating(n: number): boolean { const s = `${n}${n * 2}${n * 3}`; return s.split('').sort().join('') === '123456789'; }
2,730
Find the Longest Semi-Repetitive Substring
Medium
<p>You are given a digit string <code>s</code> that consists of digits from 0 to 9.</p> <p>A string is called <strong>semi-repetitive</strong> if there is <strong>at most</strong> one adjacent pair of the same digit. For example, <code>&quot;0010&quot;</code>, <code>&quot;002020&quot;</code>, <code>&quot;0123&quot;</code>, <code>&quot;2002&quot;</code>, and <code>&quot;54944&quot;</code> are semi-repetitive while the following are not: <code>&quot;00101022&quot;</code> (adjacent same digit pairs are 00 and 22), and <code>&quot;1101234883&quot;</code> (adjacent same digit pairs are 11 and 88).</p> <p>Return the length of the <strong>longest semi-repetitive <span data-keyword="substring-nonempty">substring</span></strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;52233&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;5223&quot;. Picking the whole string &quot;52233&quot; has two adjacent same digit pairs 22 and 33, but at most one is allowed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;5494&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> is a semi-repetitive string.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1111111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;11&quot;. Picking the substring &quot;111&quot; has two adjacent same digit pairs, but at most one is allowed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;9&#39;</code></li> </ul>
String; Sliding Window
C++
class Solution { public: int longestSemiRepetitiveSubstring(string s) { int ans = 1, n = s.size(); for (int i = 1, j = 0, cnt = 0; i < n; ++i) { cnt += s[i] == s[i - 1] ? 1 : 0; for (; cnt > 1; ++j) { cnt -= s[j] == s[j + 1] ? 1 : 0; } ans = max(ans, i - j + 1); } return ans; } };
2,730
Find the Longest Semi-Repetitive Substring
Medium
<p>You are given a digit string <code>s</code> that consists of digits from 0 to 9.</p> <p>A string is called <strong>semi-repetitive</strong> if there is <strong>at most</strong> one adjacent pair of the same digit. For example, <code>&quot;0010&quot;</code>, <code>&quot;002020&quot;</code>, <code>&quot;0123&quot;</code>, <code>&quot;2002&quot;</code>, and <code>&quot;54944&quot;</code> are semi-repetitive while the following are not: <code>&quot;00101022&quot;</code> (adjacent same digit pairs are 00 and 22), and <code>&quot;1101234883&quot;</code> (adjacent same digit pairs are 11 and 88).</p> <p>Return the length of the <strong>longest semi-repetitive <span data-keyword="substring-nonempty">substring</span></strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;52233&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;5223&quot;. Picking the whole string &quot;52233&quot; has two adjacent same digit pairs 22 and 33, but at most one is allowed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;5494&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> is a semi-repetitive string.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1111111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;11&quot;. Picking the substring &quot;111&quot; has two adjacent same digit pairs, but at most one is allowed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;9&#39;</code></li> </ul>
String; Sliding Window
Go
func longestSemiRepetitiveSubstring(s string) (ans int) { ans = 1 for i, j, cnt := 1, 0, 0; i < len(s); i++ { if s[i] == s[i-1] { cnt++ } for ; cnt > 1; j++ { if s[j] == s[j+1] { cnt-- } } ans = max(ans, i-j+1) } return }
2,730
Find the Longest Semi-Repetitive Substring
Medium
<p>You are given a digit string <code>s</code> that consists of digits from 0 to 9.</p> <p>A string is called <strong>semi-repetitive</strong> if there is <strong>at most</strong> one adjacent pair of the same digit. For example, <code>&quot;0010&quot;</code>, <code>&quot;002020&quot;</code>, <code>&quot;0123&quot;</code>, <code>&quot;2002&quot;</code>, and <code>&quot;54944&quot;</code> are semi-repetitive while the following are not: <code>&quot;00101022&quot;</code> (adjacent same digit pairs are 00 and 22), and <code>&quot;1101234883&quot;</code> (adjacent same digit pairs are 11 and 88).</p> <p>Return the length of the <strong>longest semi-repetitive <span data-keyword="substring-nonempty">substring</span></strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;52233&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;5223&quot;. Picking the whole string &quot;52233&quot; has two adjacent same digit pairs 22 and 33, but at most one is allowed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;5494&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> is a semi-repetitive string.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1111111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;11&quot;. Picking the substring &quot;111&quot; has two adjacent same digit pairs, but at most one is allowed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;9&#39;</code></li> </ul>
String; Sliding Window
Java
class Solution { public int longestSemiRepetitiveSubstring(String s) { int ans = 1, n = s.length(); for (int i = 1, j = 0, cnt = 0; i < n; ++i) { cnt += s.charAt(i) == s.charAt(i - 1) ? 1 : 0; for (; cnt > 1; ++j) { cnt -= s.charAt(j) == s.charAt(j + 1) ? 1 : 0; } ans = Math.max(ans, i - j + 1); } return ans; } }
2,730
Find the Longest Semi-Repetitive Substring
Medium
<p>You are given a digit string <code>s</code> that consists of digits from 0 to 9.</p> <p>A string is called <strong>semi-repetitive</strong> if there is <strong>at most</strong> one adjacent pair of the same digit. For example, <code>&quot;0010&quot;</code>, <code>&quot;002020&quot;</code>, <code>&quot;0123&quot;</code>, <code>&quot;2002&quot;</code>, and <code>&quot;54944&quot;</code> are semi-repetitive while the following are not: <code>&quot;00101022&quot;</code> (adjacent same digit pairs are 00 and 22), and <code>&quot;1101234883&quot;</code> (adjacent same digit pairs are 11 and 88).</p> <p>Return the length of the <strong>longest semi-repetitive <span data-keyword="substring-nonempty">substring</span></strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;52233&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;5223&quot;. Picking the whole string &quot;52233&quot; has two adjacent same digit pairs 22 and 33, but at most one is allowed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;5494&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> is a semi-repetitive string.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1111111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;11&quot;. Picking the substring &quot;111&quot; has two adjacent same digit pairs, but at most one is allowed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;9&#39;</code></li> </ul>
String; Sliding Window
Python
class Solution: def longestSemiRepetitiveSubstring(self, s: str) -> int: ans, n = 1, len(s) cnt = j = 0 for i in range(1, n): cnt += s[i] == s[i - 1] while cnt > 1: cnt -= s[j] == s[j + 1] j += 1 ans = max(ans, i - j + 1) return ans
2,730
Find the Longest Semi-Repetitive Substring
Medium
<p>You are given a digit string <code>s</code> that consists of digits from 0 to 9.</p> <p>A string is called <strong>semi-repetitive</strong> if there is <strong>at most</strong> one adjacent pair of the same digit. For example, <code>&quot;0010&quot;</code>, <code>&quot;002020&quot;</code>, <code>&quot;0123&quot;</code>, <code>&quot;2002&quot;</code>, and <code>&quot;54944&quot;</code> are semi-repetitive while the following are not: <code>&quot;00101022&quot;</code> (adjacent same digit pairs are 00 and 22), and <code>&quot;1101234883&quot;</code> (adjacent same digit pairs are 11 and 88).</p> <p>Return the length of the <strong>longest semi-repetitive <span data-keyword="substring-nonempty">substring</span></strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;52233&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;5223&quot;. Picking the whole string &quot;52233&quot; has two adjacent same digit pairs 22 and 33, but at most one is allowed.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;5494&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> is a semi-repetitive string.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1111111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repetitive substring is &quot;11&quot;. Picking the substring &quot;111&quot; has two adjacent same digit pairs, but at most one is allowed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;9&#39;</code></li> </ul>
String; Sliding Window
TypeScript
function longestSemiRepetitiveSubstring(s: string): number { const n = s.length; let ans = 1; for (let i = 1, j = 0, cnt = 0; i < n; ++i) { cnt += s[i] === s[i - 1] ? 1 : 0; for (; cnt > 1; ++j) { cnt -= s[j] === s[j + 1] ? 1 : 0; } ans = Math.max(ans, i - j + 1); } return ans; }
2,731
Movement of Robots
Medium
<p>Some robots are standing on an infinite number line with their initial coordinates given by a <strong>0-indexed</strong> integer array <code>nums</code> and will start moving once given the command to move. The robots will move a unit distance each second.</p> <p>You are given a string <code>s</code> denoting the direction in which robots will move on command. <code>&#39;L&#39;</code> means the robot will move towards the left side or negative side of the number line, whereas <code>&#39;R&#39;</code> means the robot will move towards the right side or positive side of the number line.</p> <p>If two robots collide, they will start moving in opposite directions.</p> <p>Return <em>the sum of distances between all the&nbsp;pairs of robots </em><code>d</code> <em>seconds after&nbsp;the command. </em>Since the sum can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p><b>Note: </b></p> <ul> <li>For two robots at the index <code>i</code> and <code>j</code>, pair <code>(i,j)</code> and pair <code>(j,i)</code> are considered the same pair.</li> <li>When robots collide, they <strong>instantly change</strong> their directions without wasting any time.</li> <li>Collision happens&nbsp;when two robots share the same place in a&nbsp;moment. <ul> <li>For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they&#39;ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.</li> <li>For example,&nbsp;if a robot is positioned in 0 going to the right and another is positioned in 1&nbsp;going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,2], s = &quot;RLL&quot;, d = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0], s = &quot;RL&quot;, d = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2 * 10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> <li><code>nums.length == s.length&nbsp;</code></li> <li><code>s</code> consists of &#39;L&#39; and &#39;R&#39; only</li> <li><code>nums[i]</code>&nbsp;will be unique.</li> </ul>
Brainteaser; Array; Prefix Sum; Sorting
C++
class Solution { public: int sumDistance(vector<int>& nums, string s, int d) { int n = nums.size(); vector<long long> arr(n); for (int i = 0; i < n; ++i) { arr[i] = 1LL * nums[i] + (s[i] == 'L' ? -d : d); } sort(arr.begin(), arr.end()); long long ans = 0; long long sum = 0; const int mod = 1e9 + 7; for (int i = 0; i < n; ++i) { ans = (ans + i * arr[i] - sum) % mod; sum += arr[i]; } return ans; } };
2,731
Movement of Robots
Medium
<p>Some robots are standing on an infinite number line with their initial coordinates given by a <strong>0-indexed</strong> integer array <code>nums</code> and will start moving once given the command to move. The robots will move a unit distance each second.</p> <p>You are given a string <code>s</code> denoting the direction in which robots will move on command. <code>&#39;L&#39;</code> means the robot will move towards the left side or negative side of the number line, whereas <code>&#39;R&#39;</code> means the robot will move towards the right side or positive side of the number line.</p> <p>If two robots collide, they will start moving in opposite directions.</p> <p>Return <em>the sum of distances between all the&nbsp;pairs of robots </em><code>d</code> <em>seconds after&nbsp;the command. </em>Since the sum can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p><b>Note: </b></p> <ul> <li>For two robots at the index <code>i</code> and <code>j</code>, pair <code>(i,j)</code> and pair <code>(j,i)</code> are considered the same pair.</li> <li>When robots collide, they <strong>instantly change</strong> their directions without wasting any time.</li> <li>Collision happens&nbsp;when two robots share the same place in a&nbsp;moment. <ul> <li>For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they&#39;ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.</li> <li>For example,&nbsp;if a robot is positioned in 0 going to the right and another is positioned in 1&nbsp;going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,2], s = &quot;RLL&quot;, d = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0], s = &quot;RL&quot;, d = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2 * 10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> <li><code>nums.length == s.length&nbsp;</code></li> <li><code>s</code> consists of &#39;L&#39; and &#39;R&#39; only</li> <li><code>nums[i]</code>&nbsp;will be unique.</li> </ul>
Brainteaser; Array; Prefix Sum; Sorting
Go
func sumDistance(nums []int, s string, d int) (ans int) { for i, c := range s { if c == 'R' { nums[i] += d } else { nums[i] -= d } } sort.Ints(nums) sum := 0 const mod int = 1e9 + 7 for i, x := range nums { ans = (ans + i*x - sum) % mod sum += x } return }
2,731
Movement of Robots
Medium
<p>Some robots are standing on an infinite number line with their initial coordinates given by a <strong>0-indexed</strong> integer array <code>nums</code> and will start moving once given the command to move. The robots will move a unit distance each second.</p> <p>You are given a string <code>s</code> denoting the direction in which robots will move on command. <code>&#39;L&#39;</code> means the robot will move towards the left side or negative side of the number line, whereas <code>&#39;R&#39;</code> means the robot will move towards the right side or positive side of the number line.</p> <p>If two robots collide, they will start moving in opposite directions.</p> <p>Return <em>the sum of distances between all the&nbsp;pairs of robots </em><code>d</code> <em>seconds after&nbsp;the command. </em>Since the sum can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p><b>Note: </b></p> <ul> <li>For two robots at the index <code>i</code> and <code>j</code>, pair <code>(i,j)</code> and pair <code>(j,i)</code> are considered the same pair.</li> <li>When robots collide, they <strong>instantly change</strong> their directions without wasting any time.</li> <li>Collision happens&nbsp;when two robots share the same place in a&nbsp;moment. <ul> <li>For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they&#39;ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.</li> <li>For example,&nbsp;if a robot is positioned in 0 going to the right and another is positioned in 1&nbsp;going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,2], s = &quot;RLL&quot;, d = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0], s = &quot;RL&quot;, d = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2 * 10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> <li><code>nums.length == s.length&nbsp;</code></li> <li><code>s</code> consists of &#39;L&#39; and &#39;R&#39; only</li> <li><code>nums[i]</code>&nbsp;will be unique.</li> </ul>
Brainteaser; Array; Prefix Sum; Sorting
Java
class Solution { public int sumDistance(int[] nums, String s, int d) { int n = nums.length; long[] arr = new long[n]; for (int i = 0; i < n; ++i) { arr[i] = (long) nums[i] + (s.charAt(i) == 'L' ? -d : d); } Arrays.sort(arr); long ans = 0, sum = 0; final int mod = (int) 1e9 + 7; for (int i = 0; i < n; ++i) { ans = (ans + i * arr[i] - sum) % mod; sum += arr[i]; } return (int) ans; } }
2,731
Movement of Robots
Medium
<p>Some robots are standing on an infinite number line with their initial coordinates given by a <strong>0-indexed</strong> integer array <code>nums</code> and will start moving once given the command to move. The robots will move a unit distance each second.</p> <p>You are given a string <code>s</code> denoting the direction in which robots will move on command. <code>&#39;L&#39;</code> means the robot will move towards the left side or negative side of the number line, whereas <code>&#39;R&#39;</code> means the robot will move towards the right side or positive side of the number line.</p> <p>If two robots collide, they will start moving in opposite directions.</p> <p>Return <em>the sum of distances between all the&nbsp;pairs of robots </em><code>d</code> <em>seconds after&nbsp;the command. </em>Since the sum can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p><b>Note: </b></p> <ul> <li>For two robots at the index <code>i</code> and <code>j</code>, pair <code>(i,j)</code> and pair <code>(j,i)</code> are considered the same pair.</li> <li>When robots collide, they <strong>instantly change</strong> their directions without wasting any time.</li> <li>Collision happens&nbsp;when two robots share the same place in a&nbsp;moment. <ul> <li>For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they&#39;ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.</li> <li>For example,&nbsp;if a robot is positioned in 0 going to the right and another is positioned in 1&nbsp;going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,2], s = &quot;RLL&quot;, d = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0], s = &quot;RL&quot;, d = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2 * 10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> <li><code>nums.length == s.length&nbsp;</code></li> <li><code>s</code> consists of &#39;L&#39; and &#39;R&#39; only</li> <li><code>nums[i]</code>&nbsp;will be unique.</li> </ul>
Brainteaser; Array; Prefix Sum; Sorting
Python
class Solution: def sumDistance(self, nums: List[int], s: str, d: int) -> int: mod = 10**9 + 7 for i, c in enumerate(s): nums[i] += d if c == "R" else -d nums.sort() ans = s = 0 for i, x in enumerate(nums): ans += i * x - s s += x return ans % mod
2,731
Movement of Robots
Medium
<p>Some robots are standing on an infinite number line with their initial coordinates given by a <strong>0-indexed</strong> integer array <code>nums</code> and will start moving once given the command to move. The robots will move a unit distance each second.</p> <p>You are given a string <code>s</code> denoting the direction in which robots will move on command. <code>&#39;L&#39;</code> means the robot will move towards the left side or negative side of the number line, whereas <code>&#39;R&#39;</code> means the robot will move towards the right side or positive side of the number line.</p> <p>If two robots collide, they will start moving in opposite directions.</p> <p>Return <em>the sum of distances between all the&nbsp;pairs of robots </em><code>d</code> <em>seconds after&nbsp;the command. </em>Since the sum can be very large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p><b>Note: </b></p> <ul> <li>For two robots at the index <code>i</code> and <code>j</code>, pair <code>(i,j)</code> and pair <code>(j,i)</code> are considered the same pair.</li> <li>When robots collide, they <strong>instantly change</strong> their directions without wasting any time.</li> <li>Collision happens&nbsp;when two robots share the same place in a&nbsp;moment. <ul> <li>For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they&#39;ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.</li> <li>For example,&nbsp;if a robot is positioned in 0 going to the right and another is positioned in 1&nbsp;going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-2,0,2], s = &quot;RLL&quot;, d = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> After 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right. After 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right. After 3 seconds, the positions are [-3,-1,1]. The distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2. The distance between the robot at index 0 and 2 is abs(-3 - 1) = 4. The distance between the robot at index 1 and 2 is abs(-1 - 1) = 2. The sum of the pairs of all distances = 2 + 4 + 2 = 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0], s = &quot;RL&quot;, d = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 1 second, the positions are [2,-1]. After 2 seconds, the positions are [3,-2]. The distance between the two robots is abs(-2 - 3) = 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2 * 10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> <li><code>nums.length == s.length&nbsp;</code></li> <li><code>s</code> consists of &#39;L&#39; and &#39;R&#39; only</li> <li><code>nums[i]</code>&nbsp;will be unique.</li> </ul>
Brainteaser; Array; Prefix Sum; Sorting
TypeScript
function sumDistance(nums: number[], s: string, d: number): number { const n = nums.length; for (let i = 0; i < n; ++i) { nums[i] += s[i] === 'L' ? -d : d; } nums.sort((a, b) => a - b); let ans = 0; let sum = 0; const mod = 1e9 + 7; for (let i = 0; i < n; ++i) { ans = (ans + i * nums[i] - sum) % mod; sum += nums[i]; } return ans; }
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
C++
class Solution { public: vector<int> goodSubsetofBinaryMatrix(vector<vector<int>>& grid) { unordered_map<int, int> g; for (int i = 0; i < grid.size(); ++i) { int mask = 0; for (int j = 0; j < grid[0].size(); ++j) { mask |= grid[i][j] << j; } if (mask == 0) { return {i}; } g[mask] = i; } for (auto& [a, i] : g) { for (auto& [b, j] : g) { if ((a & b) == 0) { return {min(i, j), max(i, j)}; } } } return {}; } };
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
Go
func goodSubsetofBinaryMatrix(grid [][]int) []int { g := map[int]int{} for i, row := range grid { mask := 0 for j, x := range row { mask |= x << j } if mask == 0 { return []int{i} } g[mask] = i } for a, i := range g { for b, j := range g { if a&b == 0 { return []int{min(i, j), max(i, j)} } } } return []int{} }
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
Java
class Solution { public List<Integer> goodSubsetofBinaryMatrix(int[][] grid) { Map<Integer, Integer> g = new HashMap<>(); for (int i = 0; i < grid.length; ++i) { int mask = 0; for (int j = 0; j < grid[0].length; ++j) { mask |= grid[i][j] << j; } if (mask == 0) { return List.of(i); } g.put(mask, i); } for (var e1 : g.entrySet()) { for (var e2 : g.entrySet()) { if ((e1.getKey() & e2.getKey()) == 0) { int i = e1.getValue(), j = e2.getValue(); return List.of(Math.min(i, j), Math.max(i, j)); } } } return List.of(); } }
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
Python
class Solution: def goodSubsetofBinaryMatrix(self, grid: List[List[int]]) -> List[int]: g = {} for i, row in enumerate(grid): mask = 0 for j, x in enumerate(row): mask |= x << j if mask == 0: return [i] g[mask] = i for a, i in g.items(): for b, j in g.items(): if (a & b) == 0: return sorted([i, j]) return []
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
Rust
use std::collections::HashMap; impl Solution { pub fn good_subsetof_binary_matrix(grid: Vec<Vec<i32>>) -> Vec<i32> { let mut g: HashMap<i32, i32> = HashMap::new(); for (i, row) in grid.iter().enumerate() { let mut mask = 0; for (j, &x) in row.iter().enumerate() { mask |= x << j; } if mask == 0 { return vec![i as i32]; } g.insert(mask, i as i32); } for (&a, &i) in g.iter() { for (&b, &j) in g.iter() { if (a & b) == 0 { return vec![i.min(j), i.max(j)]; } } } vec![] } }
2,732
Find a Good Subset of the Matrix
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> binary matrix <code>grid</code>.</p> <p>Let us call a <strong>non-empty</strong> subset of rows <strong>good</strong> if the sum of each column of the subset is at most half of the length of the subset.</p> <p>More formally, if the length of the chosen subset of rows is <code>k</code>, then the sum of each column should be at most <code>floor(k / 2)</code>.</p> <p>Return <em>an integer array that contains row indices of a good subset sorted in <strong>ascending</strong> order.</em></p> <p>If there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.</p> <p>A <strong>subset</strong> of rows of the matrix <code>grid</code> is any matrix that can be obtained by deleting some (possibly none or all) rows from <code>grid</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]] <strong>Output:</strong> [0,1] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> and 1<sup>st</sup> rows to create a good subset of rows. The length of the chosen subset is 2. - The sum of the 0<sup>th</sup>&nbsp;column is 0 + 0 = 0, which is at most half of the length of the subset. - The sum of the 1<sup>st</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 2<sup>nd</sup>&nbsp;column is 1 + 0 = 1, which is at most half of the length of the subset. - The sum of the 3<sup>rd</sup>&nbsp;column is 0 + 1 = 1, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[0]] <strong>Output:</strong> [0] <strong>Explanation:</strong> We can choose the 0<sup>th</sup> row to create a good subset of rows. The length of the chosen subset is 1. - The sum of the 0<sup>th</sup>&nbsp;column is 0, which is at most half of the length of the subset. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,1,1]] <strong>Output:</strong> [] <strong>Explanation:</strong> It is impossible to choose any subset of rows to create a good subset. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= n &lt;= 5</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Bit Manipulation; Array; Hash Table; Matrix
TypeScript
function goodSubsetofBinaryMatrix(grid: number[][]): number[] { const g: Map<number, number> = new Map(); const m = grid.length; const n = grid[0].length; for (let i = 0; i < m; ++i) { let mask = 0; for (let j = 0; j < n; ++j) { mask |= grid[i][j] << j; } if (!mask) { return [i]; } g.set(mask, i); } for (const [a, i] of g.entries()) { for (const [b, j] of g.entries()) { if ((a & b) === 0) { return [Math.min(i, j), Math.max(i, j)]; } } } return []; }
2,733
Neither Minimum nor Maximum
Easy
<p>Given an integer array <code>nums</code> containing <strong>distinct</strong> <strong>positive</strong> integers, find and return <strong>any</strong> number from the array that is neither the <strong>minimum</strong> nor the <strong>maximum</strong> value in the array, or <strong><code>-1</code></strong> if there is no such number.</p> <p>Return <em>the selected integer.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All values in <code>nums</code> are distinct</li> </ul>
Array; Sorting
C++
class Solution { public: int findNonMinOrMax(vector<int>& nums) { auto [mi, mx] = minmax_element(nums.begin(), nums.end()); for (int x : nums) { if (x != *mi && x != *mx) { return x; } } return -1; } };
2,733
Neither Minimum nor Maximum
Easy
<p>Given an integer array <code>nums</code> containing <strong>distinct</strong> <strong>positive</strong> integers, find and return <strong>any</strong> number from the array that is neither the <strong>minimum</strong> nor the <strong>maximum</strong> value in the array, or <strong><code>-1</code></strong> if there is no such number.</p> <p>Return <em>the selected integer.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All values in <code>nums</code> are distinct</li> </ul>
Array; Sorting
Go
func findNonMinOrMax(nums []int) int { mi, mx := slices.Min(nums), slices.Max(nums) for _, x := range nums { if x != mi && x != mx { return x } } return -1 }
2,733
Neither Minimum nor Maximum
Easy
<p>Given an integer array <code>nums</code> containing <strong>distinct</strong> <strong>positive</strong> integers, find and return <strong>any</strong> number from the array that is neither the <strong>minimum</strong> nor the <strong>maximum</strong> value in the array, or <strong><code>-1</code></strong> if there is no such number.</p> <p>Return <em>the selected integer.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All values in <code>nums</code> are distinct</li> </ul>
Array; Sorting
Java
class Solution { public int findNonMinOrMax(int[] nums) { int mi = 100, mx = 0; for (int x : nums) { mi = Math.min(mi, x); mx = Math.max(mx, x); } for (int x : nums) { if (x != mi && x != mx) { return x; } } return -1; } }
2,733
Neither Minimum nor Maximum
Easy
<p>Given an integer array <code>nums</code> containing <strong>distinct</strong> <strong>positive</strong> integers, find and return <strong>any</strong> number from the array that is neither the <strong>minimum</strong> nor the <strong>maximum</strong> value in the array, or <strong><code>-1</code></strong> if there is no such number.</p> <p>Return <em>the selected integer.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All values in <code>nums</code> are distinct</li> </ul>
Array; Sorting
Python
class Solution: def findNonMinOrMax(self, nums: List[int]) -> int: mi, mx = min(nums), max(nums) return next((x for x in nums if x != mi and x != mx), -1)
2,733
Neither Minimum nor Maximum
Easy
<p>Given an integer array <code>nums</code> containing <strong>distinct</strong> <strong>positive</strong> integers, find and return <strong>any</strong> number from the array that is neither the <strong>minimum</strong> nor the <strong>maximum</strong> value in the array, or <strong><code>-1</code></strong> if there is no such number.</p> <p>Return <em>the selected integer.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All values in <code>nums</code> are distinct</li> </ul>
Array; Sorting
Rust
impl Solution { pub fn find_non_min_or_max(nums: Vec<i32>) -> i32 { let mut mi = 100; let mut mx = 0; for &ele in nums.iter() { if ele < mi { mi = ele; } if ele > mx { mx = ele; } } for &ele in nums.iter() { if ele != mi && ele != mx { return ele; } } -1 } }
2,734
Lexicographically Smallest String After Substring Operation
Medium
<p>Given a string <code>s</code> consisting of lowercase English letters. Perform the following operation:</p> <ul> <li>Select any non-empty <span data-keyword="substring-nonempty">substring</span> then replace every letter of the substring with the preceding letter of the English alphabet. For example, &#39;b&#39; is converted to &#39;a&#39;, and &#39;a&#39; is converted to &#39;z&#39;.</li> </ul> <p>Return the <span data-keyword="lexicographically-smaller-string"><strong>lexicographically smallest</strong></span> string <strong>after performing the operation</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cbabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;baabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Perform the operation on the substring starting at index 0, and ending at index 1 inclusive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;az&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Perform the operation on the last letter.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;acbbc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abaab&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Perform the operation on the substring starting at index 1, and ending at index 4 inclusive.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;kddsbncd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Perform the operation on the entire string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of lowercase English letters</li> </ul>
Greedy; String
C++
class Solution { public: string smallestString(string s) { int n = s.size(); int i = 0; while (i < n && s[i] == 'a') { ++i; } if (i == n) { s[n - 1] = 'z'; return s; } int j = i; while (j < n && s[j] != 'a') { s[j] = s[j] - 1; ++j; } return s; } };