id
int64
1
3.65k
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
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
Rust
impl Solution { #[allow(dead_code)] pub fn find_duplicate(nums: Vec<i32>) -> i32 { let mut left = 0; let mut right = nums.len() - 1; while left < right { let mid = (left + right) >> 1; let cnt = nums.iter().filter(|x| **x <= (mid as i32)).count(); if cnt > mid { right = mid; } else { left = mid + 1; } } left as i32 } }
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
TypeScript
function findDuplicate(nums: number[]): number { let l = 0; let r = nums.length - 1; while (l < r) { const mid = (l + r) >> 1; let cnt = 0; for (const v of nums) { if (v <= mid) { ++cnt; } } if (cnt > mid) { r = mid; } else { l = mid + 1; } } return l; }
288
Unique Word Abbreviation
Medium
<p>The <strong>abbreviation</strong> of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an <strong>abbreviation</strong> of itself.</p> <p>For example:</p> <ul> <li><code>dog --&gt; d1g</code> because there is one letter between the first letter <code>&#39;d&#39;</code> and the last letter <code>&#39;g&#39;</code>.</li> <li><code>internationalization --&gt; i18n</code> because there are 18 letters between the first letter <code>&#39;i&#39;</code> and the last letter <code>&#39;n&#39;</code>.</li> <li><code>it --&gt; it</code> because any word with only two characters is an <strong>abbreviation</strong> of itself.</li> </ul> <p>Implement the <code>ValidWordAbbr</code> class:</p> <ul> <li><code>ValidWordAbbr(String[] dictionary)</code> Initializes the object with a <code>dictionary</code> of words.</li> <li><code>boolean isUnique(string word)</code> Returns <code>true</code> if <strong>either</strong> of the following conditions are met (otherwise returns <code>false</code>): <ul> <li>There is no word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>.</li> <li>For any word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>, that word and <code>word</code> are <strong>the same</strong>.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;ValidWordAbbr&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;] [[[&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]], [&quot;dear&quot;], [&quot;cart&quot;], [&quot;cane&quot;], [&quot;make&quot;], [&quot;cake&quot;]] <strong>Output</strong> [null, false, true, false, true, true] <strong>Explanation</strong> ValidWordAbbr validWordAbbr = new ValidWordAbbr([&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]); validWordAbbr.isUnique(&quot;dear&quot;); // return false, dictionary word &quot;deer&quot; and word &quot;dear&quot; have the same abbreviation &quot;d2r&quot; but are not the same. validWordAbbr.isUnique(&quot;cart&quot;); // return true, no words in the dictionary have the abbreviation &quot;c2t&quot;. validWordAbbr.isUnique(&quot;cane&quot;); // return false, dictionary word &quot;cake&quot; and word &quot;cane&quot; have the same abbreviation &quot;c2e&quot; but are not the same. validWordAbbr.isUnique(&quot;make&quot;); // return true, no words in the dictionary have the abbreviation &quot;m2e&quot;. validWordAbbr.isUnique(&quot;cake&quot;); // return true, because &quot;cake&quot; is already in the dictionary and no other word in the dictionary has &quot;c2e&quot; abbreviation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 20</code></li> <li><code>dictionary[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>At most <code>5000</code> calls will be made to <code>isUnique</code>.</li> </ul>
Design; Array; Hash Table; String
C++
class ValidWordAbbr { public: ValidWordAbbr(vector<string>& dictionary) { for (auto& s : dictionary) { d[abbr(s)].insert(s); } } bool isUnique(string word) { string s = abbr(word); return !d.count(s) || (d[s].size() == 1 && d[s].count(word)); } private: unordered_map<string, unordered_set<string>> d; string abbr(string& s) { int n = s.size(); return n < 3 ? s : s.substr(0, 1) + to_string(n - 2) + s.substr(n - 1, 1); } }; /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr* obj = new ValidWordAbbr(dictionary); * bool param_1 = obj->isUnique(word); */
288
Unique Word Abbreviation
Medium
<p>The <strong>abbreviation</strong> of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an <strong>abbreviation</strong> of itself.</p> <p>For example:</p> <ul> <li><code>dog --&gt; d1g</code> because there is one letter between the first letter <code>&#39;d&#39;</code> and the last letter <code>&#39;g&#39;</code>.</li> <li><code>internationalization --&gt; i18n</code> because there are 18 letters between the first letter <code>&#39;i&#39;</code> and the last letter <code>&#39;n&#39;</code>.</li> <li><code>it --&gt; it</code> because any word with only two characters is an <strong>abbreviation</strong> of itself.</li> </ul> <p>Implement the <code>ValidWordAbbr</code> class:</p> <ul> <li><code>ValidWordAbbr(String[] dictionary)</code> Initializes the object with a <code>dictionary</code> of words.</li> <li><code>boolean isUnique(string word)</code> Returns <code>true</code> if <strong>either</strong> of the following conditions are met (otherwise returns <code>false</code>): <ul> <li>There is no word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>.</li> <li>For any word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>, that word and <code>word</code> are <strong>the same</strong>.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;ValidWordAbbr&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;] [[[&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]], [&quot;dear&quot;], [&quot;cart&quot;], [&quot;cane&quot;], [&quot;make&quot;], [&quot;cake&quot;]] <strong>Output</strong> [null, false, true, false, true, true] <strong>Explanation</strong> ValidWordAbbr validWordAbbr = new ValidWordAbbr([&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]); validWordAbbr.isUnique(&quot;dear&quot;); // return false, dictionary word &quot;deer&quot; and word &quot;dear&quot; have the same abbreviation &quot;d2r&quot; but are not the same. validWordAbbr.isUnique(&quot;cart&quot;); // return true, no words in the dictionary have the abbreviation &quot;c2t&quot;. validWordAbbr.isUnique(&quot;cane&quot;); // return false, dictionary word &quot;cake&quot; and word &quot;cane&quot; have the same abbreviation &quot;c2e&quot; but are not the same. validWordAbbr.isUnique(&quot;make&quot;); // return true, no words in the dictionary have the abbreviation &quot;m2e&quot;. validWordAbbr.isUnique(&quot;cake&quot;); // return true, because &quot;cake&quot; is already in the dictionary and no other word in the dictionary has &quot;c2e&quot; abbreviation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 20</code></li> <li><code>dictionary[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>At most <code>5000</code> calls will be made to <code>isUnique</code>.</li> </ul>
Design; Array; Hash Table; String
Go
type ValidWordAbbr struct { d map[string]map[string]bool } func Constructor(dictionary []string) ValidWordAbbr { d := make(map[string]map[string]bool) for _, s := range dictionary { abbr := abbr(s) if _, ok := d[abbr]; !ok { d[abbr] = make(map[string]bool) } d[abbr][s] = true } return ValidWordAbbr{d} } func (this *ValidWordAbbr) IsUnique(word string) bool { ws := this.d[abbr(word)] return ws == nil || (len(ws) == 1 && ws[word]) } func abbr(s string) string { n := len(s) if n < 3 { return s } return fmt.Sprintf("%c%d%c", s[0], n-2, s[n-1]) } /** * Your ValidWordAbbr object will be instantiated and called as such: * obj := Constructor(dictionary); * param_1 := obj.IsUnique(word); */
288
Unique Word Abbreviation
Medium
<p>The <strong>abbreviation</strong> of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an <strong>abbreviation</strong> of itself.</p> <p>For example:</p> <ul> <li><code>dog --&gt; d1g</code> because there is one letter between the first letter <code>&#39;d&#39;</code> and the last letter <code>&#39;g&#39;</code>.</li> <li><code>internationalization --&gt; i18n</code> because there are 18 letters between the first letter <code>&#39;i&#39;</code> and the last letter <code>&#39;n&#39;</code>.</li> <li><code>it --&gt; it</code> because any word with only two characters is an <strong>abbreviation</strong> of itself.</li> </ul> <p>Implement the <code>ValidWordAbbr</code> class:</p> <ul> <li><code>ValidWordAbbr(String[] dictionary)</code> Initializes the object with a <code>dictionary</code> of words.</li> <li><code>boolean isUnique(string word)</code> Returns <code>true</code> if <strong>either</strong> of the following conditions are met (otherwise returns <code>false</code>): <ul> <li>There is no word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>.</li> <li>For any word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>, that word and <code>word</code> are <strong>the same</strong>.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;ValidWordAbbr&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;] [[[&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]], [&quot;dear&quot;], [&quot;cart&quot;], [&quot;cane&quot;], [&quot;make&quot;], [&quot;cake&quot;]] <strong>Output</strong> [null, false, true, false, true, true] <strong>Explanation</strong> ValidWordAbbr validWordAbbr = new ValidWordAbbr([&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]); validWordAbbr.isUnique(&quot;dear&quot;); // return false, dictionary word &quot;deer&quot; and word &quot;dear&quot; have the same abbreviation &quot;d2r&quot; but are not the same. validWordAbbr.isUnique(&quot;cart&quot;); // return true, no words in the dictionary have the abbreviation &quot;c2t&quot;. validWordAbbr.isUnique(&quot;cane&quot;); // return false, dictionary word &quot;cake&quot; and word &quot;cane&quot; have the same abbreviation &quot;c2e&quot; but are not the same. validWordAbbr.isUnique(&quot;make&quot;); // return true, no words in the dictionary have the abbreviation &quot;m2e&quot;. validWordAbbr.isUnique(&quot;cake&quot;); // return true, because &quot;cake&quot; is already in the dictionary and no other word in the dictionary has &quot;c2e&quot; abbreviation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 20</code></li> <li><code>dictionary[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>At most <code>5000</code> calls will be made to <code>isUnique</code>.</li> </ul>
Design; Array; Hash Table; String
Java
class ValidWordAbbr { private Map<String, Set<String>> d = new HashMap<>(); public ValidWordAbbr(String[] dictionary) { for (var s : dictionary) { d.computeIfAbsent(abbr(s), k -> new HashSet<>()).add(s); } } public boolean isUnique(String word) { var ws = d.get(abbr(word)); return ws == null || (ws.size() == 1 && ws.contains(word)); } private String abbr(String s) { int n = s.length(); return n < 3 ? s : s.substring(0, 1) + (n - 2) + s.substring(n - 1); } } /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr obj = new ValidWordAbbr(dictionary); * boolean param_1 = obj.isUnique(word); */
288
Unique Word Abbreviation
Medium
<p>The <strong>abbreviation</strong> of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an <strong>abbreviation</strong> of itself.</p> <p>For example:</p> <ul> <li><code>dog --&gt; d1g</code> because there is one letter between the first letter <code>&#39;d&#39;</code> and the last letter <code>&#39;g&#39;</code>.</li> <li><code>internationalization --&gt; i18n</code> because there are 18 letters between the first letter <code>&#39;i&#39;</code> and the last letter <code>&#39;n&#39;</code>.</li> <li><code>it --&gt; it</code> because any word with only two characters is an <strong>abbreviation</strong> of itself.</li> </ul> <p>Implement the <code>ValidWordAbbr</code> class:</p> <ul> <li><code>ValidWordAbbr(String[] dictionary)</code> Initializes the object with a <code>dictionary</code> of words.</li> <li><code>boolean isUnique(string word)</code> Returns <code>true</code> if <strong>either</strong> of the following conditions are met (otherwise returns <code>false</code>): <ul> <li>There is no word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>.</li> <li>For any word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>, that word and <code>word</code> are <strong>the same</strong>.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;ValidWordAbbr&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;] [[[&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]], [&quot;dear&quot;], [&quot;cart&quot;], [&quot;cane&quot;], [&quot;make&quot;], [&quot;cake&quot;]] <strong>Output</strong> [null, false, true, false, true, true] <strong>Explanation</strong> ValidWordAbbr validWordAbbr = new ValidWordAbbr([&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]); validWordAbbr.isUnique(&quot;dear&quot;); // return false, dictionary word &quot;deer&quot; and word &quot;dear&quot; have the same abbreviation &quot;d2r&quot; but are not the same. validWordAbbr.isUnique(&quot;cart&quot;); // return true, no words in the dictionary have the abbreviation &quot;c2t&quot;. validWordAbbr.isUnique(&quot;cane&quot;); // return false, dictionary word &quot;cake&quot; and word &quot;cane&quot; have the same abbreviation &quot;c2e&quot; but are not the same. validWordAbbr.isUnique(&quot;make&quot;); // return true, no words in the dictionary have the abbreviation &quot;m2e&quot;. validWordAbbr.isUnique(&quot;cake&quot;); // return true, because &quot;cake&quot; is already in the dictionary and no other word in the dictionary has &quot;c2e&quot; abbreviation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 20</code></li> <li><code>dictionary[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>At most <code>5000</code> calls will be made to <code>isUnique</code>.</li> </ul>
Design; Array; Hash Table; String
Python
class ValidWordAbbr: def __init__(self, dictionary: List[str]): self.d = defaultdict(set) for s in dictionary: self.d[self.abbr(s)].add(s) def isUnique(self, word: str) -> bool: s = self.abbr(word) return s not in self.d or all(word == t for t in self.d[s]) def abbr(self, s: str) -> str: return s if len(s) < 3 else s[0] + str(len(s) - 2) + s[-1] # Your ValidWordAbbr object will be instantiated and called as such: # obj = ValidWordAbbr(dictionary) # param_1 = obj.isUnique(word)
288
Unique Word Abbreviation
Medium
<p>The <strong>abbreviation</strong> of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an <strong>abbreviation</strong> of itself.</p> <p>For example:</p> <ul> <li><code>dog --&gt; d1g</code> because there is one letter between the first letter <code>&#39;d&#39;</code> and the last letter <code>&#39;g&#39;</code>.</li> <li><code>internationalization --&gt; i18n</code> because there are 18 letters between the first letter <code>&#39;i&#39;</code> and the last letter <code>&#39;n&#39;</code>.</li> <li><code>it --&gt; it</code> because any word with only two characters is an <strong>abbreviation</strong> of itself.</li> </ul> <p>Implement the <code>ValidWordAbbr</code> class:</p> <ul> <li><code>ValidWordAbbr(String[] dictionary)</code> Initializes the object with a <code>dictionary</code> of words.</li> <li><code>boolean isUnique(string word)</code> Returns <code>true</code> if <strong>either</strong> of the following conditions are met (otherwise returns <code>false</code>): <ul> <li>There is no word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>.</li> <li>For any word in <code>dictionary</code> whose <strong>abbreviation</strong> is equal to <code>word</code>&#39;s <strong>abbreviation</strong>, that word and <code>word</code> are <strong>the same</strong>.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;ValidWordAbbr&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;, &quot;isUnique&quot;] [[[&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]], [&quot;dear&quot;], [&quot;cart&quot;], [&quot;cane&quot;], [&quot;make&quot;], [&quot;cake&quot;]] <strong>Output</strong> [null, false, true, false, true, true] <strong>Explanation</strong> ValidWordAbbr validWordAbbr = new ValidWordAbbr([&quot;deer&quot;, &quot;door&quot;, &quot;cake&quot;, &quot;card&quot;]); validWordAbbr.isUnique(&quot;dear&quot;); // return false, dictionary word &quot;deer&quot; and word &quot;dear&quot; have the same abbreviation &quot;d2r&quot; but are not the same. validWordAbbr.isUnique(&quot;cart&quot;); // return true, no words in the dictionary have the abbreviation &quot;c2t&quot;. validWordAbbr.isUnique(&quot;cane&quot;); // return false, dictionary word &quot;cake&quot; and word &quot;cane&quot; have the same abbreviation &quot;c2e&quot; but are not the same. validWordAbbr.isUnique(&quot;make&quot;); // return true, no words in the dictionary have the abbreviation &quot;m2e&quot;. validWordAbbr.isUnique(&quot;cake&quot;); // return true, because &quot;cake&quot; is already in the dictionary and no other word in the dictionary has &quot;c2e&quot; abbreviation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= dictionary.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 20</code></li> <li><code>dictionary[i]</code> consists of lowercase English letters.</li> <li><code>1 &lt;= word.length &lt;= 20</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>At most <code>5000</code> calls will be made to <code>isUnique</code>.</li> </ul>
Design; Array; Hash Table; String
TypeScript
class ValidWordAbbr { private d: Map<string, Set<string>> = new Map(); constructor(dictionary: string[]) { for (const s of dictionary) { const abbr = this.abbr(s); if (!this.d.has(abbr)) { this.d.set(abbr, new Set()); } this.d.get(abbr)!.add(s); } } isUnique(word: string): boolean { const ws = this.d.get(this.abbr(word)); return ws === undefined || (ws.size === 1 && ws.has(word)); } abbr(s: string): string { const n = s.length; return n < 3 ? s : s[0] + (n - 2) + s[n - 1]; } } /** * Your ValidWordAbbr object will be instantiated and called as such: * var obj = new ValidWordAbbr(dictionary) * var param_1 = obj.isUnique(word) */
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
C++
class Solution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(), n = board[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int live = -board[i][j]; 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] > 0) { ++live; } } } if (board[i][j] == 1 && (live < 2 || live > 3)) { board[i][j] = 2; } if (board[i][j] == 0 && live == 3) { board[i][j] = -1; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == 2) { board[i][j] = 0; } else if (board[i][j] == -1) { board[i][j] = 1; } } } } };
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
C#
public class Solution { public void GameOfLife(int[][] board) { int m = board.Length; int n = board[0].Length; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int live = -board[i][j]; 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] > 0) { ++live; } } } if (board[i][j] == 1 && (live < 2 || live > 3)) { board[i][j] = 2; } if (board[i][j] == 0 && live == 3) { board[i][j] = -1; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == 2) { board[i][j] = 0; } if (board[i][j] == -1) { board[i][j] = 1; } } } } }
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
Go
func gameOfLife(board [][]int) { m, n := len(board), len(board[0]) for i := 0; i < m; i++ { for j, v := range board[i] { live := -v 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] > 0 { live++ } } } if v == 1 && (live < 2 || live > 3) { board[i][j] = 2 } if v == 0 && live == 3 { board[i][j] = -1 } } } for i := 0; i < m; i++ { for j, v := range board[i] { if v == 2 { board[i][j] = 0 } if v == -1 { board[i][j] = 1 } } } }
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
Java
class Solution { public void gameOfLife(int[][] board) { int m = board.length, n = board[0].length; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int live = -board[i][j]; 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] > 0) { ++live; } } } if (board[i][j] == 1 && (live < 2 || live > 3)) { board[i][j] = 2; } if (board[i][j] == 0 && live == 3) { board[i][j] = -1; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == 2) { board[i][j] = 0; } else if (board[i][j] == -1) { board[i][j] = 1; } } } } }
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
Python
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: m, n = len(board), len(board[0]) for i in range(m): for j in range(n): live = -board[i][j] 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] > 0: live += 1 if board[i][j] and (live < 2 or live > 3): board[i][j] = 2 if board[i][j] == 0 and live == 3: board[i][j] = -1 for i in range(m): for j in range(n): if board[i][j] == 2: board[i][j] = 0 elif board[i][j] == -1: board[i][j] = 1
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
Rust
const DIR: [(i32, i32); 8] = [ (-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1), ]; impl Solution { #[allow(dead_code)] pub fn game_of_life(board: &mut Vec<Vec<i32>>) { let n = board.len(); let m = board[0].len(); let mut weight_vec: Vec<Vec<i32>> = vec![vec![0; m]; n]; // Initialize the weight vector for i in 0..n { for j in 0..m { if board[i][j] == 0 { continue; } for (dx, dy) in DIR { let x = (i as i32) + dx; let y = (j as i32) + dy; if Self::check_bounds(x, y, n as i32, m as i32) { weight_vec[x as usize][y as usize] += 1; } } } } // Update the board for i in 0..n { for j in 0..m { if weight_vec[i][j] < 2 { board[i][j] = 0; } else if weight_vec[i][j] <= 3 { if board[i][j] == 0 && weight_vec[i][j] == 3 { board[i][j] = 1; } } else { board[i][j] = 0; } } } } #[allow(dead_code)] fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { i >= 0 && i < n && j >= 0 && j < m } }
289
Game of Life
Medium
<p>According to <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p> <p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p> <ol> <li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li> <li>Any live cell with two or three live neighbors lives on to the next generation.</li> <li>Any live cell with more than three live neighbors dies, as if by over-population.</li> <li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li> </ol> <p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p> <p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p> <p><strong>Note</strong> that you do not need to return anything.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid1.jpg" style="width: 562px; height: 322px;" /> <pre> <strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] <strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0289.Game%20of%20Life/images/grid2.jpg" style="width: 402px; height: 162px;" /> <pre> <strong>Input:</strong> board = [[1,1],[1,0]] <strong>Output:</strong> [[1,1],[1,1]] </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;= 25</code></li> <li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li> <li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li> </ul>
Array; Matrix; Simulation
TypeScript
/** Do not return anything, modify board in-place instead. */ function gameOfLife(board: number[][]): void { const m = board.length; const n = board[0].length; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { let live = -board[i][j]; 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] > 0) { ++live; } } } if (board[i][j] === 1 && (live < 2 || live > 3)) { board[i][j] = 2; } if (board[i][j] === 0 && live === 3) { board[i][j] = -1; } } } for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (board[i][j] === 2) { board[i][j] = 0; } if (board[i][j] === -1) { board[i][j] = 1; } } } }
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
C++
class Solution { public: bool wordPattern(string pattern, string s) { istringstream is(s); vector<string> ws; while (is >> s) { ws.push_back(s); } if (pattern.size() != ws.size()) { return false; } unordered_map<char, string> d1; unordered_map<string, char> d2; for (int i = 0; i < ws.size(); ++i) { char a = pattern[i]; string b = ws[i]; if ((d1.count(a) && d1[a] != b) || (d2.count(b) && d2[b] != a)) { return false; } d1[a] = b; d2[b] = a; } return true; } };
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
C#
public class Solution { public bool WordPattern(string pattern, string s) { var ws = s.Split(' '); if (pattern.Length != ws.Length) { return false; } var d1 = new Dictionary<char, string>(); var d2 = new Dictionary<string, char>(); for (int i = 0; i < ws.Length; ++i) { var a = pattern[i]; var b = ws[i]; if (d1.ContainsKey(a) && d1[a] != b) { return false; } if (d2.ContainsKey(b) && d2[b] != a) { return false; } d1[a] = b; d2[b] = a; } return true; } }
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
Go
func wordPattern(pattern string, s string) bool { ws := strings.Split(s, " ") if len(ws) != len(pattern) { return false } d1 := map[rune]string{} d2 := map[string]rune{} for i, a := range pattern { b := ws[i] if v, ok := d1[a]; ok && v != b { return false } if v, ok := d2[b]; ok && v != a { return false } d1[a] = b d2[b] = a } return true }
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
Java
class Solution { public boolean wordPattern(String pattern, String s) { String[] ws = s.split(" "); if (pattern.length() != ws.length) { return false; } Map<Character, String> d1 = new HashMap<>(); Map<String, Character> d2 = new HashMap<>(); for (int i = 0; i < ws.length; ++i) { char a = pattern.charAt(i); String b = ws[i]; if (!d1.getOrDefault(a, b).equals(b) || d2.getOrDefault(b, a) != a) { return false; } d1.put(a, b); d2.put(b, a); } return true; } }
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
Python
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: ws = s.split() if len(pattern) != len(ws): return False d1 = {} d2 = {} for a, b in zip(pattern, ws): if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a): return False d1[a] = b d2[b] = a return True
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
Rust
use std::collections::HashMap; impl Solution { pub fn word_pattern(pattern: String, s: String) -> bool { let cs1: Vec<char> = pattern.chars().collect(); let cs2: Vec<&str> = s.split_whitespace().collect(); let n = cs1.len(); if n != cs2.len() { return false; } let mut map1 = HashMap::new(); let mut map2 = HashMap::new(); for i in 0..n { let c = cs1[i]; let s = cs2[i]; if !map1.contains_key(&c) { map1.insert(c, i); } if !map2.contains_key(&s) { map2.insert(s, i); } if map1.get(&c) != map2.get(&s) { return false; } } true } }
290
Word Pattern
Easy
<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p> <p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p> <ul> <li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li> <li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li> <li>No two letters map to the same word, and no two words map to the same letter.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The bijection can be established as:</p> <ul> <li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li> <li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 300</code></li> <li><code>pattern</code> contains only lower-case English letters.</li> <li><code>1 &lt;= s.length &lt;= 3000</code></li> <li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li> <li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li> <li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li> </ul>
Hash Table; String
TypeScript
function wordPattern(pattern: string, s: string): boolean { const ws = s.split(' '); if (pattern.length !== ws.length) { return false; } const d1 = new Map<string, string>(); const d2 = new Map<string, string>(); for (let i = 0; i < pattern.length; ++i) { const a = pattern[i]; const b = ws[i]; if (d1.has(a) && d1.get(a) !== b) { return false; } if (d2.has(b) && d2.get(b) !== a) { return false; } d1.set(a, b); d2.set(b, a); } return true; }
291
Word Pattern II
Medium
<p>Given a <code>pattern</code> and a string <code>s</code>, return <code>true</code><em> if </em><code>s</code><em> <strong>matches</strong> the </em><code>pattern</code><em>.</em></p> <p>A string <code>s</code> <b>matches</b> a <code>pattern</code> if there is some <strong>bijective mapping</strong> of single characters to <strong>non-empty</strong> strings such that if each character in <code>pattern</code> is replaced by the string it maps to, then the resulting string is <code>s</code>. A <strong>bijective mapping</strong> means that no two characters map to the same string, and no character maps to two different strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;abab&quot;, s = &quot;redblueredblue&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;red&quot; &#39;b&#39; -&gt; &quot;blue&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aaaa&quot;, s = &quot;asdasdasdasd&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;asd&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aabb&quot;, s = &quot;xyzabcxzyabc&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length, s.length &lt;= 20</code></li> <li><code>pattern</code> and <code>s</code> consist of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
C++
class Solution { public: bool wordPatternMatch(string pattern, string s) { unordered_set<string> vis; unordered_map<char, string> d; return dfs(0, 0, pattern, s, vis, d); } bool dfs(int i, int j, string& p, string& s, unordered_set<string>& vis, unordered_map<char, string>& d) { int m = p.size(), n = s.size(); if (i == m && j == n) return true; if (i == m || j == n || m - i > n - j) return false; char c = p[i]; for (int k = j + 1; k <= n; ++k) { string t = s.substr(j, k - j); if (d.count(c) && d[c] == t) { if (dfs(i + 1, k, p, s, vis, d)) return true; } if (!d.count(c) && !vis.count(t)) { d[c] = t; vis.insert(t); if (dfs(i + 1, k, p, s, vis, d)) return true; vis.erase(t); d.erase(c); } } return false; } };
291
Word Pattern II
Medium
<p>Given a <code>pattern</code> and a string <code>s</code>, return <code>true</code><em> if </em><code>s</code><em> <strong>matches</strong> the </em><code>pattern</code><em>.</em></p> <p>A string <code>s</code> <b>matches</b> a <code>pattern</code> if there is some <strong>bijective mapping</strong> of single characters to <strong>non-empty</strong> strings such that if each character in <code>pattern</code> is replaced by the string it maps to, then the resulting string is <code>s</code>. A <strong>bijective mapping</strong> means that no two characters map to the same string, and no character maps to two different strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;abab&quot;, s = &quot;redblueredblue&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;red&quot; &#39;b&#39; -&gt; &quot;blue&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aaaa&quot;, s = &quot;asdasdasdasd&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;asd&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aabb&quot;, s = &quot;xyzabcxzyabc&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length, s.length &lt;= 20</code></li> <li><code>pattern</code> and <code>s</code> consist of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Go
func wordPatternMatch(pattern string, s string) bool { m, n := len(pattern), len(s) vis := map[string]bool{} d := map[byte]string{} var dfs func(i, j int) bool dfs = func(i, j int) bool { if i == m && j == n { return true } if i == m || j == n || m-i > n-j { return false } c := pattern[i] for k := j + 1; k <= n; k++ { t := s[j:k] if v, ok := d[c]; ok && v == t { if dfs(i+1, k) { return true } } if _, ok := d[c]; !ok && !vis[t] { d[c] = t vis[t] = true if dfs(i+1, k) { return true } delete(d, c) vis[t] = false } } return false } return dfs(0, 0) }
291
Word Pattern II
Medium
<p>Given a <code>pattern</code> and a string <code>s</code>, return <code>true</code><em> if </em><code>s</code><em> <strong>matches</strong> the </em><code>pattern</code><em>.</em></p> <p>A string <code>s</code> <b>matches</b> a <code>pattern</code> if there is some <strong>bijective mapping</strong> of single characters to <strong>non-empty</strong> strings such that if each character in <code>pattern</code> is replaced by the string it maps to, then the resulting string is <code>s</code>. A <strong>bijective mapping</strong> means that no two characters map to the same string, and no character maps to two different strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;abab&quot;, s = &quot;redblueredblue&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;red&quot; &#39;b&#39; -&gt; &quot;blue&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aaaa&quot;, s = &quot;asdasdasdasd&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;asd&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aabb&quot;, s = &quot;xyzabcxzyabc&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length, s.length &lt;= 20</code></li> <li><code>pattern</code> and <code>s</code> consist of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Java
class Solution { private Set<String> vis; private Map<Character, String> d; private String p; private String s; private int m; private int n; public boolean wordPatternMatch(String pattern, String s) { vis = new HashSet<>(); d = new HashMap<>(); this.p = pattern; this.s = s; m = p.length(); n = s.length(); return dfs(0, 0); } private boolean dfs(int i, int j) { if (i == m && j == n) { return true; } if (i == m || j == n || m - i > n - j) { return false; } char c = p.charAt(i); for (int k = j + 1; k <= n; ++k) { String t = s.substring(j, k); if (d.getOrDefault(c, "").equals(t)) { if (dfs(i + 1, k)) { return true; } } if (!d.containsKey(c) && !vis.contains(t)) { d.put(c, t); vis.add(t); if (dfs(i + 1, k)) { return true; } vis.remove(t); d.remove(c); } } return false; } }
291
Word Pattern II
Medium
<p>Given a <code>pattern</code> and a string <code>s</code>, return <code>true</code><em> if </em><code>s</code><em> <strong>matches</strong> the </em><code>pattern</code><em>.</em></p> <p>A string <code>s</code> <b>matches</b> a <code>pattern</code> if there is some <strong>bijective mapping</strong> of single characters to <strong>non-empty</strong> strings such that if each character in <code>pattern</code> is replaced by the string it maps to, then the resulting string is <code>s</code>. A <strong>bijective mapping</strong> means that no two characters map to the same string, and no character maps to two different strings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;abab&quot;, s = &quot;redblueredblue&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;red&quot; &#39;b&#39; -&gt; &quot;blue&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aaaa&quot;, s = &quot;asdasdasdasd&quot; <strong>Output:</strong> true <strong>Explanation:</strong> One possible mapping is as follows: &#39;a&#39; -&gt; &quot;asd&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> pattern = &quot;aabb&quot;, s = &quot;xyzabcxzyabc&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length, s.length &lt;= 20</code></li> <li><code>pattern</code> and <code>s</code> consist of only lowercase English letters.</li> </ul>
Hash Table; String; Backtracking
Python
class Solution: def wordPatternMatch(self, pattern: str, s: str) -> bool: def dfs(i, j): if i == m and j == n: return True if i == m or j == n or n - j < m - i: return False for k in range(j, n): t = s[j : k + 1] if d.get(pattern[i]) == t: if dfs(i + 1, k + 1): return True if pattern[i] not in d and t not in vis: d[pattern[i]] = t vis.add(t) if dfs(i + 1, k + 1): return True d.pop(pattern[i]) vis.remove(t) return False m, n = len(pattern), len(s) d = {} vis = set() return dfs(0, 0)
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
C++
class Solution { public: bool canWinNim(int n) { return n % 4 != 0; } };
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
Go
func canWinNim(n int) bool { return n%4 != 0 }
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
Java
class Solution { public boolean canWinNim(int n) { return n % 4 != 0; } }
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
Python
class Solution: def canWinNim(self, n: int) -> bool: return n % 4 != 0
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
Rust
impl Solution { pub fn can_win_nim(n: i32) -> bool { n % 4 != 0 } }
292
Nim Game
Easy
<p>You are playing the following Nim Game with your friend:</p> <ul> <li>Initially, there is a heap of stones on the table.</li> <li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li> <li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li> <li>The one who removes the last stone is the winner.</li> </ul> <p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> false <strong>Explanation:</strong> These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Brainteaser; Math; Game Theory
TypeScript
function canWinNim(n: number): boolean { return n % 4 != 0; }
293
Flip Game
Easy
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return all possible states of the string <code>currentState</code> after <strong>one valid move</strong>. You may return the answer in <strong>any order</strong>. If there is no valid move, return an empty list <code>[]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> [&quot;--++&quot;,&quot;+--+&quot;,&quot;++--&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 500</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul>
String
C++
class Solution { public: vector<string> generatePossibleNextMoves(string s) { vector<string> ans; for (int i = 0; i < s.size() - 1; ++i) { if (s[i] == '+' && s[i + 1] == '+') { s[i] = s[i + 1] = '-'; ans.emplace_back(s); s[i] = s[i + 1] = '+'; } } return ans; } };
293
Flip Game
Easy
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return all possible states of the string <code>currentState</code> after <strong>one valid move</strong>. You may return the answer in <strong>any order</strong>. If there is no valid move, return an empty list <code>[]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> [&quot;--++&quot;,&quot;+--+&quot;,&quot;++--&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 500</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul>
String
Go
func generatePossibleNextMoves(currentState string) (ans []string) { s := []byte(currentState) for i := 0; i < len(s)-1; i++ { if s[i] == '+' && s[i+1] == '+' { s[i], s[i+1] = '-', '-' ans = append(ans, string(s)) s[i], s[i+1] = '+', '+' } } return }
293
Flip Game
Easy
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return all possible states of the string <code>currentState</code> after <strong>one valid move</strong>. You may return the answer in <strong>any order</strong>. If there is no valid move, return an empty list <code>[]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> [&quot;--++&quot;,&quot;+--+&quot;,&quot;++--&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 500</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul>
String
Java
class Solution { public List<String> generatePossibleNextMoves(String currentState) { List<String> ans = new ArrayList<>(); char[] s = currentState.toCharArray(); for (int i = 0; i < s.length - 1; ++i) { if (s[i] == '+' && s[i + 1] == '+') { s[i] = '-'; s[i + 1] = '-'; ans.add(new String(s)); s[i] = '+'; s[i + 1] = '+'; } } return ans; } }
293
Flip Game
Easy
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return all possible states of the string <code>currentState</code> after <strong>one valid move</strong>. You may return the answer in <strong>any order</strong>. If there is no valid move, return an empty list <code>[]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> [&quot;--++&quot;,&quot;+--+&quot;,&quot;++--&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 500</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul>
String
Python
class Solution: def generatePossibleNextMoves(self, currentState: str) -> List[str]: s = list(currentState) ans = [] for i, (a, b) in enumerate(pairwise(s)): if a == b == "+": s[i] = s[i + 1] = "-" ans.append("".join(s)) s[i] = s[i + 1] = "+" return ans
293
Flip Game
Easy
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return all possible states of the string <code>currentState</code> after <strong>one valid move</strong>. You may return the answer in <strong>any order</strong>. If there is no valid move, return an empty list <code>[]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> [&quot;--++&quot;,&quot;+--+&quot;,&quot;++--&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 500</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul>
String
TypeScript
function generatePossibleNextMoves(currentState: string): string[] { const s = currentState.split(''); const ans: string[] = []; for (let i = 0; i < s.length - 1; ++i) { if (s[i] === '+' && s[i + 1] === '+') { s[i] = s[i + 1] = '-'; ans.push(s.join('')); s[i] = s[i + 1] = '+'; } } return ans; }
294
Flip Game II
Medium
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return <code>true</code> <em>if the starting player can <strong>guarantee a win</strong></em>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The starting player can guarantee a win by flipping the middle &quot;++&quot; to become &quot;+--+&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 60</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Derive your algorithm&#39;s runtime complexity.
Memoization; Math; Dynamic Programming; Backtracking; Game Theory
C++
using ll = long long; class Solution { public: int n; unordered_map<ll, bool> memo; bool canWin(string currentState) { n = currentState.size(); ll mask = 0; for (int i = 0; i < n; ++i) if (currentState[i] == '+') mask |= 1ll << i; return dfs(mask); } bool dfs(ll mask) { if (memo.count(mask)) return memo[mask]; for (int i = 0; i < n - 1; ++i) { if ((mask & (1ll << i)) == 0 || (mask & (1ll << (i + 1))) == 0) continue; if (dfs(mask ^ (1ll << i) ^ (1ll << (i + 1)))) continue; memo[mask] = true; return true; } memo[mask] = false; return false; } };
294
Flip Game II
Medium
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return <code>true</code> <em>if the starting player can <strong>guarantee a win</strong></em>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The starting player can guarantee a win by flipping the middle &quot;++&quot; to become &quot;+--+&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 60</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Derive your algorithm&#39;s runtime complexity.
Memoization; Math; Dynamic Programming; Backtracking; Game Theory
Go
func canWin(currentState string) bool { n := len(currentState) memo := map[int]bool{} mask := 0 for i, c := range currentState { if c == '+' { mask |= 1 << i } } var dfs func(int) bool dfs = func(mask int) bool { if v, ok := memo[mask]; ok { return v } for i := 0; i < n-1; i++ { if (mask&(1<<i)) == 0 || (mask&(1<<(i+1))) == 0 { continue } if dfs(mask ^ (1 << i) ^ (1 << (i + 1))) { continue } memo[mask] = true return true } memo[mask] = false return false } return dfs(mask) }
294
Flip Game II
Medium
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return <code>true</code> <em>if the starting player can <strong>guarantee a win</strong></em>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The starting player can guarantee a win by flipping the middle &quot;++&quot; to become &quot;+--+&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 60</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Derive your algorithm&#39;s runtime complexity.
Memoization; Math; Dynamic Programming; Backtracking; Game Theory
Java
class Solution { private int n; private Map<Long, Boolean> memo = new HashMap<>(); public boolean canWin(String currentState) { long mask = 0; n = currentState.length(); for (int i = 0; i < n; ++i) { if (currentState.charAt(i) == '+') { mask |= 1 << i; } } return dfs(mask); } private boolean dfs(long mask) { if (memo.containsKey(mask)) { return memo.get(mask); } for (int i = 0; i < n - 1; ++i) { if ((mask & (1 << i)) == 0 || (mask & (1 << (i + 1))) == 0) { continue; } if (dfs(mask ^ (1 << i) ^ (1 << (i + 1)))) { continue; } memo.put(mask, true); return true; } memo.put(mask, false); return false; } }
294
Flip Game II
Medium
<p>You are playing a Flip Game with your friend.</p> <p>You are given a string <code>currentState</code> that contains only <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. You and your friend take turns to flip <strong>two consecutive</strong> <code>&quot;++&quot;</code> into <code>&quot;--&quot;</code>. The game ends when a person can no longer make a move, and therefore the other person will be the winner.</p> <p>Return <code>true</code> <em>if the starting player can <strong>guarantee a win</strong></em>, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;++++&quot; <strong>Output:</strong> true <strong>Explanation:</strong> The starting player can guarantee a win by flipping the middle &quot;++&quot; to become &quot;+--+&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> currentState = &quot;+&quot; <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= currentState.length &lt;= 60</code></li> <li><code>currentState[i]</code> is either <code>&#39;+&#39;</code> or <code>&#39;-&#39;</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Derive your algorithm&#39;s runtime complexity.
Memoization; Math; Dynamic Programming; Backtracking; Game Theory
Python
class Solution: def canWin(self, currentState: str) -> bool: @cache def dfs(mask): for i in range(n - 1): if (mask & (1 << i)) == 0 or (mask & (1 << (i + 1)) == 0): continue if dfs(mask ^ (1 << i) ^ (1 << (i + 1))): continue return True return False mask, n = 0, len(currentState) for i, c in enumerate(currentState): if c == '+': mask |= 1 << i return dfs(mask)
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
C++
class MedianFinder { public: MedianFinder() { } void addNum(int num) { maxQ.push(num); minQ.push(maxQ.top()); maxQ.pop(); if (minQ.size() > maxQ.size() + 1) { maxQ.push(minQ.top()); minQ.pop(); } } double findMedian() { return minQ.size() == maxQ.size() ? (minQ.top() + maxQ.top()) / 2.0 : minQ.top(); } private: priority_queue<int> maxQ; priority_queue<int, vector<int>, greater<int>> minQ; }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
C#
public class MedianFinder { private PriorityQueue<int, int> minQ = new PriorityQueue<int, int>(); private PriorityQueue<int, int> maxQ = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a))); public MedianFinder() { } public void AddNum(int num) { maxQ.Enqueue(num, num); minQ.Enqueue(maxQ.Peek(), maxQ.Dequeue()); if (minQ.Count > maxQ.Count + 1) { maxQ.Enqueue(minQ.Peek(), minQ.Dequeue()); } } public double FindMedian() { return minQ.Count == maxQ.Count ? (minQ.Peek() + maxQ.Peek()) / 2.0 : minQ.Peek(); } } /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.AddNum(num); * double param_2 = obj.FindMedian(); */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
Go
type MedianFinder struct { minq hp maxq hp } func Constructor() MedianFinder { return MedianFinder{hp{}, hp{}} } func (this *MedianFinder) AddNum(num int) { minq, maxq := &this.minq, &this.maxq heap.Push(maxq, -num) heap.Push(minq, -heap.Pop(maxq).(int)) if minq.Len()-maxq.Len() > 1 { heap.Push(maxq, -heap.Pop(minq).(int)) } } func (this *MedianFinder) FindMedian() float64 { minq, maxq := this.minq, this.maxq if minq.Len() == maxq.Len() { return float64(minq.IntSlice[0]-maxq.IntSlice[0]) / 2 } return float64(minq.IntSlice[0]) } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v } /** * Your MedianFinder object will be instantiated and called as such: * obj := Constructor(); * obj.AddNum(num); * param_2 := obj.FindMedian(); */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
Java
class MedianFinder { private PriorityQueue<Integer> minQ = new PriorityQueue<>(); private PriorityQueue<Integer> maxQ = new PriorityQueue<>(Collections.reverseOrder()); public MedianFinder() { } public void addNum(int num) { maxQ.offer(num); minQ.offer(maxQ.poll()); if (minQ.size() - maxQ.size() > 1) { maxQ.offer(minQ.poll()); } } public double findMedian() { return minQ.size() == maxQ.size() ? (minQ.peek() + maxQ.peek()) / 2.0 : minQ.peek(); } } /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
JavaScript
var MedianFinder = function () { this.minQ = new MinPriorityQueue(); this.maxQ = new MaxPriorityQueue(); }; /** * @param {number} num * @return {void} */ MedianFinder.prototype.addNum = function (num) { this.maxQ.enqueue(num); this.minQ.enqueue(this.maxQ.dequeue().element); if (this.minQ.size() - this.maxQ.size() > 1) { this.maxQ.enqueue(this.minQ.dequeue().element); } }; /** * @return {number} */ MedianFinder.prototype.findMedian = function () { if (this.minQ.size() === this.maxQ.size()) { return (this.minQ.front().element + this.maxQ.front().element) / 2; } return this.minQ.front().element; }; /** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
Python
class MedianFinder: def __init__(self): self.minq = [] self.maxq = [] def addNum(self, num: int) -> None: heappush(self.minq, -heappushpop(self.maxq, -num)) if len(self.minq) - len(self.maxq) > 1: heappush(self.maxq, -heappop(self.minq)) def findMedian(self) -> float: if len(self.minq) == len(self.maxq): return (self.minq[0] - self.maxq[0]) / 2 return self.minq[0] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
Rust
use std::cmp::Reverse; use std::collections::BinaryHeap; struct MedianFinder { minQ: BinaryHeap<Reverse<i32>>, maxQ: BinaryHeap<i32>, } impl MedianFinder { fn new() -> Self { MedianFinder { minQ: BinaryHeap::new(), maxQ: BinaryHeap::new(), } } fn add_num(&mut self, num: i32) { self.maxQ.push(num); self.minQ.push(Reverse(self.maxQ.pop().unwrap())); if self.minQ.len() > self.maxQ.len() + 1 { self.maxQ.push(self.minQ.pop().unwrap().0); } } fn find_median(&self) -> f64 { if self.minQ.len() == self.maxQ.len() { let min_top = self.minQ.peek().unwrap().0; let max_top = *self.maxQ.peek().unwrap(); (min_top + max_top) as f64 / 2.0 } else { self.minQ.peek().unwrap().0 as f64 } } }
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
Swift
class MedianFinder { private var minQ = Heap<Int>(sort: <) private var maxQ = Heap<Int>(sort: >) init() { } func addNum(_ num: Int) { maxQ.insert(num) minQ.insert(maxQ.remove()!) if maxQ.count < minQ.count { maxQ.insert(minQ.remove()!) } } func findMedian() -> Double { if maxQ.count > minQ.count { return Double(maxQ.peek()!) } return (Double(maxQ.peek()!) + Double(minQ.peek()!)) / 2.0 } } struct Heap<T> { var elements: [T] let sort: (T, T) -> Bool init(sort: @escaping (T, T) -> Bool, elements: [T] = []) { self.sort = sort self.elements = elements if !elements.isEmpty { for i in stride(from: elements.count / 2 - 1, through: 0, by: -1) { siftDown(from: i) } } } var isEmpty: Bool { return elements.isEmpty } var count: Int { return elements.count } func peek() -> T? { return elements.first } mutating func insert(_ value: T) { elements.append(value) siftUp(from: elements.count - 1) } mutating func remove() -> T? { guard !elements.isEmpty else { return nil } elements.swapAt(0, elements.count - 1) let removedValue = elements.removeLast() siftDown(from: 0) return removedValue } private mutating func siftUp(from index: Int) { var child = index var parent = parentIndex(ofChildAt: child) while child > 0 && sort(elements[child], elements[parent]) { elements.swapAt(child, parent) child = parent parent = parentIndex(ofChildAt: child) } } private mutating func siftDown(from index: Int) { var parent = index while true { let left = leftChildIndex(ofParentAt: parent) let right = rightChildIndex(ofParentAt: parent) var candidate = parent if left < count && sort(elements[left], elements[candidate]) { candidate = left } if right < count && sort(elements[right], elements[candidate]) { candidate = right } if candidate == parent { return } elements.swapAt(parent, candidate) parent = candidate } } private func parentIndex(ofChildAt index: Int) -> Int { return (index - 1) / 2 } private func leftChildIndex(ofParentAt index: Int) -> Int { return 2 * index + 1 } private func rightChildIndex(ofParentAt index: Int) -> Int { return 2 * index + 2 } } /** * Your MedianFinder object will be instantiated and called as such: * let obj = MedianFinder() * obj.addNum(num) * let ret_2: Double = obj.findMedian() */
295
Find Median from Data Stream
Hard
<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p> <ul> <li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li> <li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li> </ul> <p>Implement the MedianFinder class:</p> <ul> <li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li> <li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li> <li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;] [[], [1], [2], [], [3], []] <strong>Output</strong> [null, null, null, 1.5, null, 2.0] <strong>Explanation</strong> MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li> <li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li> <li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> <li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li> </ul>
Design; Two Pointers; Data Stream; Sorting; Heap (Priority Queue)
TypeScript
class MedianFinder { #minQ = new MinPriorityQueue(); #maxQ = new MaxPriorityQueue(); addNum(num: number): void { const [minQ, maxQ] = [this.#minQ, this.#maxQ]; maxQ.enqueue(num); minQ.enqueue(maxQ.dequeue().element); if (minQ.size() - maxQ.size() > 1) { maxQ.enqueue(minQ.dequeue().element); } } findMedian(): number { const [minQ, maxQ] = [this.#minQ, this.#maxQ]; if (minQ.size() === maxQ.size()) { return (minQ.front().element + maxQ.front().element) / 2; } return minQ.front().element; } } /** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
296
Best Meeting Point
Hard
<p>Given an <code>m x n</code> binary grid <code>grid</code> where each <code>1</code> marks the home of one friend, return <em>the minimal <strong>total travel distance</strong></em>.</p> <p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> <p>The distance is calculated using <a href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Manhattan Distance</a>, where <code>distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0296.Best%20Meeting%20Point/images/meetingpoint-grid.jpg" style="width: 413px; height: 253px;" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] <strong>Output:</strong> 6 <strong>Explanation:</strong> Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There will be <strong>at least two</strong> friends in the <code>grid</code>.</li> </ul>
Array; Math; Matrix; Sorting
C++
class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<int> rows; vector<int> cols; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j]) { rows.emplace_back(i); cols.emplace_back(j); } } } sort(cols.begin(), cols.end()); int i = rows[rows.size() / 2]; int j = cols[cols.size() / 2]; auto f = [](vector<int>& arr, int x) { int s = 0; for (int v : arr) { s += abs(v - x); } return s; }; return f(rows, i) + f(cols, j); } };
296
Best Meeting Point
Hard
<p>Given an <code>m x n</code> binary grid <code>grid</code> where each <code>1</code> marks the home of one friend, return <em>the minimal <strong>total travel distance</strong></em>.</p> <p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> <p>The distance is calculated using <a href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Manhattan Distance</a>, where <code>distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0296.Best%20Meeting%20Point/images/meetingpoint-grid.jpg" style="width: 413px; height: 253px;" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] <strong>Output:</strong> 6 <strong>Explanation:</strong> Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There will be <strong>at least two</strong> friends in the <code>grid</code>.</li> </ul>
Array; Math; Matrix; Sorting
Go
func minTotalDistance(grid [][]int) int { rows, cols := []int{}, []int{} for i, row := range grid { for j, v := range row { if v == 1 { rows = append(rows, i) cols = append(cols, j) } } } sort.Ints(cols) i := rows[len(rows)>>1] j := cols[len(cols)>>1] f := func(arr []int, x int) int { s := 0 for _, v := range arr { s += abs(v - x) } return s } return f(rows, i) + f(cols, j) } func abs(x int) int { if x < 0 { return -x } return x }
296
Best Meeting Point
Hard
<p>Given an <code>m x n</code> binary grid <code>grid</code> where each <code>1</code> marks the home of one friend, return <em>the minimal <strong>total travel distance</strong></em>.</p> <p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> <p>The distance is calculated using <a href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Manhattan Distance</a>, where <code>distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0296.Best%20Meeting%20Point/images/meetingpoint-grid.jpg" style="width: 413px; height: 253px;" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] <strong>Output:</strong> 6 <strong>Explanation:</strong> Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There will be <strong>at least two</strong> friends in the <code>grid</code>.</li> </ul>
Array; Math; Matrix; Sorting
Java
class Solution { public int minTotalDistance(int[][] grid) { int m = grid.length, n = grid[0].length; List<Integer> rows = new ArrayList<>(); List<Integer> cols = new ArrayList<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 1) { rows.add(i); cols.add(j); } } } Collections.sort(cols); int i = rows.get(rows.size() >> 1); int j = cols.get(cols.size() >> 1); return f(rows, i) + f(cols, j); } private int f(List<Integer> arr, int x) { int s = 0; for (int v : arr) { s += Math.abs(v - x); } return s; } }
296
Best Meeting Point
Hard
<p>Given an <code>m x n</code> binary grid <code>grid</code> where each <code>1</code> marks the home of one friend, return <em>the minimal <strong>total travel distance</strong></em>.</p> <p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> <p>The distance is calculated using <a href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Manhattan Distance</a>, where <code>distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0296.Best%20Meeting%20Point/images/meetingpoint-grid.jpg" style="width: 413px; height: 253px;" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] <strong>Output:</strong> 6 <strong>Explanation:</strong> Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There will be <strong>at least two</strong> friends in the <code>grid</code>.</li> </ul>
Array; Math; Matrix; Sorting
Python
class Solution: def minTotalDistance(self, grid: List[List[int]]) -> int: def f(arr, x): return sum(abs(v - x) for v in arr) rows, cols = [], [] for i, row in enumerate(grid): for j, v in enumerate(row): if v: rows.append(i) cols.append(j) cols.sort() i = rows[len(rows) >> 1] j = cols[len(cols) >> 1] return f(rows, i) + f(cols, j)
296
Best Meeting Point
Hard
<p>Given an <code>m x n</code> binary grid <code>grid</code> where each <code>1</code> marks the home of one friend, return <em>the minimal <strong>total travel distance</strong></em>.</p> <p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> <p>The distance is calculated using <a href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Manhattan Distance</a>, where <code>distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0296.Best%20Meeting%20Point/images/meetingpoint-grid.jpg" style="width: 413px; height: 253px;" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] <strong>Output:</strong> 6 <strong>Explanation:</strong> Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li>There will be <strong>at least two</strong> friends in the <code>grid</code>.</li> </ul>
Array; Math; Matrix; Sorting
Rust
impl Solution { #[allow(dead_code)] pub fn min_total_distance(grid: Vec<Vec<i32>>) -> i32 { let n = grid.len(); let m = grid[0].len(); let mut row_vec = Vec::new(); let mut col_vec = Vec::new(); // Initialize the two vector for i in 0..n { for j in 0..m { if grid[i][j] == 1 { row_vec.push(i as i32); col_vec.push(j as i32); } } } // Since the row vector is originally sorted, we only need to sort the col vector here col_vec.sort(); Self::compute_manhattan_dis(&row_vec, row_vec[row_vec.len() / 2]) + Self::compute_manhattan_dis(&col_vec, col_vec[col_vec.len() / 2]) } #[allow(dead_code)] fn compute_manhattan_dis(v: &Vec<i32>, e: i32) -> i32 { let mut ret = 0; for num in v { ret += (num - e).abs(); } ret } }
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if (!root) { return ""; } queue<TreeNode*> q{{root}}; string ans; while (!q.empty()) { auto node = q.front(); q.pop(); if (node) { ans += to_string(node->val) + " "; q.push(node->left); q.push(node->right); } else { ans += "# "; } } ans.pop_back(); return ans; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data == "") { return nullptr; } stringstream ss(data); string t; ss >> t; TreeNode* root = new TreeNode(stoi(t)); queue<TreeNode*> q{{root}}; while (!q.empty()) { auto node = q.front(); q.pop(); ss >> t; if (t != "#") { node->left = new TreeNode(stoi(t)); q.push(node->left); } ss >> t; if (t != "#") { node->right = new TreeNode(stoi(t)); q.push(node->right); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public string serialize(TreeNode root) { if (root == null) { return null; } List<string> ans = new List<string>(); Queue<TreeNode> q = new Queue<TreeNode>(); q.Enqueue(root); while (q.Count > 0) { TreeNode node = q.Dequeue(); if (node != null) { ans.Add(node.val.ToString()); q.Enqueue(node.left); q.Enqueue(node.right); } else { ans.Add("#"); } } return string.Join(",", ans); } // Decodes your encoded data to tree. public TreeNode deserialize(string data) { if (data == null) { return null; } string[] vals = data.Split(','); int i = 0; TreeNode root = new TreeNode(int.Parse(vals[i++])); Queue<TreeNode> q = new Queue<TreeNode>(); q.Enqueue(root); while (q.Count > 0) { TreeNode node = q.Dequeue(); if (vals[i] != "#") { node.left = new TreeNode(int.Parse(vals[i])); q.Enqueue(node.left); } i++; if (vals[i] != "#") { node.right = new TreeNode(int.Parse(vals[i])); q.Enqueue(node.right); } i++; } return root; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type Codec struct { } func Constructor() Codec { return Codec{} } // Serializes a tree to a single string. func (this *Codec) serialize(root *TreeNode) string { if root == nil { return "" } q := []*TreeNode{root} ans := []string{} for len(q) > 0 { node := q[0] q = q[1:] if node != nil { ans = append(ans, strconv.Itoa(node.Val)) q = append(q, node.Left) q = append(q, node.Right) } else { ans = append(ans, "#") } } return strings.Join(ans, ",") } // Deserializes your encoded data to tree. func (this *Codec) deserialize(data string) *TreeNode { if data == "" { return nil } vals := strings.Split(data, ",") v, _ := strconv.Atoi(vals[0]) i := 1 root := &TreeNode{Val: v} q := []*TreeNode{root} for len(q) > 0 { node := q[0] q = q[1:] if x, err := strconv.Atoi(vals[i]); err == nil { node.Left = &TreeNode{Val: x} q = append(q, node.Left) } i++ if x, err := strconv.Atoi(vals[i]); err == nil { node.Right = &TreeNode{Val: x} q = append(q, node.Right) } i++ } return root } /** * Your Codec object will be instantiated and called as such: * ser := Constructor(); * deser := Constructor(); * data := ser.serialize(root); * ans := deser.deserialize(data); */
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) { return null; } List<String> ans = new ArrayList<>(); Deque<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { TreeNode node = q.poll(); if (node != null) { ans.add(node.val + ""); q.offer(node.left); q.offer(node.right); } else { ans.add("#"); } } return String.join(",", ans); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data == null) { return null; } String[] vals = data.split(","); int i = 0; TreeNode root = new TreeNode(Integer.valueOf(vals[i++])); Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { TreeNode node = q.poll(); if (!"#".equals(vals[i])) { node.left = new TreeNode(Integer.valueOf(vals[i])); q.offer(node.left); } ++i; if (!"#".equals(vals[i])) { node.right = new TreeNode(Integer.valueOf(vals[i])); q.offer(node.right); } ++i; } return root; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */ var serialize = function (root) { if (root === null) { return null; } const ans = []; const q = [root]; let index = 0; while (index < q.length) { const node = q[index++]; if (node !== null) { ans.push(node.val.toString()); q.push(node.left); q.push(node.right); } else { ans.push('#'); } } return ans.join(','); }; /** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */ var deserialize = function (data) { if (data === null) { return null; } const vals = data.split(','); let i = 0; const root = new TreeNode(parseInt(vals[i++])); const q = [root]; let index = 0; while (index < q.length) { const node = q[index++]; if (vals[i] !== '#') { node.left = new TreeNode(+vals[i]); q.push(node.left); } i++; if (vals[i] !== '#') { node.right = new TreeNode(+vals[i]); q.push(node.right); } i++; } return root; }; /** * Your functions will be called as such: * deserialize(serialize(root)); */
297
Serialize and Deserialize Binary Tree
Hard
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p> <p><strong>Clarification:</strong> The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/images/serdeser.jpg" style="width: 442px; height: 324px;" /> <pre> <strong>Input:</strong> root = [1,2,3,null,null,4,5] <strong>Output:</strong> [1,2,3,null,null,4,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </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>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; String; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return "" q = deque([root]) ans = [] while q: node = q.popleft() if node: ans.append(str(node.val)) q.append(node.left) q.append(node.right) else: ans.append("#") return ",".join(ans) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if not data: return None vals = data.split(",") root = TreeNode(int(vals[0])) q = deque([root]) i = 1 while q: node = q.popleft() if vals[i] != "#": node.left = TreeNode(int(vals[i])) q.append(node.left) i += 1 if vals[i] != "#": node.right = TreeNode(int(vals[i])) q.append(node.right) i += 1 return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
298
Binary Tree Longest Consecutive Sequence
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest <strong>consecutive sequence path</strong></em>.</p> <p>A <strong>consecutive sequence path</strong> is a path where the values <strong>increase by one</strong> along the path.</p> <p>Note that the path can start <strong>at any node</strong> in the tree, and you cannot go from a node to its parent in the path.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-1-tree.jpg" style="width: 306px; height: 400px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-2-tree.jpg" style="width: 249px; height: 400px;" /> <pre> <strong>Input:</strong> root = [2,null,3,2,null,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int longestConsecutive(TreeNode* root) { int ans = 0; function<int(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return 0; } int l = dfs(root->left) + 1; int r = dfs(root->right) + 1; if (root->left && root->left->val - root->val != 1) { l = 1; } if (root->right && root->right->val - root->val != 1) { r = 1; } int t = max(l, r); ans = max(ans, t); return t; }; dfs(root); return ans; } };
298
Binary Tree Longest Consecutive Sequence
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest <strong>consecutive sequence path</strong></em>.</p> <p>A <strong>consecutive sequence path</strong> is a path where the values <strong>increase by one</strong> along the path.</p> <p>Note that the path can start <strong>at any node</strong> in the tree, and you cannot go from a node to its parent in the path.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-1-tree.jpg" style="width: 306px; height: 400px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-2-tree.jpg" style="width: 249px; height: 400px;" /> <pre> <strong>Input:</strong> root = [2,null,3,2,null,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func longestConsecutive(root *TreeNode) (ans int) { var dfs func(*TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } l := dfs(root.Left) + 1 r := dfs(root.Right) + 1 if root.Left != nil && root.Left.Val-root.Val != 1 { l = 1 } if root.Right != nil && root.Right.Val-root.Val != 1 { r = 1 } t := max(l, r) ans = max(ans, t) return t } dfs(root) return }
298
Binary Tree Longest Consecutive Sequence
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest <strong>consecutive sequence path</strong></em>.</p> <p>A <strong>consecutive sequence path</strong> is a path where the values <strong>increase by one</strong> along the path.</p> <p>Note that the path can start <strong>at any node</strong> in the tree, and you cannot go from a node to its parent in the path.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-1-tree.jpg" style="width: 306px; height: 400px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-2-tree.jpg" style="width: 249px; height: 400px;" /> <pre> <strong>Input:</strong> root = [2,null,3,2,null,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans; public int longestConsecutive(TreeNode root) { dfs(root); return ans; } private int dfs(TreeNode root) { if (root == null) { return 0; } int l = dfs(root.left) + 1; int r = dfs(root.right) + 1; if (root.left != null && root.left.val - root.val != 1) { l = 1; } if (root.right != null && root.right.val - root.val != 1) { r = 1; } int t = Math.max(l, r); ans = Math.max(ans, t); return t; } }
298
Binary Tree Longest Consecutive Sequence
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest <strong>consecutive sequence path</strong></em>.</p> <p>A <strong>consecutive sequence path</strong> is a path where the values <strong>increase by one</strong> along the path.</p> <p>Note that the path can start <strong>at any node</strong> in the tree, and you cannot go from a node to its parent in the path.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-1-tree.jpg" style="width: 306px; height: 400px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-2-tree.jpg" style="width: 249px; height: 400px;" /> <pre> <strong>Input:</strong> root = [2,null,3,2,null,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestConsecutive(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l = dfs(root.left) + 1 r = dfs(root.right) + 1 if root.left and root.left.val - root.val != 1: l = 1 if root.right and root.right.val - root.val != 1: r = 1 t = max(l, r) nonlocal ans ans = max(ans, t) return t ans = 0 dfs(root) return ans
298
Binary Tree Longest Consecutive Sequence
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest <strong>consecutive sequence path</strong></em>.</p> <p>A <strong>consecutive sequence path</strong> is a path where the values <strong>increase by one</strong> along the path.</p> <p>Note that the path can start <strong>at any node</strong> in the tree, and you cannot go from a node to its parent in the path.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-1-tree.jpg" style="width: 306px; height: 400px;" /> <pre> <strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/images/consec1-2-tree.jpg" style="width: 249px; height: 400px;" /> <pre> <strong>Input:</strong> root = [2,null,3,2,null,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li> <li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function longestConsecutive(root: TreeNode | null): number { let ans = 0; const dfs = (root: TreeNode | null): number => { if (root === null) { return 0; } let l = dfs(root.left) + 1; let r = dfs(root.right) + 1; if (root.left && root.left.val - root.val !== 1) { l = 1; } if (root.right && root.right.val - root.val !== 1) { r = 1; } const t = Math.max(l, r); ans = Math.max(ans, t); return t; }; dfs(root); return ans; }
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
C++
class Solution { public: string getHint(string secret, string guess) { int x = 0, y = 0; int cnt1[10]{}; int cnt2[10]{}; for (int i = 0; i < secret.size(); ++i) { int a = secret[i] - '0', b = guess[i] - '0'; if (a == b) { ++x; } else { ++cnt1[a]; ++cnt2[b]; } } for (int i = 0; i < 10; ++i) { y += min(cnt1[i], cnt2[i]); } return to_string(x) + "A" + to_string(y) + "B"; } };
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
Go
func getHint(secret string, guess string) string { x, y := 0, 0 cnt1 := [10]int{} cnt2 := [10]int{} for i, c := range secret { a, b := int(c-'0'), int(guess[i]-'0') if a == b { x++ } else { cnt1[a]++ cnt2[b]++ } } for i, c := range cnt1 { y += min(c, cnt2[i]) } return fmt.Sprintf("%dA%dB", x, y) }
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
Java
class Solution { public String getHint(String secret, String guess) { int x = 0, y = 0; int[] cnt1 = new int[10]; int[] cnt2 = new int[10]; for (int i = 0; i < secret.length(); ++i) { int a = secret.charAt(i) - '0', b = guess.charAt(i) - '0'; if (a == b) { ++x; } else { ++cnt1[a]; ++cnt2[b]; } } for (int i = 0; i < 10; ++i) { y += Math.min(cnt1[i], cnt2[i]); } return String.format("%dA%dB", x, y); } }
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
PHP
class Solution { /** * @param String $secret * @param String $guess * @return String */ function getHint($secret, $guess) { $cnt1 = array_fill(0, 10, 0); $cnt2 = array_fill(0, 10, 0); $x = 0; for ($i = 0; $i < strlen($secret); ++$i) { if ($secret[$i] === $guess[$i]) { ++$x; } else { ++$cnt1[(int) $secret[$i]]; ++$cnt2[(int) $guess[$i]]; } } $y = 0; for ($i = 0; $i < 10; ++$i) { $y += min($cnt1[$i], $cnt2[$i]); } return "{$x}A{$y}B"; } }
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
Python
class Solution: def getHint(self, secret: str, guess: str) -> str: cnt1, cnt2 = Counter(), Counter() x = 0 for a, b in zip(secret, guess): if a == b: x += 1 else: cnt1[a] += 1 cnt2[b] += 1 y = sum(min(cnt1[c], cnt2[c]) for c in cnt1) return f"{x}A{y}B"
299
Bulls and Cows
Medium
<p>You are playing the <strong><a href="https://en.wikipedia.org/wiki/Bulls_and_Cows" target="_blank">Bulls and Cows</a></strong> game with your friend.</p> <p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p> <ul> <li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li> <li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li> </ul> <p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p> <p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot; <strong>Output:</strong> &quot;1A3B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1807&quot; | &quot;<u>7</u>8<u>10</u>&quot;</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot; <strong>Output:</strong> &quot;1A1B&quot; <strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined: &quot;1123&quot; &quot;1123&quot; | or | &quot;01<u>1</u>1&quot; &quot;011<u>1</u>&quot; Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li> <li><code>secret.length == guess.length</code></li> <li><code>secret</code> and <code>guess</code> consist of digits only.</li> </ul>
Hash Table; String; Counting
TypeScript
function getHint(secret: string, guess: string): string { const cnt1: number[] = Array(10).fill(0); const cnt2: number[] = Array(10).fill(0); let x: number = 0; for (let i = 0; i < secret.length; ++i) { if (secret[i] === guess[i]) { ++x; } else { ++cnt1[+secret[i]]; ++cnt2[+guess[i]]; } } let y: number = 0; for (let i = 0; i < 10; ++i) { y += Math.min(cnt1[i], cnt2[i]); } return `${x}A${y}B`; }
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
C++
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); vector<int> f(n, 1); for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) { f[i] = max(f[i], f[j] + 1); } } } return *max_element(f.begin(), f.end()); } };
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
Go
func lengthOfLIS(nums []int) int { n := len(nums) f := make([]int, n) for i := range f { f[i] = 1 } ans := 1 for i := 1; i < n; i++ { for j := 0; j < i; j++ { if nums[j] < nums[i] { f[i] = max(f[i], f[j]+1) ans = max(ans, f[i]) } } } return ans }
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
Java
class Solution { public int lengthOfLIS(int[] nums) { int n = nums.length; int[] f = new int[n]; Arrays.fill(f, 1); int ans = 1; for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) { f[i] = Math.max(f[i], f[j] + 1); } } ans = Math.max(ans, f[i]); } return ans; } }
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
Python
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) f = [1] * n for i in range(1, n): for j in range(i): if nums[j] < nums[i]: f[i] = max(f[i], f[j] + 1) return max(f)
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
Rust
impl Solution { pub fn length_of_lis(nums: Vec<i32>) -> i32 { let n = nums.len(); let mut f = vec![1; n]; for i in 1..n { for j in 0..i { if nums[j] < nums[i] { f[i] = f[i].max(f[j] + 1); } } } *f.iter().max().unwrap() } }
300
Longest Increasing Subsequence
Medium
<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword="subsequence-array"><em><strong>subsequence</strong></em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,9,2,5,3,7,101,18] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,0,3,2,3] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7,7,7] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2500</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
Array; Binary Search; Dynamic Programming
TypeScript
function lengthOfLIS(nums: number[]): number { const n = nums.length; const f: number[] = new Array(n).fill(1); for (let i = 1; i < n; ++i) { for (let j = 0; j < i; ++j) { if (nums[j] < nums[i]) { f[i] = Math.max(f[i], f[j] + 1); } } } return Math.max(...f); }
301
Remove Invalid Parentheses
Hard
<p>Given a string <code>s</code> that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p> <p>Return <em>a list of <strong>unique strings</strong> that are valid with the minimum number of removals</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;()())()&quot; <strong>Output:</strong> [&quot;(())()&quot;,&quot;()()()&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;(a)())()&quot; <strong>Output:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;)(&quot; <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 25</code></li> <li><code>s</code> consists of lowercase English letters and parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>.</li> <li>There will be at most <code>20</code> parentheses in <code>s</code>.</li> </ul>
Breadth-First Search; String; Backtracking
C++
class Solution { public: vector<string> removeInvalidParentheses(string s) { unordered_set<string> ans; int l = 0, r = 0, n = s.size(); for (char& c : s) { if (c == '(') { ++l; } else if (c == ')') { if (l) { --l; } else { ++r; } } } function<void(int, int, int, int, int, string)> dfs; dfs = [&](int i, int l, int r, int lcnt, int rcnt, string t) { if (i == n) { if (l == 0 && r == 0) { ans.insert(t); } return; } if (n - i < l + r || lcnt < rcnt) { return; } if (s[i] == '(' && l) { dfs(i + 1, l - 1, r, lcnt, rcnt, t); } if (s[i] == ')' && r) { dfs(i + 1, l, r - 1, lcnt, rcnt, t); } int x = s[i] == '(' ? 1 : 0; int y = s[i] == ')' ? 1 : 0; dfs(i + 1, l, r, lcnt + x, rcnt + y, t + s[i]); }; dfs(0, l, r, 0, 0, ""); return vector<string>(ans.begin(), ans.end()); } };
301
Remove Invalid Parentheses
Hard
<p>Given a string <code>s</code> that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p> <p>Return <em>a list of <strong>unique strings</strong> that are valid with the minimum number of removals</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;()())()&quot; <strong>Output:</strong> [&quot;(())()&quot;,&quot;()()()&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;(a)())()&quot; <strong>Output:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;)(&quot; <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 25</code></li> <li><code>s</code> consists of lowercase English letters and parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>.</li> <li>There will be at most <code>20</code> parentheses in <code>s</code>.</li> </ul>
Breadth-First Search; String; Backtracking
Go
func removeInvalidParentheses(s string) []string { vis := map[string]bool{} l, r, n := 0, 0, len(s) for _, c := range s { if c == '(' { l++ } else if c == ')' { if l > 0 { l-- } else { r++ } } } var dfs func(i, l, r, lcnt, rcnt int, t string) dfs = func(i, l, r, lcnt, rcnt int, t string) { if i == n { if l == 0 && r == 0 { vis[t] = true } return } if n-i < l+r || lcnt < rcnt { return } if s[i] == '(' && l > 0 { dfs(i+1, l-1, r, lcnt, rcnt, t) } if s[i] == ')' && r > 0 { dfs(i+1, l, r-1, lcnt, rcnt, t) } x, y := 0, 0 if s[i] == '(' { x = 1 } else if s[i] == ')' { y = 1 } dfs(i+1, l, r, lcnt+x, rcnt+y, t+string(s[i])) } dfs(0, l, r, 0, 0, "") ans := make([]string, 0, len(vis)) for v := range vis { ans = append(ans, v) } return ans }
301
Remove Invalid Parentheses
Hard
<p>Given a string <code>s</code> that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p> <p>Return <em>a list of <strong>unique strings</strong> that are valid with the minimum number of removals</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;()())()&quot; <strong>Output:</strong> [&quot;(())()&quot;,&quot;()()()&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;(a)())()&quot; <strong>Output:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;)(&quot; <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 25</code></li> <li><code>s</code> consists of lowercase English letters and parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>.</li> <li>There will be at most <code>20</code> parentheses in <code>s</code>.</li> </ul>
Breadth-First Search; String; Backtracking
Java
class Solution { private String s; private int n; private Set<String> ans = new HashSet<>(); public List<String> removeInvalidParentheses(String s) { this.s = s; this.n = s.length(); int l = 0, r = 0; for (char c : s.toCharArray()) { if (c == '(') { ++l; } else if (c == ')') { if (l > 0) { --l; } else { ++r; } } } dfs(0, l, r, 0, 0, ""); return new ArrayList<>(ans); } private void dfs(int i, int l, int r, int lcnt, int rcnt, String t) { if (i == n) { if (l == 0 && r == 0) { ans.add(t); } return; } if (n - i < l + r || lcnt < rcnt) { return; } char c = s.charAt(i); if (c == '(' && l > 0) { dfs(i + 1, l - 1, r, lcnt, rcnt, t); } if (c == ')' && r > 0) { dfs(i + 1, l, r - 1, lcnt, rcnt, t); } int x = c == '(' ? 1 : 0; int y = c == ')' ? 1 : 0; dfs(i + 1, l, r, lcnt + x, rcnt + y, t + c); } }
301
Remove Invalid Parentheses
Hard
<p>Given a string <code>s</code> that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p> <p>Return <em>a list of <strong>unique strings</strong> that are valid with the minimum number of removals</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;()())()&quot; <strong>Output:</strong> [&quot;(())()&quot;,&quot;()()()&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;(a)())()&quot; <strong>Output:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;)(&quot; <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 25</code></li> <li><code>s</code> consists of lowercase English letters and parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>.</li> <li>There will be at most <code>20</code> parentheses in <code>s</code>.</li> </ul>
Breadth-First Search; String; Backtracking
Python
class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: def dfs(i, l, r, lcnt, rcnt, t): if i == n: if l == 0 and r == 0: ans.add(t) return if n - i < l + r or lcnt < rcnt: return if s[i] == '(' and l: dfs(i + 1, l - 1, r, lcnt, rcnt, t) elif s[i] == ')' and r: dfs(i + 1, l, r - 1, lcnt, rcnt, t) dfs(i + 1, l, r, lcnt + (s[i] == '('), rcnt + (s[i] == ')'), t + s[i]) l = r = 0 for c in s: if c == '(': l += 1 elif c == ')': if l: l -= 1 else: r += 1 ans = set() n = len(s) dfs(0, l, r, 0, 0, '') return list(ans)
302
Smallest Rectangle Enclosing Black Pixels
Hard
<p>You are given an <code>m x n</code> binary matrix <code>image</code> where <code>0</code> represents a white pixel and <code>1</code> represents a black pixel.</p> <p>The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.</p> <p>Given two integers <code>x</code> and <code>y</code> that represents the location of one of the black pixels, return <em>the area of the smallest (axis-aligned) rectangle that encloses all black pixels</em>.</p> <p>You must write an algorithm with less than <code>O(mn)</code> runtime complexity</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0302.Smallest%20Rectangle%20Enclosing%20Black%20Pixels/images/pixel-grid.jpg" style="width: 333px; height: 253px;" /> <pre> <strong>Input:</strong> image = [[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;]], x = 0, y = 2 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> image = [[&quot;1&quot;]], x = 0, y = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == image.length</code></li> <li><code>n == image[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>image[i][j]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>image[x][y] == &#39;1&#39;.</code></li> <li>The black pixels in the <code>image</code> only form <strong>one component</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Binary Search; Matrix
C++
class Solution { public: int minArea(vector<vector<char>>& image, int x, int y) { int m = image.size(), n = image[0].size(); int left = 0, right = x; while (left < right) { int mid = (left + right) >> 1; int c = 0; while (c < n && image[mid][c] == '0') ++c; if (c < n) right = mid; else left = mid + 1; } int u = left; left = x; right = m - 1; while (left < right) { int mid = (left + right + 1) >> 1; int c = 0; while (c < n && image[mid][c] == '0') ++c; if (c < n) left = mid; else right = mid - 1; } int d = left; left = 0; right = y; while (left < right) { int mid = (left + right) >> 1; int r = 0; while (r < m && image[r][mid] == '0') ++r; if (r < m) right = mid; else left = mid + 1; } int l = left; left = y; right = n - 1; while (left < right) { int mid = (left + right + 1) >> 1; int r = 0; while (r < m && image[r][mid] == '0') ++r; if (r < m) left = mid; else right = mid - 1; } int r = left; return (d - u + 1) * (r - l + 1); } };
302
Smallest Rectangle Enclosing Black Pixels
Hard
<p>You are given an <code>m x n</code> binary matrix <code>image</code> where <code>0</code> represents a white pixel and <code>1</code> represents a black pixel.</p> <p>The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.</p> <p>Given two integers <code>x</code> and <code>y</code> that represents the location of one of the black pixels, return <em>the area of the smallest (axis-aligned) rectangle that encloses all black pixels</em>.</p> <p>You must write an algorithm with less than <code>O(mn)</code> runtime complexity</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0302.Smallest%20Rectangle%20Enclosing%20Black%20Pixels/images/pixel-grid.jpg" style="width: 333px; height: 253px;" /> <pre> <strong>Input:</strong> image = [[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;]], x = 0, y = 2 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> image = [[&quot;1&quot;]], x = 0, y = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == image.length</code></li> <li><code>n == image[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>image[i][j]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>image[x][y] == &#39;1&#39;.</code></li> <li>The black pixels in the <code>image</code> only form <strong>one component</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Binary Search; Matrix
Go
func minArea(image [][]byte, x int, y int) int { m, n := len(image), len(image[0]) left, right := 0, x for left < right { mid := (left + right) >> 1 c := 0 for c < n && image[mid][c] == '0' { c++ } if c < n { right = mid } else { left = mid + 1 } } u := left left, right = x, m-1 for left < right { mid := (left + right + 1) >> 1 c := 0 for c < n && image[mid][c] == '0' { c++ } if c < n { left = mid } else { right = mid - 1 } } d := left left, right = 0, y for left < right { mid := (left + right) >> 1 r := 0 for r < m && image[r][mid] == '0' { r++ } if r < m { right = mid } else { left = mid + 1 } } l := left left, right = y, n-1 for left < right { mid := (left + right + 1) >> 1 r := 0 for r < m && image[r][mid] == '0' { r++ } if r < m { left = mid } else { right = mid - 1 } } r := left return (d - u + 1) * (r - l + 1) }
302
Smallest Rectangle Enclosing Black Pixels
Hard
<p>You are given an <code>m x n</code> binary matrix <code>image</code> where <code>0</code> represents a white pixel and <code>1</code> represents a black pixel.</p> <p>The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.</p> <p>Given two integers <code>x</code> and <code>y</code> that represents the location of one of the black pixels, return <em>the area of the smallest (axis-aligned) rectangle that encloses all black pixels</em>.</p> <p>You must write an algorithm with less than <code>O(mn)</code> runtime complexity</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0302.Smallest%20Rectangle%20Enclosing%20Black%20Pixels/images/pixel-grid.jpg" style="width: 333px; height: 253px;" /> <pre> <strong>Input:</strong> image = [[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;]], x = 0, y = 2 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> image = [[&quot;1&quot;]], x = 0, y = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == image.length</code></li> <li><code>n == image[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>image[i][j]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>image[x][y] == &#39;1&#39;.</code></li> <li>The black pixels in the <code>image</code> only form <strong>one component</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Binary Search; Matrix
Java
class Solution { public int minArea(char[][] image, int x, int y) { int m = image.length, n = image[0].length; int left = 0, right = x; while (left < right) { int mid = (left + right) >> 1; int c = 0; while (c < n && image[mid][c] == '0') { ++c; } if (c < n) { right = mid; } else { left = mid + 1; } } int u = left; left = x; right = m - 1; while (left < right) { int mid = (left + right + 1) >> 1; int c = 0; while (c < n && image[mid][c] == '0') { ++c; } if (c < n) { left = mid; } else { right = mid - 1; } } int d = left; left = 0; right = y; while (left < right) { int mid = (left + right) >> 1; int r = 0; while (r < m && image[r][mid] == '0') { ++r; } if (r < m) { right = mid; } else { left = mid + 1; } } int l = left; left = y; right = n - 1; while (left < right) { int mid = (left + right + 1) >> 1; int r = 0; while (r < m && image[r][mid] == '0') { ++r; } if (r < m) { left = mid; } else { right = mid - 1; } } int r = left; return (d - u + 1) * (r - l + 1); } }
302
Smallest Rectangle Enclosing Black Pixels
Hard
<p>You are given an <code>m x n</code> binary matrix <code>image</code> where <code>0</code> represents a white pixel and <code>1</code> represents a black pixel.</p> <p>The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.</p> <p>Given two integers <code>x</code> and <code>y</code> that represents the location of one of the black pixels, return <em>the area of the smallest (axis-aligned) rectangle that encloses all black pixels</em>.</p> <p>You must write an algorithm with less than <code>O(mn)</code> runtime complexity</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0302.Smallest%20Rectangle%20Enclosing%20Black%20Pixels/images/pixel-grid.jpg" style="width: 333px; height: 253px;" /> <pre> <strong>Input:</strong> image = [[&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;]], x = 0, y = 2 <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> image = [[&quot;1&quot;]], x = 0, y = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == image.length</code></li> <li><code>n == image[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 100</code></li> <li><code>image[i][j]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>image[x][y] == &#39;1&#39;.</code></li> <li>The black pixels in the <code>image</code> only form <strong>one component</strong>.</li> </ul>
Depth-First Search; Breadth-First Search; Array; Binary Search; Matrix
Python
class Solution: def minArea(self, image: List[List[str]], x: int, y: int) -> int: m, n = len(image), len(image[0]) left, right = 0, x while left < right: mid = (left + right) >> 1 c = 0 while c < n and image[mid][c] == '0': c += 1 if c < n: right = mid else: left = mid + 1 u = left left, right = x, m - 1 while left < right: mid = (left + right + 1) >> 1 c = 0 while c < n and image[mid][c] == '0': c += 1 if c < n: left = mid else: right = mid - 1 d = left left, right = 0, y while left < right: mid = (left + right) >> 1 r = 0 while r < m and image[r][mid] == '0': r += 1 if r < m: right = mid else: left = mid + 1 l = left left, right = y, n - 1 while left < right: mid = (left + right + 1) >> 1 r = 0 while r < m and image[r][mid] == '0': r += 1 if r < m: left = mid else: right = mid - 1 r = left return (d - u + 1) * (r - l + 1)
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
C
typedef struct { int* s; } NumArray; NumArray* numArrayCreate(int* nums, int n) { int* s = malloc(sizeof(int) * (n + 1)); s[0] = 0; for (int i = 0; i < n; i++) { s[i + 1] = s[i] + nums[i]; } NumArray* obj = malloc(sizeof(NumArray)); obj->s = s; return obj; } int numArraySumRange(NumArray* obj, int left, int right) { return obj->s[right + 1] - obj->s[left]; } void numArrayFree(NumArray* obj) { free(obj->s); free(obj); } /** * Your NumArray struct will be instantiated and called as such: * NumArray* obj = numArrayCreate(nums, numsSize); * int param_1 = numArraySumRange(obj, left, right); * numArrayFree(obj); */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
C++
class NumArray { public: NumArray(vector<int>& nums) { int n = nums.size(); s.resize(n + 1); for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } } int sumRange(int left, int right) { return s[right + 1] - s[left]; } private: vector<int> s; }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(left,right); */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
Go
type NumArray struct { s []int } func Constructor(nums []int) NumArray { n := len(nums) s := make([]int, n+1) for i, v := range nums { s[i+1] = s[i] + v } return NumArray{s} } func (this *NumArray) SumRange(left int, right int) int { return this.s[right+1] - this.s[left] } /** * Your NumArray object will be instantiated and called as such: * obj := Constructor(nums); * param_1 := obj.SumRange(left,right); */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
Java
class NumArray { private int[] s; public NumArray(int[] nums) { int n = nums.length; s = new int[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } } public int sumRange(int left, int right) { return s[right + 1] - s[left]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(left,right); */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
JavaScript
/** * @param {number[]} nums */ var NumArray = function (nums) { const n = nums.length; this.s = Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { this.s[i + 1] = this.s[i] + nums[i]; } }; /** * @param {number} left * @param {number} right * @return {number} */ NumArray.prototype.sumRange = function (left, right) { return this.s[right + 1] - this.s[left]; }; /** * Your NumArray object will be instantiated and called as such: * var obj = new NumArray(nums) * var param_1 = obj.sumRange(left,right) */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
Kotlin
class NumArray(nums: IntArray) { private val prefix_sums: IntArray init { val nums_size = nums.size this.prefix_sums = IntArray(nums_size + 1) for (i in 0..<nums_size) { this.prefix_sums[i + 1] = this.prefix_sums[i] + nums[i] } } fun sumRange(left: Int, right: Int): Int = this.prefix_sums[right + 1] - this.prefix_sums[left] } /** * Your NumArray object will be instantiated and called as such: var obj = NumArray(nums) var * param_1 = obj.sumRange(left,right) */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
PHP
class NumArray { /** * @param Integer[] $nums */ function __construct($nums) { $this->s = [0]; foreach ($nums as $x) { $this->s[] = $this->s[count($this->s) - 1] + $x; } } /** * @param Integer $left * @param Integer $right * @return Integer */ function sumRange($left, $right) { return $this->s[$right + 1] - $this->s[$left]; } } /** * Your NumArray object will be instantiated and called as such: * $obj = NumArray($nums); * $ret_1 = $obj->sumRange($left, $right); */
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
Python
class NumArray: def __init__(self, nums: List[int]): self.s = list(accumulate(nums, initial=0)) def sumRange(self, left: int, right: int) -> int: return self.s[right + 1] - self.s[left] # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(left,right)
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
Rust
struct NumArray { s: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl NumArray { fn new(mut nums: Vec<i32>) -> Self { let n = nums.len(); let mut s = vec![0; n + 1]; for i in 0..n { s[i + 1] = s[i] + nums[i]; } Self { s } } fn sum_range(&self, left: i32, right: i32) -> i32 { self.s[(right + 1) as usize] - self.s[left as usize] } }
303
Range Sum Query - Immutable
Easy
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p> <ol> <li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li> </ol> <p>Implement the <code>NumArray</code> class:</p> <ul> <li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] <strong>Output</strong> [null, 1, -1, -3] <strong>Explanation</strong> NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 </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>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li> </ul>
Design; Array; Prefix Sum
TypeScript
class NumArray { private s: number[]; constructor(nums: number[]) { const n = nums.length; this.s = Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { this.s[i + 1] = this.s[i] + nums[i]; } } sumRange(left: number, right: number): number { return this.s[right + 1] - this.s[left]; } } /** * Your NumArray object will be instantiated and called as such: * var obj = new NumArray(nums) * var param_1 = obj.sumRange(left,right) */
304
Range Sum Query 2D - Immutable
Medium
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> <ul> <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>Implement the <code>NumMatrix</code> class:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" /> <pre> <strong>Input</strong> [&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] <strong>Output</strong> [null, 8, 11, 12] <strong>Explanation</strong> NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> </ul>
Design; Array; Matrix; Prefix Sum
C++
class NumMatrix { public: vector<vector<int>> s; NumMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); s.resize(m + 1, vector<int>(n + 1)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + matrix[i][j]; } } } int sumRegion(int row1, int col1, int row2, int col2) { return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; } }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */
304
Range Sum Query 2D - Immutable
Medium
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> <ul> <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>Implement the <code>NumMatrix</code> class:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" /> <pre> <strong>Input</strong> [&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] <strong>Output</strong> [null, 8, 11, 12] <strong>Explanation</strong> NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> </ul>
Design; Array; Matrix; Prefix Sum
Go
type NumMatrix struct { s [][]int } func Constructor(matrix [][]int) NumMatrix { m, n := len(matrix), len(matrix[0]) s := make([][]int, m+1) for i := range s { s[i] = make([]int, n+1) } for i, row := range matrix { for j, v := range row { s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + v } } return NumMatrix{s} } func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { return this.s[row2+1][col2+1] - this.s[row2+1][col1] - this.s[row1][col2+1] + this.s[row1][col1] } /** * Your NumMatrix object will be instantiated and called as such: * obj := Constructor(matrix); * param_1 := obj.SumRegion(row1,col1,row2,col2); */
304
Range Sum Query 2D - Immutable
Medium
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> <ul> <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>Implement the <code>NumMatrix</code> class:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" /> <pre> <strong>Input</strong> [&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] <strong>Output</strong> [null, 8, 11, 12] <strong>Explanation</strong> NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> </ul>
Design; Array; Matrix; Prefix Sum
Java
class NumMatrix { private int[][] s; public NumMatrix(int[][] matrix) { int m = matrix.length, n = matrix[0].length; s = new int[m + 1][n + 1]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + matrix[i][j]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { return s[row2 + 1][col2 + 1] - s[row2 + 1][col1] - s[row1][col2 + 1] + s[row1][col1]; } } /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */
304
Range Sum Query 2D - Immutable
Medium
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> <ul> <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>Implement the <code>NumMatrix</code> class:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" /> <pre> <strong>Input</strong> [&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] <strong>Output</strong> [null, 8, 11, 12] <strong>Explanation</strong> NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> </ul>
Design; Array; Matrix; Prefix Sum
JavaScript
/** * @param {number[][]} matrix */ var NumMatrix = function (matrix) { const m = matrix.length; const n = matrix[0].length; this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { this.s[i + 1][j + 1] = this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j]; } } }; /** * @param {number} row1 * @param {number} col1 * @param {number} row2 * @param {number} col2 * @return {number} */ NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) { return ( this.s[row2 + 1][col2 + 1] - this.s[row2 + 1][col1] - this.s[row1][col2 + 1] + this.s[row1][col1] ); }; /** * Your NumMatrix object will be instantiated and called as such: * var obj = new NumMatrix(matrix) * var param_1 = obj.sumRegion(row1,col1,row2,col2) */
304
Range Sum Query 2D - Immutable
Medium
<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p> <ul> <li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>Implement the <code>NumMatrix</code> class:</p> <ul> <li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li> <li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li> </ul> <p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/images/sum-grid.jpg" style="width: 415px; height: 415px;" /> <pre> <strong>Input</strong> [&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;] [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] <strong>Output</strong> [null, 8, 11, 12] <strong>Explanation</strong> NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li> <li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li> </ul>
Design; Array; Matrix; Prefix Sum
Kotlin
class NumMatrix(matrix: Array<IntArray>) { private val n: Int private val m: Int private val matrix: Array<IntArray> private val prefix_sums_matrix: Array<IntArray> private var initialized: Boolean init { this.n = matrix.size this.m = matrix[0].size this.matrix = matrix this.prefix_sums_matrix = Array(n + 1) { IntArray(m + 1) } this.initialized = false } fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { this.init() return this.prefix_sums_matrix[row2 + 1][col2 + 1] - this.prefix_sums_matrix[row2 + 1][col1] - this.prefix_sums_matrix[row1][col2 + 1] + this.prefix_sums_matrix[row1][col1] } private fun init(): Boolean { if (!this.initialized) { for (i in 0..<this.n) { for (j in 0..<this.m) { this.prefix_sums_matrix[i + 1][j + 1] = this.prefix_sums_matrix[i + 1][j] + this.prefix_sums_matrix[i][j + 1] - this.prefix_sums_matrix[i][j] + this.matrix[i][j] } } this.initialized = true return true } return false } } /** * Your NumMatrix object will be instantiated and called as such: var obj = NumMatrix(matrix) var * param_1 = obj.sumRegion(row1,col1,row2,col2) */