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
518
Coin Change II
Medium
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p> <p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p> <p>You may assume that you have an infinite number of each kind of coin.</p> <p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> amount = 5, coins = [1,2,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> amount = 3, coins = [2] <strong>Output:</strong> 0 <strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> amount = 10, coins = [10] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 300</code></li> <li><code>1 &lt;= coins[i] &lt;= 5000</code></li> <li>All the values of <code>coins</code> are <strong>unique</strong>.</li> <li><code>0 &lt;= amount &lt;= 5000</code></li> </ul>
Array; Dynamic Programming
Go
func change(amount int, coins []int) int { m, n := len(coins), amount f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } f[0][0] = 1 for i := 1; i <= m; i++ { for j := 0; j <= n; j++ { f[i][j] = f[i-1][j] if j >= coins[i-1] { f[i][j] += f[i][j-coins[i-1]] } } } return f[m][n] }
518
Coin Change II
Medium
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p> <p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p> <p>You may assume that you have an infinite number of each kind of coin.</p> <p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> amount = 5, coins = [1,2,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> amount = 3, coins = [2] <strong>Output:</strong> 0 <strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> amount = 10, coins = [10] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 300</code></li> <li><code>1 &lt;= coins[i] &lt;= 5000</code></li> <li>All the values of <code>coins</code> are <strong>unique</strong>.</li> <li><code>0 &lt;= amount &lt;= 5000</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int change(int amount, int[] coins) { int m = coins.length, n = amount; int[][] f = new int[m + 1][n + 1]; f[0][0] = 1; for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= coins[i - 1]) { f[i][j] += f[i][j - coins[i - 1]]; } } } return f[m][n]; } }
518
Coin Change II
Medium
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p> <p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p> <p>You may assume that you have an infinite number of each kind of coin.</p> <p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> amount = 5, coins = [1,2,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> amount = 3, coins = [2] <strong>Output:</strong> 0 <strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> amount = 10, coins = [10] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 300</code></li> <li><code>1 &lt;= coins[i] &lt;= 5000</code></li> <li>All the values of <code>coins</code> are <strong>unique</strong>.</li> <li><code>0 &lt;= amount &lt;= 5000</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def change(self, amount: int, coins: List[int]) -> int: m, n = len(coins), amount f = [[0] * (n + 1) for _ in range(m + 1)] f[0][0] = 1 for i, x in enumerate(coins, 1): for j in range(n + 1): f[i][j] = f[i - 1][j] if j >= x: f[i][j] += f[i][j - x] return f[m][n]
518
Coin Change II
Medium
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p> <p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p> <p>You may assume that you have an infinite number of each kind of coin.</p> <p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> amount = 5, coins = [1,2,5] <strong>Output:</strong> 4 <strong>Explanation:</strong> there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> amount = 3, coins = [2] <strong>Output:</strong> 0 <strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> amount = 10, coins = [10] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= coins.length &lt;= 300</code></li> <li><code>1 &lt;= coins[i] &lt;= 5000</code></li> <li>All the values of <code>coins</code> are <strong>unique</strong>.</li> <li><code>0 &lt;= amount &lt;= 5000</code></li> </ul>
Array; Dynamic Programming
TypeScript
function change(amount: number, coins: number[]): number { const [m, n] = [coins.length, amount]; const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); f[0][0] = 1; for (let i = 1; i <= m; ++i) { for (let j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= coins[i - 1]) { f[i][j] += f[i][j - coins[i - 1]]; } } } return f[m][n]; }
519
Random Flip Matrix
Medium
<p>There is an <code>m x n</code> binary grid <code>matrix</code> with all the values set <code>0</code> initially. Design an algorithm to randomly pick an index <code>(i, j)</code> where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>. All the indices <code>(i, j)</code> where <code>matrix[i][j] == 0</code> should be equally likely to be returned.</p> <p>Optimize your algorithm to minimize the number of calls made to the <strong>built-in</strong> random function of your language and optimize the time and space complexity.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int m, int n)</code> Initializes the object with the size of the binary matrix <code>m</code> and <code>n</code>.</li> <li><code>int[] flip()</code> Returns a random index <code>[i, j]</code> of the matrix where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>.</li> <li><code>void reset()</code> Resets all the values of the matrix to be <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;reset&quot;, &quot;flip&quot;] [[3, 1], [], [], [], [], []] <strong>Output</strong> [null, [1, 0], [2, 0], [0, 0], null, [2, 0]] <strong>Explanation</strong> Solution solution = new Solution(3, 1); solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0] solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned. solution.reset(); // All the values are reset to 0 and can be returned. solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li>There will be at least one free cell for each call to <code>flip</code>.</li> <li>At most <code>1000</code> calls will be made to <code>flip</code> and <code>reset</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
Java
class Solution { private int m; private int n; private int total; private Random rand = new Random(); private Map<Integer, Integer> mp = new HashMap<>(); public Solution(int m, int n) { this.m = m; this.n = n; this.total = m * n; } public int[] flip() { int x = rand.nextInt(total--); int idx = mp.getOrDefault(x, x); mp.put(x, mp.getOrDefault(total, total)); return new int[] {idx / n, idx % n}; } public void reset() { total = m * n; mp.clear(); } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(m, n); * int[] param_1 = obj.flip(); * obj.reset(); */
519
Random Flip Matrix
Medium
<p>There is an <code>m x n</code> binary grid <code>matrix</code> with all the values set <code>0</code> initially. Design an algorithm to randomly pick an index <code>(i, j)</code> where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>. All the indices <code>(i, j)</code> where <code>matrix[i][j] == 0</code> should be equally likely to be returned.</p> <p>Optimize your algorithm to minimize the number of calls made to the <strong>built-in</strong> random function of your language and optimize the time and space complexity.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int m, int n)</code> Initializes the object with the size of the binary matrix <code>m</code> and <code>n</code>.</li> <li><code>int[] flip()</code> Returns a random index <code>[i, j]</code> of the matrix where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>.</li> <li><code>void reset()</code> Resets all the values of the matrix to be <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;reset&quot;, &quot;flip&quot;] [[3, 1], [], [], [], [], []] <strong>Output</strong> [null, [1, 0], [2, 0], [0, 0], null, [2, 0]] <strong>Explanation</strong> Solution solution = new Solution(3, 1); solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0] solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned. solution.reset(); // All the values are reset to 0 and can be returned. solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li> <li>There will be at least one free cell for each call to <code>flip</code>.</li> <li>At most <code>1000</code> calls will be made to <code>flip</code> and <code>reset</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
Python
class Solution: def __init__(self, m: int, n: int): self.m = m self.n = n self.total = m * n self.mp = {} def flip(self) -> List[int]: self.total -= 1 x = random.randint(0, self.total) idx = self.mp.get(x, x) self.mp[x] = self.mp.get(self.total, self.total) return [idx // self.n, idx % self.n] def reset(self) -> None: self.total = self.m * self.n self.mp.clear() # Your Solution object will be instantiated and called as such: # obj = Solution(m, n) # param_1 = obj.flip() # obj.reset()
520
Detect Capital
Easy
<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p> <ul> <li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li> <li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li> <li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li> </ul> <p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> word = "USA" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> word = "FlaG" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists of lowercase and uppercase English letters.</li> </ul>
String
C++
class Solution { public: bool detectCapitalUse(string word) { int cnt = count_if(word.begin(), word.end(), [](char c) { return isupper(c); }); return cnt == 0 || cnt == word.length() || (cnt == 1 && isupper(word[0])); } };
520
Detect Capital
Easy
<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p> <ul> <li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li> <li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li> <li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li> </ul> <p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> word = "USA" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> word = "FlaG" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists of lowercase and uppercase English letters.</li> </ul>
String
Go
func detectCapitalUse(word string) bool { cnt := 0 for _, c := range word { if unicode.IsUpper(c) { cnt++ } } return cnt == 0 || cnt == len(word) || (cnt == 1 && unicode.IsUpper(rune(word[0]))) }
520
Detect Capital
Easy
<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p> <ul> <li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li> <li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li> <li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li> </ul> <p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> word = "USA" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> word = "FlaG" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists of lowercase and uppercase English letters.</li> </ul>
String
Java
class Solution { public boolean detectCapitalUse(String word) { int cnt = 0; for (char c : word.toCharArray()) { if (Character.isUpperCase(c)) { ++cnt; } } return cnt == 0 || cnt == word.length() || (cnt == 1 && Character.isUpperCase(word.charAt(0))); } }
520
Detect Capital
Easy
<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p> <ul> <li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li> <li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li> <li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li> </ul> <p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> word = "USA" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> word = "FlaG" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists of lowercase and uppercase English letters.</li> </ul>
String
Python
class Solution: def detectCapitalUse(self, word: str) -> bool: cnt = sum(c.isupper() for c in word) return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper())
520
Detect Capital
Easy
<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p> <ul> <li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li> <li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li> <li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li> </ul> <p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> word = "USA" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> word = "FlaG" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists of lowercase and uppercase English letters.</li> </ul>
String
TypeScript
function detectCapitalUse(word: string): boolean { const cnt = word.split('').reduce((acc, c) => acc + (c === c.toUpperCase() ? 1 : 0), 0); return cnt === 0 || cnt === word.length || (cnt === 1 && word[0] === word[0].toUpperCase()); }
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
C++
class Solution { public: int findLUSlength(string a, string b) { return a == b ? -1 : max(a.size(), b.size()); } };
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
Go
func findLUSlength(a string, b string) int { if a == b { return -1 } if len(a) > len(b) { return len(a) } return len(b) }
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
Java
class Solution { public int findLUSlength(String a, String b) { return a.equals(b) ? -1 : Math.max(a.length(), b.length()); } }
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
Python
class Solution: def findLUSlength(self, a: str, b: str) -> int: return -1 if a == b else max(len(a), len(b))
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
Rust
impl Solution { pub fn find_lu_slength(a: String, b: String) -> i32 { if a == b { return -1; } a.len().max(b.len()) as i32 } }
521
Longest Uncommon Subsequence I
Easy
<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p> <p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword="subsequence-string">subsequence</span> of exactly one of them</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;. Note that &quot;cdc&quot; is also a longest uncommon subsequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 100</code></li> <li><code>a</code> and <code>b</code> consist of lower-case English letters.</li> </ul>
String
TypeScript
function findLUSlength(a: string, b: string): number { return a === b ? -1 : Math.max(a.length, b.length); }
522
Longest Uncommon Subsequence II
Medium
<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p> <p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p> <p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p> <ul> <li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> strs = ["aba","cdc","eae"] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> strs = ["aaa","aaa","aa"] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= strs.length &lt;= 50</code></li> <li><code>1 &lt;= strs[i].length &lt;= 10</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; Two Pointers; String; Sorting
C++
class Solution { public: int findLUSlength(vector<string>& strs) { int ans = -1; int n = strs.size(); auto check = [&](const string& s, const string& t) { int m = s.size(), n = t.size(); int i = 0; for (int j = 0; i < m && j < n; ++j) { if (s[i] == t[j]) { ++i; } } return i == m; }; for (int i = 0, j; i < n; ++i) { int x = strs[i].size(); for (j = 0; j < n; ++j) { if (i != j && check(strs[i], strs[j])) { x = -1; break; } } ans = max(ans, x); } return ans; } };
522
Longest Uncommon Subsequence II
Medium
<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p> <p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p> <p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p> <ul> <li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> strs = ["aba","cdc","eae"] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> strs = ["aaa","aaa","aa"] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= strs.length &lt;= 50</code></li> <li><code>1 &lt;= strs[i].length &lt;= 10</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; Two Pointers; String; Sorting
Go
func findLUSlength(strs []string) int { ans := -1 check := func(s, t string) bool { m, n := len(s), len(t) i := 0 for j := 0; i < m && j < n; j++ { if s[i] == t[j] { i++ } } return i == m } for i, s := range strs { x := len(s) for j, t := range strs { if i != j && check(s, t) { x = -1 break } } ans = max(ans, x) } return ans }
522
Longest Uncommon Subsequence II
Medium
<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p> <p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p> <p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p> <ul> <li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> strs = ["aba","cdc","eae"] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> strs = ["aaa","aaa","aa"] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= strs.length &lt;= 50</code></li> <li><code>1 &lt;= strs[i].length &lt;= 10</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; Two Pointers; String; Sorting
Java
class Solution { public int findLUSlength(String[] strs) { int ans = -1; int n = strs.length; for (int i = 0, j; i < n; ++i) { int x = strs[i].length(); for (j = 0; j < n; ++j) { if (i != j && check(strs[i], strs[j])) { x = -1; break; } } ans = Math.max(ans, x); } return ans; } private boolean check(String s, String t) { int m = s.length(), n = t.length(); int i = 0; for (int j = 0; i < m && j < n; ++j) { if (s.charAt(i) == t.charAt(j)) { ++i; } } return i == m; } }
522
Longest Uncommon Subsequence II
Medium
<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p> <p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p> <p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p> <ul> <li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> strs = ["aba","cdc","eae"] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> strs = ["aaa","aaa","aa"] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= strs.length &lt;= 50</code></li> <li><code>1 &lt;= strs[i].length &lt;= 10</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; Two Pointers; String; Sorting
Python
class Solution: def findLUSlength(self, strs: List[str]) -> int: def check(s: str, t: str): i = j = 0 while i < len(s) and j < len(t): if s[i] == t[j]: i += 1 j += 1 return i == len(s) ans = -1 for i, s in enumerate(strs): for j, t in enumerate(strs): if i != j and check(s, t): break else: ans = max(ans, len(s)) return ans
522
Longest Uncommon Subsequence II
Medium
<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p> <p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p> <p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p> <ul> <li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> strs = ["aba","cdc","eae"] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> strs = ["aaa","aaa","aa"] <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= strs.length &lt;= 50</code></li> <li><code>1 &lt;= strs[i].length &lt;= 10</code></li> <li><code>strs[i]</code> consists of lowercase English letters.</li> </ul>
Array; Hash Table; Two Pointers; String; Sorting
TypeScript
function findLUSlength(strs: string[]): number { const n = strs.length; let ans = -1; const check = (s: string, t: string): boolean => { const [m, n] = [s.length, t.length]; let i = 0; for (let j = 0; i < m && j < n; ++j) { if (s[i] === t[j]) { ++i; } } return i === m; }; for (let i = 0; i < n; ++i) { let x = strs[i].length; for (let j = 0; j < n; ++j) { if (i !== j && check(strs[i], strs[j])) { x = -1; break; } } ans = Math.max(ans, x); } return ans; }
523
Continuous Subarray Sum
Medium
<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>good subarray</strong> is a subarray where:</p> <ul> <li>its length is <strong>at least two</strong>, and</li> <li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li> </ul> <p><strong>Note</strong> that:</p> <ul> <li>A <strong>subarray</strong> is a contiguous part of the array.</li> <li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [23,2,6,4,7], k = 13 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table; Math; Prefix Sum
C++
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { unordered_map<int, int> d{{0, -1}}; int s = 0; for (int i = 0; i < nums.size(); ++i) { s = (s + nums[i]) % k; if (!d.contains(s)) { d[s] = i; } else if (i - d[s] > 1) { return true; } } return false; } };
523
Continuous Subarray Sum
Medium
<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>good subarray</strong> is a subarray where:</p> <ul> <li>its length is <strong>at least two</strong>, and</li> <li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li> </ul> <p><strong>Note</strong> that:</p> <ul> <li>A <strong>subarray</strong> is a contiguous part of the array.</li> <li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [23,2,6,4,7], k = 13 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table; Math; Prefix Sum
Go
func checkSubarraySum(nums []int, k int) bool { d := map[int]int{0: -1} s := 0 for i, x := range nums { s = (s + x) % k if _, ok := d[s]; !ok { d[s] = i } else if i-d[s] > 1 { return true } } return false }
523
Continuous Subarray Sum
Medium
<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>good subarray</strong> is a subarray where:</p> <ul> <li>its length is <strong>at least two</strong>, and</li> <li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li> </ul> <p><strong>Note</strong> that:</p> <ul> <li>A <strong>subarray</strong> is a contiguous part of the array.</li> <li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [23,2,6,4,7], k = 13 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table; Math; Prefix Sum
Java
class Solution { public boolean checkSubarraySum(int[] nums, int k) { Map<Integer, Integer> d = new HashMap<>(); d.put(0, -1); int s = 0; for (int i = 0; i < nums.length; ++i) { s = (s + nums[i]) % k; if (!d.containsKey(s)) { d.put(s, i); } else if (i - d.get(s) > 1) { return true; } } return false; } }
523
Continuous Subarray Sum
Medium
<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>good subarray</strong> is a subarray where:</p> <ul> <li>its length is <strong>at least two</strong>, and</li> <li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li> </ul> <p><strong>Note</strong> that:</p> <ul> <li>A <strong>subarray</strong> is a contiguous part of the array.</li> <li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [23,2,6,4,7], k = 13 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table; Math; Prefix Sum
Python
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: d = {0: -1} s = 0 for i, x in enumerate(nums): s = (s + x) % k if s not in d: d[s] = i elif i - d[s] > 1: return True return False
523
Continuous Subarray Sum
Medium
<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>good subarray</strong> is a subarray where:</p> <ul> <li>its length is <strong>at least two</strong>, and</li> <li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li> </ul> <p><strong>Note</strong> that:</p> <ul> <li>A <strong>subarray</strong> is a contiguous part of the array.</li> <li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6 <strong>Output:</strong> true <strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [23,2,6,4,7], k = 13 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table; Math; Prefix Sum
TypeScript
function checkSubarraySum(nums: number[], k: number): boolean { const d: Record<number, number> = { 0: -1 }; let s = 0; for (let i = 0; i < nums.length; ++i) { s = (s + nums[i]) % k; if (!d.hasOwnProperty(s)) { d[s] = i; } else if (i - d[s] > 1) { return true; } } return false; }
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
C++
class Solution { public: string findLongestWord(string s, vector<string>& dictionary) { string ans = ""; auto check = [&](const string& s, const string& t) { int m = s.size(), n = t.size(); int i = 0; for (int j = 0; i < m && j < n; ++j) { if (s[i] == t[j]) { ++i; } } return i == m; }; for (auto& t : dictionary) { int a = ans.size(), b = t.size(); if (check(t, s) && (a < b || (a == b && ans > t))) { ans = t; } } return ans; } };
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
Go
func findLongestWord(s string, dictionary []string) string { ans := '' check := func(s, t string) bool { m, n := len(s), len(t) i := 0 for j := 0; i < m && j < n; j++ { if s[i] == t[j] { i++ } } return i == m } for _, t := range dictionary { a, b := len(ans), len(t) if check(t, s) && (a < b || (a == b && ans > t)) { ans = t } } return ans }
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
Java
class Solution { public String findLongestWord(String s, List<String> dictionary) { String ans = ""; for (String t : dictionary) { int a = ans.length(), b = t.length(); if (check(t, s) && (a < b || (a == b && t.compareTo(ans) < 0))) { ans = t; } } return ans; } private boolean check(String s, String t) { int m = s.length(), n = t.length(); int i = 0; for (int j = 0; i < m && j < n; ++j) { if (s.charAt(i) == t.charAt(j)) { ++i; } } return i == m; } }
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
Python
class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: def check(s: str, t: str) -> bool: m, n = len(s), len(t) i = j = 0 while i < m and j < n: if s[i] == t[j]: i += 1 j += 1 return i == m ans = "" for t in dictionary: if check(t, s) and (len(ans) < len(t) or (len(ans) == len(t) and ans > t)): ans = t return ans
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
Rust
impl Solution { pub fn find_longest_word(s: String, dictionary: Vec<String>) -> String { let mut ans = String::new(); for t in dictionary { let a = ans.len(); let b = t.len(); if Self::check(&t, &s) && (a < b || (a == b && t < ans)) { ans = t; } } ans } fn check(s: &str, t: &str) -> bool { let (m, n) = (s.len(), t.len()); let mut i = 0; let mut j = 0; let s: Vec<char> = s.chars().collect(); let t: Vec<char> = t.chars().collect(); while i < m && j < n { if s[i] == t[j] { i += 1; } j += 1; } i == m } }
524
Longest Word in Dictionary through Deleting
Medium
<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;] <strong>Output:</strong> &quot;apple&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] <strong>Output:</strong> &quot;a&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary.length &lt;= 1000</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li> <li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li> </ul>
Array; Two Pointers; String; Sorting
TypeScript
function findLongestWord(s: string, dictionary: string[]): string { const check = (s: string, t: string): boolean => { const [m, n] = [s.length, t.length]; let i = 0; for (let j = 0; i < m && j < n; ++j) { if (s[i] === t[j]) { ++i; } } return i === m; }; let ans: string = ''; for (const t of dictionary) { const [a, b] = [ans.length, t.length]; if (check(t, s) && (a < b || (a === b && ans > t))) { ans = t; } } return ans; }
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: int findMaxLength(vector<int>& nums) { unordered_map<int, int> d{{0, -1}}; int ans = 0, s = 0; for (int i = 0; i < nums.size(); ++i) { s += nums[i] ? 1 : -1; if (d.contains(s)) { ans = max(ans, i - d[s]); } else { d[s] = i; } } return ans; } };
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
Go
func findMaxLength(nums []int) int { d := map[int]int{0: -1} ans, s := 0, 0 for i, x := range nums { if x == 0 { x = -1 } s += x if j, ok := d[s]; ok { ans = max(ans, i-j) } else { d[s] = i } } return ans }
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public int findMaxLength(int[] nums) { Map<Integer, Integer> d = new HashMap<>(); d.put(0, -1); int ans = 0, s = 0; for (int i = 0; i < nums.length; ++i) { s += nums[i] == 1 ? 1 : -1; if (d.containsKey(s)) { ans = Math.max(ans, i - d.get(s)); } else { d.put(s, i); } } return ans; } }
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
JavaScript
/** * @param {number[]} nums * @return {number} */ var findMaxLength = function (nums) { const d = { 0: -1 }; let ans = 0; let s = 0; for (let i = 0; i < nums.length; ++i) { s += nums[i] ? 1 : -1; if (d.hasOwnProperty(s)) { ans = Math.max(ans, i - d[s]); } else { d[s] = i; } } return ans; };
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def findMaxLength(self, nums: List[int]) -> int: d = {0: -1} ans = s = 0 for i, x in enumerate(nums): s += 1 if x else -1 if s in d: ans = max(ans, i - d[s]) else: d[s] = i return ans
525
Contiguous Array
Medium
<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0] <strong>Output:</strong> 2 <strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0] <strong>Output:</strong> 6 <strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Hash Table; Prefix Sum
TypeScript
function findMaxLength(nums: number[]): number { const d: Record<number, number> = { 0: -1 }; let ans = 0; let s = 0; for (let i = 0; i < nums.length; ++i) { s += nums[i] ? 1 : -1; if (d.hasOwnProperty(s)) { ans = Math.max(ans, i - d[s]); } else { d[s] = i; } } return ans; }
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
C++
class Solution { public: int n; int ans; vector<bool> vis; unordered_map<int, vector<int>> match; int countArrangement(int n) { this->n = n; this->ans = 0; vis.resize(n + 1); for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) if (i % j == 0 || j % i == 0) match[i].push_back(j); dfs(1); return ans; } void dfs(int i) { if (i == n + 1) { ++ans; return; } for (int j : match[i]) { if (!vis[j]) { vis[j] = true; dfs(i + 1); vis[j] = false; } } } };
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
Go
func countArrangement(n int) int { ans := 0 match := make(map[int][]int) for i := 1; i <= n; i++ { for j := 1; j <= n; j++ { if i%j == 0 || j%i == 0 { match[i] = append(match[i], j) } } } vis := make([]bool, n+1) var dfs func(i int) dfs = func(i int) { if i == n+1 { ans++ return } for _, j := range match[i] { if !vis[j] { vis[j] = true dfs(i + 1) vis[j] = false } } } dfs(1) return ans }
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
Java
class Solution { private int n; private int ans; private boolean[] vis; private Map<Integer, List<Integer>> match; public int countArrangement(int n) { this.n = n; ans = 0; vis = new boolean[n + 1]; match = new HashMap<>(); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (i % j == 0 || j % i == 0) { match.computeIfAbsent(i, k -> new ArrayList<>()).add(j); } } } dfs(1); return ans; } private void dfs(int i) { if (i == n + 1) { ++ans; return; } if (!match.containsKey(i)) { return; } for (int j : match.get(i)) { if (!vis[j]) { vis[j] = true; dfs(i + 1); vis[j] = false; } } } }
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
Python
class Solution: def countArrangement(self, n: int) -> int: def dfs(i): nonlocal ans, n if i == n + 1: ans += 1 return for j in match[i]: if not vis[j]: vis[j] = True dfs(i + 1) vis[j] = False ans = 0 vis = [False] * (n + 1) match = defaultdict(list) for i in range(1, n + 1): for j in range(1, n + 1): if j % i == 0 or i % j == 0: match[i].append(j) dfs(1) return ans
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
Rust
impl Solution { fn dfs(i: usize, n: usize, mat: &Vec<Vec<usize>>, vis: &mut Vec<bool>, res: &mut i32) { if i == n + 1 { *res += 1; return; } for &j in mat[i].iter() { if !vis[j] { vis[j] = true; Self::dfs(i + 1, n, mat, vis, res); vis[j] = false; } } } pub fn count_arrangement(n: i32) -> i32 { let n = n as usize; let mut vis = vec![false; n + 1]; let mut mat = vec![Vec::new(); n + 1]; for i in 1..=n { for j in 1..=n { if i % j == 0 || j % i == 0 { mat[i].push(j); } } } let mut res = 0; Self::dfs(1, n, &mat, &mut vis, &mut res); res } }
526
Beautiful Arrangement
Medium
<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p> <ul> <li><code>perm[i]</code> is divisible by <code>i</code>.</li> <li><code>i</code> is divisible by <code>perm[i]</code>.</li> </ul> <p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 2 <b>Explanation:</b> The first beautiful arrangement is [1,2]: - perm[1] = 1 is divisible by i = 1 - perm[2] = 2 is divisible by i = 2 The second beautiful arrangement is [2,1]: - perm[1] = 2 is divisible by i = 1 - i = 2 is divisible by perm[2] = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 15</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
TypeScript
function countArrangement(n: number): number { const vis = new Array(n + 1).fill(0); const match = Array.from({ length: n + 1 }, () => []); for (let i = 1; i <= n; i++) { for (let j = 1; j <= n; j++) { if (i % j === 0 || j % i === 0) { match[i].push(j); } } } let res = 0; const dfs = (i: number, n: number) => { if (i === n + 1) { res++; return; } for (const j of match[i]) { if (!vis[j]) { vis[j] = true; dfs(i + 1, n); vis[j] = false; } } }; dfs(1, n); return res; }
527
Word Abbreviation
Hard
<p>Given an array of <strong>distinct</strong> strings <code>words</code>, return <em>the minimal possible <strong>abbreviations</strong> for every word</em>.</p> <p>The following are the rules for a string abbreviation:</p> <ol> <li>The <strong>initial</strong> abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.</li> <li>If more than one word shares the <strong>same</strong> abbreviation, then perform the following operation: <ul> <li><strong>Increase</strong> the prefix (characters in the first part) of each of their abbreviations by <code>1</code>. <ul> <li>For example, say you start with the words <code>[&quot;abcdef&quot;,&quot;abndef&quot;]</code> both initially abbreviated as <code>&quot;a4f&quot;</code>. Then, a sequence of operations would be <code>[&quot;a4f&quot;,&quot;a4f&quot;]</code> -&gt; <code>[&quot;ab3f&quot;,&quot;ab3f&quot;]</code> -&gt; <code>[&quot;abc2f&quot;,&quot;abn2f&quot;]</code>.</li> </ul> </li> <li>This operation is repeated until every abbreviation is <strong>unique</strong>.</li> </ul> </li> <li>At the end, if an abbreviation did not make a word shorter, then keep it as the original word.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] <strong>Output:</strong> ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> words = ["aa","aaa"] <strong>Output:</strong> ["aa","aaa"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 400</code></li> <li><code>2 &lt;= words[i].length &lt;= 400</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are <strong>unique</strong>.</li> </ul>
Greedy; Trie; Array; String; Sorting
C++
class Trie { public: Trie() : cnt(0) { fill(children.begin(), children.end(), nullptr); } void insert(const string& w) { Trie* node = this; for (char c : w) { int idx = c - 'a'; if (node->children[idx] == nullptr) { node->children[idx] = new Trie(); } node = node->children[idx]; ++node->cnt; } } int search(const string& w) { Trie* node = this; int ans = 0; for (char c : w) { ++ans; int idx = c - 'a'; node = node->children[idx]; if (node->cnt == 1) { return ans; } } return w.size(); } private: array<Trie*, 26> children; int cnt; }; class Solution { public: vector<string> wordsAbbreviation(vector<string>& words) { map<pair<int, int>, Trie*> tries; for (const auto& w : words) { pair<int, int> key = {static_cast<int>(w.size()), w.back() - 'a'}; if (tries.find(key) == tries.end()) { tries[key] = new Trie(); } tries[key]->insert(w); } vector<string> ans; for (const auto& w : words) { int m = w.size(); pair<int, int> key = {m, w.back() - 'a'}; int cnt = tries[key]->search(w); ans.push_back((cnt + 2 >= m) ? w : w.substr(0, cnt) + to_string(m - cnt - 1) + w.back()); } return ans; } };
527
Word Abbreviation
Hard
<p>Given an array of <strong>distinct</strong> strings <code>words</code>, return <em>the minimal possible <strong>abbreviations</strong> for every word</em>.</p> <p>The following are the rules for a string abbreviation:</p> <ol> <li>The <strong>initial</strong> abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.</li> <li>If more than one word shares the <strong>same</strong> abbreviation, then perform the following operation: <ul> <li><strong>Increase</strong> the prefix (characters in the first part) of each of their abbreviations by <code>1</code>. <ul> <li>For example, say you start with the words <code>[&quot;abcdef&quot;,&quot;abndef&quot;]</code> both initially abbreviated as <code>&quot;a4f&quot;</code>. Then, a sequence of operations would be <code>[&quot;a4f&quot;,&quot;a4f&quot;]</code> -&gt; <code>[&quot;ab3f&quot;,&quot;ab3f&quot;]</code> -&gt; <code>[&quot;abc2f&quot;,&quot;abn2f&quot;]</code>.</li> </ul> </li> <li>This operation is repeated until every abbreviation is <strong>unique</strong>.</li> </ul> </li> <li>At the end, if an abbreviation did not make a word shorter, then keep it as the original word.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] <strong>Output:</strong> ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> words = ["aa","aaa"] <strong>Output:</strong> ["aa","aaa"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 400</code></li> <li><code>2 &lt;= words[i].length &lt;= 400</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are <strong>unique</strong>.</li> </ul>
Greedy; Trie; Array; String; Sorting
Go
type Trie struct { children [26]*Trie cnt int } func (t *Trie) insert(w string) { node := t for _, c := range w { idx := c - 'a' if node.children[idx] == nil { node.children[idx] = &Trie{} } node = node.children[idx] node.cnt++ } } func (t *Trie) search(w string) int { node := t ans := 0 for _, c := range w { ans++ idx := c - 'a' node = node.children[idx] if node.cnt == 1 { return ans } } return len(w) } func wordsAbbreviation(words []string) (ans []string) { tries := make(map[[2]int]*Trie) for _, w := range words { key := [2]int{len(w), int(w[len(w)-1] - 'a')} _, exists := tries[key] if !exists { tries[key] = &Trie{} } tries[key].insert(w) } for _, w := range words { m := len(w) key := [2]int{m, int(w[m-1] - 'a')} cnt := tries[key].search(w) if cnt+2 >= m { ans = append(ans, w) } else { abbr := w[:cnt] + fmt.Sprintf("%d", m-cnt-1) + w[m-1:] ans = append(ans, abbr) } } return }
527
Word Abbreviation
Hard
<p>Given an array of <strong>distinct</strong> strings <code>words</code>, return <em>the minimal possible <strong>abbreviations</strong> for every word</em>.</p> <p>The following are the rules for a string abbreviation:</p> <ol> <li>The <strong>initial</strong> abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.</li> <li>If more than one word shares the <strong>same</strong> abbreviation, then perform the following operation: <ul> <li><strong>Increase</strong> the prefix (characters in the first part) of each of their abbreviations by <code>1</code>. <ul> <li>For example, say you start with the words <code>[&quot;abcdef&quot;,&quot;abndef&quot;]</code> both initially abbreviated as <code>&quot;a4f&quot;</code>. Then, a sequence of operations would be <code>[&quot;a4f&quot;,&quot;a4f&quot;]</code> -&gt; <code>[&quot;ab3f&quot;,&quot;ab3f&quot;]</code> -&gt; <code>[&quot;abc2f&quot;,&quot;abn2f&quot;]</code>.</li> </ul> </li> <li>This operation is repeated until every abbreviation is <strong>unique</strong>.</li> </ul> </li> <li>At the end, if an abbreviation did not make a word shorter, then keep it as the original word.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] <strong>Output:</strong> ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> words = ["aa","aaa"] <strong>Output:</strong> ["aa","aaa"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 400</code></li> <li><code>2 &lt;= words[i].length &lt;= 400</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are <strong>unique</strong>.</li> </ul>
Greedy; Trie; Array; String; Sorting
Java
class Trie { private final Trie[] children = new Trie[26]; private int cnt; public void insert(String w) { Trie node = this; for (char c : w.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; ++node.cnt; } } public int search(String w) { Trie node = this; int ans = 0; for (char c : w.toCharArray()) { ++ans; int idx = c - 'a'; node = node.children[idx]; if (node.cnt == 1) { return ans; } } return w.length(); } } class Solution { public List<String> wordsAbbreviation(List<String> words) { Map<List<Integer>, Trie> tries = new HashMap<>(); for (var w : words) { var key = List.of(w.length(), w.charAt(w.length() - 1) - 'a'); tries.putIfAbsent(key, new Trie()); tries.get(key).insert(w); } List<String> ans = new ArrayList<>(); for (var w : words) { int m = w.length(); var key = List.of(m, w.charAt(m - 1) - 'a'); int cnt = tries.get(key).search(w); ans.add(cnt + 2 >= m ? w : w.substring(0, cnt) + (m - cnt - 1) + w.substring(m - 1)); } return ans; } }
527
Word Abbreviation
Hard
<p>Given an array of <strong>distinct</strong> strings <code>words</code>, return <em>the minimal possible <strong>abbreviations</strong> for every word</em>.</p> <p>The following are the rules for a string abbreviation:</p> <ol> <li>The <strong>initial</strong> abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.</li> <li>If more than one word shares the <strong>same</strong> abbreviation, then perform the following operation: <ul> <li><strong>Increase</strong> the prefix (characters in the first part) of each of their abbreviations by <code>1</code>. <ul> <li>For example, say you start with the words <code>[&quot;abcdef&quot;,&quot;abndef&quot;]</code> both initially abbreviated as <code>&quot;a4f&quot;</code>. Then, a sequence of operations would be <code>[&quot;a4f&quot;,&quot;a4f&quot;]</code> -&gt; <code>[&quot;ab3f&quot;,&quot;ab3f&quot;]</code> -&gt; <code>[&quot;abc2f&quot;,&quot;abn2f&quot;]</code>.</li> </ul> </li> <li>This operation is repeated until every abbreviation is <strong>unique</strong>.</li> </ul> </li> <li>At the end, if an abbreviation did not make a word shorter, then keep it as the original word.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] <strong>Output:</strong> ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> words = ["aa","aaa"] <strong>Output:</strong> ["aa","aaa"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 400</code></li> <li><code>2 &lt;= words[i].length &lt;= 400</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are <strong>unique</strong>.</li> </ul>
Greedy; Trie; Array; String; Sorting
Python
class Trie: __slots__ = ["children", "cnt"] def __init__(self): self.children = [None] * 26 self.cnt = 0 def insert(self, w: str): node = self for c in w: idx = ord(c) - ord("a") if not node.children[idx]: node.children[idx] = Trie() node = node.children[idx] node.cnt += 1 def search(self, w: str) -> int: node = self cnt = 0 for c in w: cnt += 1 idx = ord(c) - ord("a") node = node.children[idx] if node.cnt == 1: return cnt return len(w) class Solution: def wordsAbbreviation(self, words: List[str]) -> List[str]: tries = {} for w in words: m = len(w) if (m, w[-1]) not in tries: tries[(m, w[-1])] = Trie() tries[(m, w[-1])].insert(w) ans = [] for w in words: cnt = tries[(len(w), w[-1])].search(w) ans.append( w if cnt + 2 >= len(w) else w[:cnt] + str(len(w) - cnt - 1) + w[-1] ) return ans
527
Word Abbreviation
Hard
<p>Given an array of <strong>distinct</strong> strings <code>words</code>, return <em>the minimal possible <strong>abbreviations</strong> for every word</em>.</p> <p>The following are the rules for a string abbreviation:</p> <ol> <li>The <strong>initial</strong> abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.</li> <li>If more than one word shares the <strong>same</strong> abbreviation, then perform the following operation: <ul> <li><strong>Increase</strong> the prefix (characters in the first part) of each of their abbreviations by <code>1</code>. <ul> <li>For example, say you start with the words <code>[&quot;abcdef&quot;,&quot;abndef&quot;]</code> both initially abbreviated as <code>&quot;a4f&quot;</code>. Then, a sequence of operations would be <code>[&quot;a4f&quot;,&quot;a4f&quot;]</code> -&gt; <code>[&quot;ab3f&quot;,&quot;ab3f&quot;]</code> -&gt; <code>[&quot;abc2f&quot;,&quot;abn2f&quot;]</code>.</li> </ul> </li> <li>This operation is repeated until every abbreviation is <strong>unique</strong>.</li> </ul> </li> <li>At the end, if an abbreviation did not make a word shorter, then keep it as the original word.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> words = ["like","god","internal","me","internet","interval","intension","face","intrusion"] <strong>Output:</strong> ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> words = ["aa","aaa"] <strong>Output:</strong> ["aa","aaa"] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 400</code></li> <li><code>2 &lt;= words[i].length &lt;= 400</code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>All the strings of <code>words</code> are <strong>unique</strong>.</li> </ul>
Greedy; Trie; Array; String; Sorting
TypeScript
class Trie { private children: Trie[] = Array(26); private cnt: number = 0; insert(w: string): void { let node: Trie = this; for (const c of w) { const idx: number = c.charCodeAt(0) - 'a'.charCodeAt(0); if (!node.children[idx]) { node.children[idx] = new Trie(); } node = node.children[idx]; node.cnt++; } } search(w: string): number { let node: Trie = this; let ans: number = 0; for (const c of w) { ans++; const idx: number = c.charCodeAt(0) - 'a'.charCodeAt(0); node = node.children[idx]; if (node.cnt === 1) { return ans; } } return w.length; } } function wordsAbbreviation(words: string[]): string[] { const tries: Map<string, Trie> = new Map(); for (const w of words) { const key: string = `${w.length}-${w.charCodeAt(w.length - 1) - 'a'.charCodeAt(0)}`; if (!tries.get(key)) { tries.set(key, new Trie()); } tries.get(key)!.insert(w); } const ans: string[] = []; for (const w of words) { const m: number = w.length; const key: string = `${m}-${w.charCodeAt(m - 1) - 'a'.charCodeAt(0)}`; const cnt: number = tries.get(key)!.search(w); ans.push(cnt + 2 >= m ? w : w.substring(0, cnt) + (m - cnt - 1) + w.substring(m - 1)); } return ans; }
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
C++
class Solution { public: vector<int> s; Solution(vector<int>& w) { int n = w.size(); s.resize(n + 1); for (int i = 0; i < n; ++i) s[i + 1] = s[i] + w[i]; } int pickIndex() { int n = s.size(); int x = 1 + rand() % s[n - 1]; int left = 1, right = n - 1; while (left < right) { int mid = left + right >> 1; if (s[mid] >= x) right = mid; else left = mid + 1; } return left - 1; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(w); * int param_1 = obj->pickIndex(); */
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
Go
type Solution struct { s []int } func Constructor(w []int) Solution { n := len(w) s := make([]int, n+1) for i := 0; i < n; i++ { s[i+1] = s[i] + w[i] } return Solution{s} } func (this *Solution) PickIndex() int { n := len(this.s) x := 1 + rand.Intn(this.s[n-1]) left, right := 1, n-1 for left < right { mid := (left + right) >> 1 if this.s[mid] >= x { right = mid } else { left = mid + 1 } } return left - 1 } /** * Your Solution object will be instantiated and called as such: * obj := Constructor(w); * param_1 := obj.PickIndex(); */
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
Java
class Solution { private int[] s; private Random random = new Random(); public Solution(int[] w) { int n = w.length; s = new int[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + w[i]; } } public int pickIndex() { int x = 1 + random.nextInt(s[s.length - 1]); int left = 1, right = s.length - 1; while (left < right) { int mid = (left + right) >> 1; if (s[mid] >= x) { right = mid; } else { left = mid + 1; } } return left - 1; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(w); * int param_1 = obj.pickIndex(); */
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
JavaScript
/** * @param {number[]} w */ var Solution = function (w) { const n = w.length; this.s = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { this.s[i + 1] = this.s[i] + w[i]; } }; /** * @return {number} */ Solution.prototype.pickIndex = function () { const n = this.s.length; const x = 1 + Math.floor(Math.random() * this.s[n - 1]); let left = 1, right = n - 1; while (left < right) { const mid = (left + right) >> 1; if (this.s[mid] >= x) { right = mid; } else { left = mid + 1; } } return left - 1; }; /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(w) * var param_1 = obj.pickIndex() */
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
Python
class Solution: def __init__(self, w: List[int]): self.s = [0] for c in w: self.s.append(self.s[-1] + c) def pickIndex(self) -> int: x = random.randint(1, self.s[-1]) left, right = 1, len(self.s) - 1 while left < right: mid = (left + right) >> 1 if self.s[mid] >= x: right = mid else: left = mid + 1 return left - 1 # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex()
528
Random Pick with Weight
Medium
<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p> <p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p> <ul> <li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;] [[[1]],[]] <strong>Output</strong> [null,0] <strong>Explanation</strong> Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;] [[[1,3]],[],[],[],[],[]] <strong>Output</strong> [null,1,1,1,1,0] <strong>Explanation</strong> Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li> <li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li> </ul>
Array; Math; Binary Search; Prefix Sum; Randomized
Rust
use rand::{thread_rng, Rng}; struct Solution { sum: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl Solution { fn new(w: Vec<i32>) -> Self { let n = w.len(); let mut sum = vec![0; n + 1]; for i in 1..=n { sum[i] = sum[i - 1] + w[i - 1]; } Self { sum } } fn pick_index(&self) -> i32 { let x = thread_rng().gen_range(1, self.sum.last().unwrap() + 1); let (mut left, mut right) = (1, self.sum.len() - 1); while left < right { let mid = (left + right) >> 1; if self.sum[mid] < x { left = mid + 1; } else { right = mid; } } (left - 1) as i32 } }
529
Minesweeper
Medium
<p>Let&#39;s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p> <p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p> <ul> <li><code>&#39;M&#39;</code> represents an unrevealed mine,</li> <li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li> <li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li> <li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li> <li><code>&#39;X&#39;</code> represents a revealed mine.</li> </ul> <p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p> <p>Return <em>the board after revealing this position according to the following rules</em>:</p> <ol> <li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li> <li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li> <li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li> <li>Return the board when no more squares will be revealed.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled.jpeg" style="width: 500px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled-2.jpeg" style="width: 489px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li> <li><code>click.length == 2</code></li> <li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li> <li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li> <li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
C++
class Solution { public: vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) { int m = board.size(), n = board[0].size(); int i = click[0], j = click[1]; function<void(int, int)> dfs = [&](int i, int j) { int cnt = 0; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { ++cnt; } } } if (cnt) { board[i][j] = cnt + '0'; } else { board[i][j] = 'B'; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { dfs(x, y); } } } } }; if (board[i][j] == 'M') { board[i][j] = 'X'; } else { dfs(i, j); } return board; } };
529
Minesweeper
Medium
<p>Let&#39;s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p> <p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p> <ul> <li><code>&#39;M&#39;</code> represents an unrevealed mine,</li> <li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li> <li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li> <li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li> <li><code>&#39;X&#39;</code> represents a revealed mine.</li> </ul> <p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p> <p>Return <em>the board after revealing this position according to the following rules</em>:</p> <ol> <li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li> <li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li> <li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li> <li>Return the board when no more squares will be revealed.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled.jpeg" style="width: 500px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled-2.jpeg" style="width: 489px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li> <li><code>click.length == 2</code></li> <li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li> <li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li> <li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Go
func updateBoard(board [][]byte, click []int) [][]byte { m, n := len(board), len(board[0]) i, j := click[0], click[1] var dfs func(i, j int) dfs = func(i, j int) { cnt := 0 for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M' { cnt++ } } } if cnt > 0 { board[i][j] = byte(cnt + '0') return } board[i][j] = 'B' for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E' { dfs(x, y) } } } } if board[i][j] == 'M' { board[i][j] = 'X' } else { dfs(i, j) } return board }
529
Minesweeper
Medium
<p>Let&#39;s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p> <p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p> <ul> <li><code>&#39;M&#39;</code> represents an unrevealed mine,</li> <li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li> <li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li> <li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li> <li><code>&#39;X&#39;</code> represents a revealed mine.</li> </ul> <p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p> <p>Return <em>the board after revealing this position according to the following rules</em>:</p> <ol> <li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li> <li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li> <li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li> <li>Return the board when no more squares will be revealed.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled.jpeg" style="width: 500px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled-2.jpeg" style="width: 489px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li> <li><code>click.length == 2</code></li> <li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li> <li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li> <li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Java
class Solution { private char[][] board; private int m; private int n; public char[][] updateBoard(char[][] board, int[] click) { m = board.length; n = board[0].length; this.board = board; int i = click[0], j = click[1]; if (board[i][j] == 'M') { board[i][j] = 'X'; } else { dfs(i, j); } return board; } private void dfs(int i, int j) { int cnt = 0; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') { ++cnt; } } } if (cnt > 0) { board[i][j] = (char) (cnt + '0'); } else { board[i][j] = 'B'; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') { dfs(x, y); } } } } } }
529
Minesweeper
Medium
<p>Let&#39;s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p> <p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p> <ul> <li><code>&#39;M&#39;</code> represents an unrevealed mine,</li> <li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li> <li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li> <li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li> <li><code>&#39;X&#39;</code> represents a revealed mine.</li> </ul> <p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p> <p>Return <em>the board after revealing this position according to the following rules</em>:</p> <ol> <li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li> <li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li> <li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li> <li>Return the board when no more squares will be revealed.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled.jpeg" style="width: 500px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled-2.jpeg" style="width: 489px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li> <li><code>click.length == 2</code></li> <li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li> <li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li> <li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
Python
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: def dfs(i: int, j: int): cnt = 0 for x in range(i - 1, i + 2): for y in range(j - 1, j + 2): if 0 <= x < m and 0 <= y < n and board[x][y] == "M": cnt += 1 if cnt: board[i][j] = str(cnt) else: board[i][j] = "B" for x in range(i - 1, i + 2): for y in range(j - 1, j + 2): if 0 <= x < m and 0 <= y < n and board[x][y] == "E": dfs(x, y) m, n = len(board), len(board[0]) i, j = click if board[i][j] == "M": board[i][j] = "X" else: dfs(i, j) return board
529
Minesweeper
Medium
<p>Let&#39;s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p> <p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p> <ul> <li><code>&#39;M&#39;</code> represents an unrevealed mine,</li> <li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li> <li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li> <li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li> <li><code>&#39;X&#39;</code> represents a revealed mine.</li> </ul> <p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p> <p>Return <em>the board after revealing this position according to the following rules</em>:</p> <ol> <li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li> <li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li> <li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li> <li>Return the board when no more squares will be revealed.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled.jpeg" style="width: 500px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p><strong class="example">Example 2:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0529.Minesweeper/images/untitled-2.jpeg" style="width: 489px; max-width: 400px; height: 269px;" /> <pre> <strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2] <strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == board.length</code></li> <li><code>n == board[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li> <li><code>click.length == 2</code></li> <li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li> <li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li> <li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Matrix
TypeScript
function updateBoard(board: string[][], click: number[]): string[][] { const m = board.length; const n = board[0].length; const [i, j] = click; const dfs = (i: number, j: number) => { let cnt = 0; for (let x = i - 1; x <= i + 1; ++x) { for (let y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] === 'M') { ++cnt; } } } if (cnt > 0) { board[i][j] = cnt.toString(); return; } board[i][j] = 'B'; for (let x = i - 1; x <= i + 1; ++x) { for (let y = j - 1; y <= j + 1; ++y) { if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] === 'E') { dfs(x, y); } } } }; if (board[i][j] === 'M') { board[i][j] = 'X'; } else { dfs(i, j); } return board; }
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int getMinimumDifference(TreeNode* root) { const int inf = 1 << 30; int ans = inf, pre = -inf; auto dfs = [&](this auto&& dfs, TreeNode* root) -> void { if (!root) { return; } dfs(root->left); ans = min(ans, root->val - pre); pre = root->val; dfs(root->right); }; dfs(root); return ans; } };
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func getMinimumDifference(root *TreeNode) int { const inf int = 1 << 30 ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) ans = min(ans, root.Val-pre) pre = root.Val dfs(root.Right) } dfs(root) return ans }
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private final int inf = 1 << 30; private int ans = inf; private int pre = -inf; public int getMinimumDifference(TreeNode root) { dfs(root); return ans; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); } }
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var getMinimumDifference = function (root) { let [ans, pre] = [Infinity, -Infinity]; const dfs = root => { if (!root) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); }; dfs(root); return ans; };
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getMinimumDifference(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) nonlocal pre, ans ans = min(ans, root.val - pre) pre = root.val dfs(root.right) pre = -inf ans = inf dfs(root) return ans
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn get_minimum_difference(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { const inf: i32 = 1 << 30; let mut ans = inf; let mut pre = -inf; fn dfs(node: Option<Rc<RefCell<TreeNode>>>, ans: &mut i32, pre: &mut i32) { if let Some(n) = node { let n = n.borrow(); dfs(n.left.clone(), ans, pre); *ans = (*ans).min(n.val - *pre); *pre = n.val; dfs(n.right.clone(), ans, pre); } } dfs(root, &mut ans, &mut pre); ans } }
530
Minimum Absolute Difference in BST
Easy
<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</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/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst1.jpg" style="width: 292px; height: 301px;" /> <pre> <strong>Input:</strong> root = [4,2,6,1,3] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/images/bst2.jpg" style="width: 282px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,0,48,null,null,12,49] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 783: <a href="https://leetcode.com/problems/minimum-distance-between-bst-nodes/" target="_blank">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>
Tree; Depth-First Search; Breadth-First Search; Binary Search Tree; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function getMinimumDifference(root: TreeNode | null): number { let [ans, pre] = [Infinity, -Infinity]; const dfs = (root: TreeNode | null) => { if (!root) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); }; dfs(root); return ans; }
531
Lonely Pixel I
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position where the same row and same column don&#39;t have <strong>any other</strong> black pixels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;W&quot;,&quot;W&quot;]] <strong>Output:</strong> 3 <strong>Explanation:</strong> All the three &#39;B&#39;s are black lonely pixels. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel2.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
C++
class Solution { public: int findLonelyPixel(vector<vector<char>>& picture) { int m = picture.size(), n = picture[0].size(); vector<int> rows(m); vector<int> cols(n); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { ++ans; } } } return ans; } };
531
Lonely Pixel I
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position where the same row and same column don&#39;t have <strong>any other</strong> black pixels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;W&quot;,&quot;W&quot;]] <strong>Output:</strong> 3 <strong>Explanation:</strong> All the three &#39;B&#39;s are black lonely pixels. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel2.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Go
func findLonelyPixel(picture [][]byte) (ans int) { rows := make([]int, len(picture)) cols := make([]int, len(picture[0])) for i, row := range picture { for j, x := range row { if x == 'B' { rows[i]++ cols[j]++ } } } for i, row := range picture { for j, x := range row { if x == 'B' && rows[i] == 1 && cols[j] == 1 { ans++ } } } return }
531
Lonely Pixel I
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position where the same row and same column don&#39;t have <strong>any other</strong> black pixels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;W&quot;,&quot;W&quot;]] <strong>Output:</strong> 3 <strong>Explanation:</strong> All the three &#39;B&#39;s are black lonely pixels. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel2.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Java
class Solution { public int findLonelyPixel(char[][] picture) { int m = picture.length, n = picture[0].length; int[] rows = new int[m]; int[] cols = new int[n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { ++ans; } } } return ans; } }
531
Lonely Pixel I
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position where the same row and same column don&#39;t have <strong>any other</strong> black pixels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;W&quot;,&quot;W&quot;]] <strong>Output:</strong> 3 <strong>Explanation:</strong> All the three &#39;B&#39;s are black lonely pixels. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel2.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Python
class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: rows = [0] * len(picture) cols = [0] * len(picture[0]) for i, row in enumerate(picture): for j, x in enumerate(row): if x == "B": rows[i] += 1 cols[j] += 1 ans = 0 for i, row in enumerate(picture): for j, x in enumerate(row): if x == "B" and rows[i] == 1 and cols[j] == 1: ans += 1 return ans
531
Lonely Pixel I
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position where the same row and same column don&#39;t have <strong>any other</strong> black pixels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel1.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;W&quot;,&quot;W&quot;]] <strong>Output:</strong> 3 <strong>Explanation:</strong> All the three &#39;B&#39;s are black lonely pixels. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0531.Lonely%20Pixel%20I/images/pixel2.jpg" style="width: 242px; height: 242px;" /> <pre> <strong>Input:</strong> picture = [[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
TypeScript
function findLonelyPixel(picture: string[][]): number { const m = picture.length; const n = picture[0].length; const rows: number[] = Array(m).fill(0); const cols: number[] = Array(n).fill(0); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (picture[i][j] === 'B') { ++rows[i]; ++cols[j]; } } } let ans = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (picture[i][j] === 'B' && rows[i] === 1 && cols[j] === 1) { ++ans; } } } return ans; }
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
C++
class Solution { public: int findPairs(vector<int>& nums, int k) { unordered_set<int> ans, vis; for (int x : nums) { if (vis.count(x - k)) { ans.insert(x - k); } if (vis.count(x + k)) { ans.insert(x); } vis.insert(x); } return ans.size(); } };
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Go
func findPairs(nums []int, k int) int { ans := make(map[int]struct{}) vis := make(map[int]struct{}) for _, x := range nums { if _, ok := vis[x-k]; ok { ans[x-k] = struct{}{} } if _, ok := vis[x+k]; ok { ans[x] = struct{}{} } vis[x] = struct{}{} } return len(ans) }
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Java
class Solution { public int findPairs(int[] nums, int k) { Set<Integer> ans = new HashSet<>(); Set<Integer> vis = new HashSet<>(); for (int x : nums) { if (vis.contains(x - k)) { ans.add(x - k); } if (vis.contains(x + k)) { ans.add(x); } vis.add(x); } return ans.size(); } }
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Python
class Solution: def findPairs(self, nums: List[int], k: int) -> int: ans = set() vis = set() for x in nums: if x - k in vis: ans.add(x - k) if x + k in vis: ans.add(x) vis.add(x) return len(ans)
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Rust
use std::collections::HashSet; impl Solution { pub fn find_pairs(nums: Vec<i32>, k: i32) -> i32 { let mut ans = HashSet::new(); let mut vis = HashSet::new(); for &x in &nums { if vis.contains(&(x - k)) { ans.insert(x - k); } if vis.contains(&(x + k)) { ans.insert(x); } vis.insert(x); } ans.len() as i32 } }
532
K-diff Pairs in an Array
Medium
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p> <p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p> <ul> <li><code>0 &lt;= i, j &lt; nums.length</code></li> <li><code>i != j</code></li> <li><code>|nums[i] - nums[j]| == k</code></li> </ul> <p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,1,5], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 1 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,5,4], k = 0 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
TypeScript
function findPairs(nums: number[], k: number): number { const ans = new Set<number>(); const vis = new Set<number>(); for (const x of nums) { if (vis.has(x - k)) { ans.add(x - k); } if (vis.has(x + k)) { ans.add(x); } vis.add(x); } return ans.size; }
533
Lonely Pixel II
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels and an integer target, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position <code>(r, c)</code> where:</p> <ul> <li>Row <code>r</code> and column <code>c</code> both contain exactly <code>target</code> black pixels.</li> <li>For all rows that have a black pixel at column <code>c</code>, they should be exactly the same as row <code>r</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-1-grid.jpg" style="width: 493px; height: 333px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;]], target = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> All the green &#39;B&#39; are the black pixels we need (all &#39;B&#39;s at column 1 and 3). Take &#39;B&#39; at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;]], target = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> <li><code>1 &lt;= target &lt;= min(m, n)</code></li> </ul>
Array; Hash Table; Matrix
C++
class Solution { public: int findBlackPixel(vector<vector<char>>& picture, int target) { int m = picture.size(); int n = picture[0].size(); vector<int> g[n]; vector<int> rows(m); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; g[j].push_back(i); } } } int ans = 0; for (int j = 0; j < n; ++j) { if (g[j].empty() || (rows[g[j][0]] != target)) { continue; } int i1 = g[j][0]; int ok = 0; if (g[j].size() == rows[i1]) { ok = target; for (int i2 : g[j]) { if (picture[i1] != picture[i2]) { ok = 0; break; } } } ans += ok; } return ans; } };
533
Lonely Pixel II
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels and an integer target, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position <code>(r, c)</code> where:</p> <ul> <li>Row <code>r</code> and column <code>c</code> both contain exactly <code>target</code> black pixels.</li> <li>For all rows that have a black pixel at column <code>c</code>, they should be exactly the same as row <code>r</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-1-grid.jpg" style="width: 493px; height: 333px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;]], target = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> All the green &#39;B&#39; are the black pixels we need (all &#39;B&#39;s at column 1 and 3). Take &#39;B&#39; at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;]], target = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> <li><code>1 &lt;= target &lt;= min(m, n)</code></li> </ul>
Array; Hash Table; Matrix
Go
func findBlackPixel(picture [][]byte, target int) (ans int) { m := len(picture) n := len(picture[0]) g := make([][]int, n) rows := make([]int, m) for i, row := range picture { for j, x := range row { if x == 'B' { rows[i]++ g[j] = append(g[j], i) } } } for j := 0; j < n; j++ { if len(g[j]) == 0 || rows[g[j][0]] != target { continue } i1 := g[j][0] ok := 0 if len(g[j]) == rows[i1] { ok = target for _, i2 := range g[j] { if !bytes.Equal(picture[i1], picture[i2]) { ok = 0 break } } } ans += ok } return }
533
Lonely Pixel II
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels and an integer target, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position <code>(r, c)</code> where:</p> <ul> <li>Row <code>r</code> and column <code>c</code> both contain exactly <code>target</code> black pixels.</li> <li>For all rows that have a black pixel at column <code>c</code>, they should be exactly the same as row <code>r</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-1-grid.jpg" style="width: 493px; height: 333px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;]], target = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> All the green &#39;B&#39; are the black pixels we need (all &#39;B&#39;s at column 1 and 3). Take &#39;B&#39; at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;]], target = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> <li><code>1 &lt;= target &lt;= min(m, n)</code></li> </ul>
Array; Hash Table; Matrix
Java
class Solution { public int findBlackPixel(char[][] picture, int target) { int m = picture.length; int n = picture[0].length; List<Integer>[] g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); int[] rows = new int[m]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; g[j].add(i); } } } int ans = 0; for (int j = 0; j < n; ++j) { if (g[j].isEmpty() || (rows[g[j].get(0)] != target)) { continue; } int i1 = g[j].get(0); int ok = 0; if (g[j].size() == rows[i1]) { ok = target; for (int i2 : g[j]) { if (!Arrays.equals(picture[i1], picture[i2])) { ok = 0; break; } } } ans += ok; } return ans; } }
533
Lonely Pixel II
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels and an integer target, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position <code>(r, c)</code> where:</p> <ul> <li>Row <code>r</code> and column <code>c</code> both contain exactly <code>target</code> black pixels.</li> <li>For all rows that have a black pixel at column <code>c</code>, they should be exactly the same as row <code>r</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-1-grid.jpg" style="width: 493px; height: 333px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;]], target = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> All the green &#39;B&#39; are the black pixels we need (all &#39;B&#39;s at column 1 and 3). Take &#39;B&#39; at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;]], target = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> <li><code>1 &lt;= target &lt;= min(m, n)</code></li> </ul>
Array; Hash Table; Matrix
Python
class Solution: def findBlackPixel(self, picture: List[List[str]], target: int) -> int: rows = [0] * len(picture) g = defaultdict(list) for i, row in enumerate(picture): for j, x in enumerate(row): if x == "B": rows[i] += 1 g[j].append(i) ans = 0 for j in g: i1 = g[j][0] if rows[i1] != target: continue if len(g[j]) == rows[i1] and all(picture[i2] == picture[i1] for i2 in g[j]): ans += target return ans
533
Lonely Pixel II
Medium
<p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>&#39;B&#39;</code> and white <code>&#39;W&#39;</code> pixels and an integer target, return <em>the number of <b>black</b> lonely pixels</em>.</p> <p>A black lonely pixel is a character <code>&#39;B&#39;</code> that located at a specific position <code>(r, c)</code> where:</p> <ul> <li>Row <code>r</code> and column <code>c</code> both contain exactly <code>target</code> black pixels.</li> <li>For all rows that have a black pixel at column <code>c</code>, they should be exactly the same as row <code>r</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-1-grid.jpg" style="width: 493px; height: 333px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;B&quot;,&quot;W&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;,&quot;B&quot;,&quot;W&quot;]], target = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> All the green &#39;B&#39; are the black pixels we need (all &#39;B&#39;s at column 1 and 3). Take &#39;B&#39; at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0533.Lonely%20Pixel%20II/images/pixel2-2-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> picture = [[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;],[&quot;W&quot;,&quot;W&quot;,&quot;B&quot;]], target = 1 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m ==&nbsp;picture.length</code></li> <li><code>n ==&nbsp;picture[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>picture[i][j]</code> is <code>&#39;W&#39;</code> or <code>&#39;B&#39;</code>.</li> <li><code>1 &lt;= target &lt;= min(m, n)</code></li> </ul>
Array; Hash Table; Matrix
TypeScript
function findBlackPixel(picture: string[][], target: number): number { const m: number = picture.length; const n: number = picture[0].length; const g: number[][] = Array.from({ length: n }, () => []); const rows: number[] = Array(m).fill(0); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (picture[i][j] === 'B') { ++rows[i]; g[j].push(i); } } } let ans: number = 0; for (let j = 0; j < n; ++j) { if (g[j].length === 0 || rows[g[j][0]] !== target) { continue; } const i1: number = g[j][0]; let ok: number = 0; if (g[j].length === rows[i1]) { ok = target; for (const i2 of g[j]) { if (picture[i1].join('') !== picture[i2].join('')) { ok = 0; break; } } } ans += ok; } return ans; }
534
Game Play Analysis III
Medium
<p>Table: <code>Activity</code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key (column with unique values) of this table. This table shows the activity of players of some games. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. </pre> <p>&nbsp;</p> <p>Write a solution to report for each player and date, how many games played <strong>so far</strong> by the player. That is, the total number of games played by the player until that date. Check the example for clarity.</p> <p>Return the result table in <strong>any order</strong>.</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> Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 6 | | 1 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ <strong>Output:</strong> +-----------+------------+---------------------+ | player_id | event_date | games_played_so_far | +-----------+------------+---------------------+ | 1 | 2016-03-01 | 5 | | 1 | 2016-05-02 | 11 | | 1 | 2017-06-25 | 12 | | 3 | 2016-03-02 | 0 | | 3 | 2018-07-03 | 5 | +-----------+------------+---------------------+ <strong>Explanation:</strong> For the player with id 1, 5 + 6 = 11 games played by 2016-05-02, and 5 + 6 + 1 = 12 games played by 2017-06-25. For the player with id 3, 0 + 5 = 5 games played by 2018-07-03. Note that for each player we only care about the days when the player logged in. </pre>
Database
SQL
# Write your MySQL query statement below SELECT player_id, event_date, SUM(games_played) OVER ( PARTITION BY player_id ORDER BY event_date ) AS games_played_so_far FROM Activity;
535
Encode and Decode TinyURL
Medium
<blockquote>Note: This is a companion problem to the <a href="https://leetcode.com/discuss/interview-question/system-design/" target="_blank">System Design</a> problem: <a href="https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/" target="_blank">Design TinyURL</a>.</blockquote> <p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p> <p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution()</code> Initializes the object of the system.</li> <li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li> <li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Output:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Explanation:</strong> Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li> <li><code>url</code> is guranteed to be a valid URL.</li> </ul>
Design; Hash Table; String; Hash Function
C++
class Solution { public: // Encodes a URL to a shortened URL. string encode(string longUrl) { string v = to_string(++idx); m[v] = longUrl; return domain + v; } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { int i = shortUrl.rfind('/') + 1; return m[shortUrl.substr(i, shortUrl.size() - i)]; } private: unordered_map<string, string> m; int idx = 0; string domain = "https://tinyurl.com/"; }; // Your Solution object will be instantiated and called as such: // Solution solution; // solution.decode(solution.encode(url));
535
Encode and Decode TinyURL
Medium
<blockquote>Note: This is a companion problem to the <a href="https://leetcode.com/discuss/interview-question/system-design/" target="_blank">System Design</a> problem: <a href="https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/" target="_blank">Design TinyURL</a>.</blockquote> <p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p> <p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution()</code> Initializes the object of the system.</li> <li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li> <li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Output:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Explanation:</strong> Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li> <li><code>url</code> is guranteed to be a valid URL.</li> </ul>
Design; Hash Table; String; Hash Function
Go
type Codec struct { m map[int]string idx int } func Constructor() Codec { m := map[int]string{} return Codec{m, 0} } // Encodes a URL to a shortened URL. func (this *Codec) encode(longUrl string) string { this.idx++ this.m[this.idx] = longUrl return "https://tinyurl.com/" + strconv.Itoa(this.idx) } // Decodes a shortened URL to its original URL. func (this *Codec) decode(shortUrl string) string { i := strings.LastIndexByte(shortUrl, '/') v, _ := strconv.Atoi(shortUrl[i+1:]) return this.m[v] } /** * Your Codec object will be instantiated and called as such: * obj := Constructor(); * url := obj.encode(longUrl); * ans := obj.decode(url); */
535
Encode and Decode TinyURL
Medium
<blockquote>Note: This is a companion problem to the <a href="https://leetcode.com/discuss/interview-question/system-design/" target="_blank">System Design</a> problem: <a href="https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/" target="_blank">Design TinyURL</a>.</blockquote> <p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p> <p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution()</code> Initializes the object of the system.</li> <li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li> <li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Output:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Explanation:</strong> Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li> <li><code>url</code> is guranteed to be a valid URL.</li> </ul>
Design; Hash Table; String; Hash Function
Java
public class Codec { private Map<String, String> m = new HashMap<>(); private int idx = 0; private String domain = "https://tinyurl.com/"; // Encodes a URL to a shortened URL. public String encode(String longUrl) { String v = String.valueOf(++idx); m.put(v, longUrl); return domain + v; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { int i = shortUrl.lastIndexOf('/') + 1; return m.get(shortUrl.substring(i)); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));
535
Encode and Decode TinyURL
Medium
<blockquote>Note: This is a companion problem to the <a href="https://leetcode.com/discuss/interview-question/system-design/" target="_blank">System Design</a> problem: <a href="https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/" target="_blank">Design TinyURL</a>.</blockquote> <p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p> <p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution()</code> Initializes the object of the system.</li> <li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li> <li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Output:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot; <strong>Explanation:</strong> Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after decoding it. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li> <li><code>url</code> is guranteed to be a valid URL.</li> </ul>
Design; Hash Table; String; Hash Function
Python
class Codec: def __init__(self): self.m = defaultdict() self.idx = 0 self.domain = 'https://tinyurl.com/' def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL.""" self.idx += 1 self.m[str(self.idx)] = longUrl return f'{self.domain}{self.idx}' def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL.""" idx = shortUrl.split('/')[-1] return self.m[idx] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
536
Construct Binary Tree from String
Medium
<p>You need to construct a binary tree from a string consisting of parenthesis and integers.</p> <p>The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root&#39;s value and a pair of parenthesis contains a child binary tree with the same structure.</p> <p>You always start to construct the <b>left</b> child node of the parent first if it exists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/images/butree.jpg" style="width: 382px; height: 322px;" /> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5))&quot; <strong>Output:</strong> [4,2,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [4,2,6,3,1,5,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;-4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [-4,2,6,3,1,5,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39;-&#39;</code> only.</li> <li>All numbers in the tree have value <strong>at most</strong> than <code>2<sup>30</sup></code>.</li> </ul>
Stack; Tree; Depth-First Search; String; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* str2tree(string s) { return dfs(s); } TreeNode* dfs(string s) { if (s == "") return nullptr; int p = s.find("("); if (p == s.npos) return new TreeNode(stoi(s)); TreeNode* root = new TreeNode(stoi(s.substr(0, p))); int start = p; int cnt = 0; for (int i = p; i < s.size(); ++i) { if (s[i] == '(') ++cnt; else if (s[i] == ')') --cnt; if (cnt == 0) { if (start == p) { root->left = dfs(s.substr(start + 1, i - start - 1)); start = i + 1; } else root->right = dfs(s.substr(start + 1, i - start - 1)); } } return root; } };
536
Construct Binary Tree from String
Medium
<p>You need to construct a binary tree from a string consisting of parenthesis and integers.</p> <p>The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root&#39;s value and a pair of parenthesis contains a child binary tree with the same structure.</p> <p>You always start to construct the <b>left</b> child node of the parent first if it exists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/images/butree.jpg" style="width: 382px; height: 322px;" /> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5))&quot; <strong>Output:</strong> [4,2,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [4,2,6,3,1,5,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;-4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [-4,2,6,3,1,5,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39;-&#39;</code> only.</li> <li>All numbers in the tree have value <strong>at most</strong> than <code>2<sup>30</sup></code>.</li> </ul>
Stack; Tree; Depth-First Search; String; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func str2tree(s string) *TreeNode { var dfs func(s string) *TreeNode dfs = func(s string) *TreeNode { if s == "" { return nil } p := strings.IndexAny(s, "(") if p == -1 { v, _ := strconv.Atoi(s) return &TreeNode{Val: v} } v, _ := strconv.Atoi(s[:p]) root := &TreeNode{Val: v} start := p cnt := 0 for i := p; i < len(s); i++ { if s[i] == '(' { cnt++ } else if s[i] == ')' { cnt-- } if cnt == 0 { if p == start { root.Left = dfs(s[start+1 : i]) start = i + 1 } else { root.Right = dfs(s[start+1 : i]) } } } return root } return dfs(s) }
536
Construct Binary Tree from String
Medium
<p>You need to construct a binary tree from a string consisting of parenthesis and integers.</p> <p>The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root&#39;s value and a pair of parenthesis contains a child binary tree with the same structure.</p> <p>You always start to construct the <b>left</b> child node of the parent first if it exists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/images/butree.jpg" style="width: 382px; height: 322px;" /> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5))&quot; <strong>Output:</strong> [4,2,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [4,2,6,3,1,5,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;-4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [-4,2,6,3,1,5,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39;-&#39;</code> only.</li> <li>All numbers in the tree have value <strong>at most</strong> than <code>2<sup>30</sup></code>.</li> </ul>
Stack; Tree; Depth-First Search; String; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode str2tree(String s) { return dfs(s); } private TreeNode dfs(String s) { if ("".equals(s)) { return null; } int p = s.indexOf("("); if (p == -1) { return new TreeNode(Integer.parseInt(s)); } TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, p))); int start = p; int cnt = 0; for (int i = p; i < s.length(); ++i) { if (s.charAt(i) == '(') { ++cnt; } else if (s.charAt(i) == ')') { --cnt; } if (cnt == 0) { if (start == p) { root.left = dfs(s.substring(start + 1, i)); start = i + 1; } else { root.right = dfs(s.substring(start + 1, i)); } } } return root; } }
536
Construct Binary Tree from String
Medium
<p>You need to construct a binary tree from a string consisting of parenthesis and integers.</p> <p>The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root&#39;s value and a pair of parenthesis contains a child binary tree with the same structure.</p> <p>You always start to construct the <b>left</b> child node of the parent first if it exists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/images/butree.jpg" style="width: 382px; height: 322px;" /> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5))&quot; <strong>Output:</strong> [4,2,6,3,1,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [4,2,6,3,1,5,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;-4(2(3)(1))(6(5)(7))&quot; <strong>Output:</strong> [-4,2,6,3,1,5,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39;-&#39;</code> only.</li> <li>All numbers in the tree have value <strong>at most</strong> than <code>2<sup>30</sup></code>.</li> </ul>
Stack; Tree; Depth-First Search; String; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def str2tree(self, s: str) -> TreeNode: def dfs(s): if not s: return None p = s.find('(') if p == -1: return TreeNode(int(s)) root = TreeNode(int(s[:p])) start = p cnt = 0 for i in range(p, len(s)): if s[i] == '(': cnt += 1 elif s[i] == ')': cnt -= 1 if cnt == 0: if start == p: root.left = dfs(s[start + 1 : i]) start = i + 1 else: root.right = dfs(s[start + 1 : i]) return root return dfs(s)
537
Complex Number Multiplication
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p> <ul> <li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>i<sup>2</sup> == -1</code>.</li> </ul> <p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot; <strong>Output:</strong> &quot;0+2i&quot; <strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot; <strong>Output:</strong> &quot;0+-2i&quot; <strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>num1</code> and <code>num2</code> are valid complex numbers.</li> </ul>
Math; String; Simulation
C++
class Solution { public: string complexNumberMultiply(string num1, string num2) { int a1, b1, a2, b2; sscanf(num1.c_str(), "%d+%di", &a1, &b1); sscanf(num2.c_str(), "%d+%di", &a2, &b2); return to_string(a1 * a2 - b1 * b2) + "+" + to_string(a1 * b2 + a2 * b1) + "i"; } };
537
Complex Number Multiplication
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p> <ul> <li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>i<sup>2</sup> == -1</code>.</li> </ul> <p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot; <strong>Output:</strong> &quot;0+2i&quot; <strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot; <strong>Output:</strong> &quot;0+-2i&quot; <strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>num1</code> and <code>num2</code> are valid complex numbers.</li> </ul>
Math; String; Simulation
Go
func complexNumberMultiply(num1 string, num2 string) string { x, _ := strconv.ParseComplex(num1, 64) y, _ := strconv.ParseComplex(num2, 64) return fmt.Sprintf("%d+%di", int(real(x*y)), int(imag(x*y))) }
537
Complex Number Multiplication
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p> <ul> <li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>i<sup>2</sup> == -1</code>.</li> </ul> <p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot; <strong>Output:</strong> &quot;0+2i&quot; <strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot; <strong>Output:</strong> &quot;0+-2i&quot; <strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>num1</code> and <code>num2</code> are valid complex numbers.</li> </ul>
Math; String; Simulation
Java
class Solution { public String complexNumberMultiply(String num1, String num2) { int[] x = parse(num1); int[] y = parse(num2); int a1 = x[0], b1 = x[1], a2 = y[0], b2 = y[1]; return (a1 * a2 - b1 * b2) + "+" + (a1 * b2 + a2 * b1) + "i"; } private int[] parse(String s) { var cs = s.substring(0, s.length() - 1).split("\\+"); return new int[] {Integer.parseInt(cs[0]), Integer.parseInt(cs[1])}; } }
537
Complex Number Multiplication
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p> <ul> <li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>i<sup>2</sup> == -1</code>.</li> </ul> <p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot; <strong>Output:</strong> &quot;0+2i&quot; <strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot; <strong>Output:</strong> &quot;0+-2i&quot; <strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>num1</code> and <code>num2</code> are valid complex numbers.</li> </ul>
Math; String; Simulation
Python
class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: a1, b1 = map(int, num1[:-1].split("+")) a2, b2 = map(int, num2[:-1].split("+")) return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i"
537
Complex Number Multiplication
Medium
<p>A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p> <ul> <li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li> <li><code>i<sup>2</sup> == -1</code>.</li> </ul> <p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot; <strong>Output:</strong> &quot;0+2i&quot; <strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot; <strong>Output:</strong> &quot;0+-2i&quot; <strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>num1</code> and <code>num2</code> are valid complex numbers.</li> </ul>
Math; String; Simulation
TypeScript
function complexNumberMultiply(num1: string, num2: string): string { const [a1, b1] = num1.slice(0, -1).split('+').map(Number); const [a2, b2] = num2.slice(0, -1).split('+').map(Number); return `${a1 * a2 - b1 * b2}+${a1 * b2 + a2 * b1}i`; }
538
Convert BST to Greater Tree
Medium
<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p> <p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0538.Convert%20BST%20to%20Greater%20Tree/images/tree.png" style="width: 500px; height: 341px;" /> <pre> <strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] <strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0,null,1] <strong>Output:</strong> [1,null,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>All the values in the tree are <strong>unique</strong>.</li> <li><code>root</code> is guaranteed to be a valid binary search tree.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int s = 0; TreeNode* convertBST(TreeNode* root) { dfs(root); return root; } void dfs(TreeNode* root) { if (!root) return; dfs(root->right); s += root->val; root->val = s; dfs(root->left); } };
538
Convert BST to Greater Tree
Medium
<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p> <p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p> <ul> <li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0538.Convert%20BST%20to%20Greater%20Tree/images/tree.png" style="width: 500px; height: 341px;" /> <pre> <strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] <strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [0,null,1] <strong>Output:</strong> [1,null,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>All the values in the tree are <strong>unique</strong>.</li> <li><code>root</code> is guaranteed to be a valid binary search tree.</li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func convertBST(root *TreeNode) *TreeNode { s := 0 var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Right) s += root.Val root.Val = s dfs(root.Left) } dfs(root) return root }